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

...
Автор SHA1 Повідомлення Дата
l0ng-ai 0ecf2bcf52 fix(build): never wipe an artifact's chosen output folder 2026-11-16 18:22:03 +08:00
LU XIANGRUIтаwildcatDownstairs 0a8df16941 fix(terminal): show URLs as links without hovering (#3720)
With Highlight hyperlinks on, terminal URLs only got their underline from xterm's link provider while hovered, so they looked like plain text. Visible URLs now get xterm decorations in the theme's link colour with an underline (viewport-only scan coalesced per frame, rebuilt on theme or setting changes, off in the alternate buffer), in the main and embedded terminals. Link hit ranges were computed from string offsets, so wide CJK characters before a link shifted its hover and click area; both now use cell columns.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-16 17:53:28 +08:00
Yann 6dcece3081 fix(agents): confirm Codex project trust before loading sessions (#3711)
Codex keeps its own project trust decision, so a project trusted in the IDE could still have its project-local .codex configuration (MCP servers, hooks, exec policies) disabled, and the Codex adapter dropped Codex's configWarning and warning notifications. Those warnings now reach the task, including ones sent before a session exists. When Codex reports the current project's .codex layer disabled, starting, resuming or forking a session first asks Trust Project in Codex / Keep Untrusted; only an explicit confirmation writes that project's trust entry through Codex's config API (with the user layer's version), Full Access doesn't bypass the question and side chats deny it.

Co-authored-by: YannABC <[email protected]>
2026-11-16 17:51:05 +08:00
Nc 5c59566897 fix(editor): autosave editable diff views when focus leaves (#3724)
Attached document views (the editable side of a diff, file previews) synchronized the buffer but never saved on blur, so an edit in a diff stayed unsaved on disk (e.g. removing an added final newline left Git reporting the file modified while the diff showed identical content). Attached views now autosave on blur with files.autoSave, sharing the regular editor's popup-aware delay (saveOnBlur), skip read-only views and cancel a pending save when destroyed or released.

Co-authored-by: qiany-sui <[email protected]>
2026-11-16 17:45:28 +08:00
SunZhiQiang 6b3edb6cf5 fix(agents): name the default model entry by the model it resolves to (#3716)
The Claude CLI's initialize response carries resolvedModel for the default entry, but Settings::from_cli kept only its display name, so the model picker and the composer chip showed "Default (recommended)" without the model that runs. The default entry is now named "Default (<resolved model>)"; without a resolved model it keeps the agent's own name.

Co-authored-by: panda-student <[email protected]>
2026-11-16 17:42:51 +08:00
l0ng-ai e598936529 fix(editor): gutter icons move with their line's text on Enter (#3726)
Line-start gutter icons were mapped with the default association, so Enter at the start of their line left them on the new empty line until each source placed them again. They now move with their line's text at once (mapLineStart), and HTTP endpoint markers are mapped through edits instead of cleared. Sibling of #3722.
2026-11-16 17:40:40 +08:00
l0ng-ai 8b7318e59a fix(vcs): merge toolbar and footer buttons act on their own merge editor (#3725)
The merge editor's toolbar and footer buttons ran global actions that only apply to the focused merge editor, so they did nothing while it lacked focus (e.g. right after opening). Each button now runs its command on its own merge editor; Previous/Next Change are disabled once no unresolved change is left.
2026-11-16 17:37:57 +08:00
LU XIANGRUIтаwildcatDownstairs faa9a91953 fix(editor): keep the gutter icon area's width while editing (#3722)
After an edit each icon source places its icons again on its own schedule (run icons before the language server's inheritance icons, plugin line markers cleared and refilled), so a line's icons briefly part and the shared icon area narrowed and widened again, shifting the code. The area now widens at once but narrows only after the text and the icon count stayed unchanged for 2 seconds, and its width follows the line with the most icons in the whole file.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-16 17:35:47 +08:00
l0ng-ai c805173467 fix(appearance): soften file colors on editor tabs and keep their hover feedback
Editor tabs tinted by File Colors used the data source tint strength (22%),
so they looked much stronger than the same file in the project view. They now
use --file-tint-strength like the project view, which drops from 14% to 9%,
and a tinted tab still shows the hover background on hover.
2026-11-16 16:28:06 +08:00
langxpтаkradme 94b72c271a fix(agents): restore native Codex slash commands (#3705)
After Codex moved from codex-acp to the native app-server driver, the composer kept the dynamic skills but lost the 11 builtin commands the adapter provided, and typing one sent it to the model as a prompt. The native adapter now owns a typed command table (/plan, /mcp, /skills, /status, /review, /review-branch, /review-commit, /compact, /goal, /rename, /logout), merged with skills/list, and routes each to its app-server operation (thread/compact/start, review/start, thread/goal/*, thread/name/set, config/mcpServer/reload, account/logout) or answers locally; /plan switches the collaboration mode, also offered in the config picker.

Co-authored-by: kradme <[email protected]>
2026-11-16 16:16:05 +08:00
misswellтаmisswell 610d68ee41 fix(java): go to implementation lands on the method in dependency classes (#3706)
jdtls answers textDocument/implementation for an implementation in a dependency at 0:0 of the decompiled class file (the search match has no source offset), so the gutter and Go to Implementation opened the class instead of the method. java-usages 1.15.0 adds openidea.java.implementationLocations, which finds the overriding method with MethodOverrideTester and returns its decompiled declaration; explicit Go to Implementation refines jdt 0:0 targets, and gutter markers resolve them lazily when opened (lsp_implementation_locations).

Co-authored-by: misswell <[email protected]>
2026-11-16 16:11:59 +08:00
l0ng-ai c6bd809d08 fix(run): Debug on a running configuration asks to stop it instead of starting another (#3710)
Debug skipped the single-instance check Run has, so each click started one more debug session of the same configuration. Debug now asks "not allowed to run in parallel" and stops the configuration's running and debugged instances first (unless it allows multiple instances); a click while the first Debug is still preparing is ignored. Run also counts the configuration's debug sessions as running instances.
2026-11-16 16:07:07 +08:00
l0ng-ai 401d66d850 fix(navigation): keep the keyboard in choosers and filter implementations by class (#3708)
A speed search that matched nothing replaced the focused list with a non-focusable empty state, so focus fell to the page and the chooser stopped taking keys. List now renders its empty state inside the focusable list (all list popups and choosers). Chooser rows whose targets share one name (a method's implementations, same-named declaration candidates) show the containing class as their text, so typing a class name filters them.
2026-11-16 16:03:30 +08:00
l0ng-ai 4561ae05b2 feat(refactor): Extract Interface for Java classes (#3707)
Refactor > Extract Interface… (also in Refactor This) opens a dialog for the class of the current Java file: interface name, package and members. jdtls checks the extraction and computes the edit, which creates the interface, makes the class implement it and uses it where possible; the new file opens afterwards.
2026-11-16 15:50:27 +08:00
l0ng-ai 34c81a61e4 feat(refactor): Java Move for classes, static members, nested types and instance methods (#3704)
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:36:01 +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
143 змінених файлів з 11120 додано та 656 видалено

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();
+126 -25
Переглянути файл
@@ -70,6 +70,8 @@ pub(crate) const LIMITS_UPDATE: &str = "openidea_limits";
/// A native agent's own update: the background tasks its session runs
/// (see [`TaskState::background_tasks`]).
pub(crate) const BACKGROUND_TASKS_UPDATE: &str = "openidea_background_tasks";
/// A native agent's diagnostic, including warnings emitted before a session exists.
pub(crate) const WARNING_NOTIFICATION: &str = "_openidea/warning";
/// Referenced files up to this size are embedded in the prompt (when the agent takes it).
const MAX_EMBED: u64 = 256 * 1024;
/// How long a probe waits for the agent to answer `initialize`.
@@ -208,10 +210,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 +420,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)>>,
@@ -626,14 +639,9 @@ impl AgentManager {
}
offered = self.shared.known_commands(&provider);
}
for &(name, description) in builtin_commands(&provider) {
if !offered.iter().any(|c| c.name == name) {
offered.push(AgentCommand {
name: name.to_owned(),
description: description.to_owned(),
hint: None,
source: AgentCommandSource::Command,
});
for command in builtin_commands(&provider) {
if !offered.iter().any(|c| c.name == command.name) {
offered.push(command);
}
}
if provider != "claude" && provider != "claude-acp" {
@@ -724,6 +732,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 +824,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 +926,7 @@ impl AgentManager {
resets_ms: None,
retry: None,
background: Box::default(),
mcp_overrides: req.mcp_overrides,
config,
};
let handle = self.register(TaskFile {
@@ -1117,9 +1128,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 +1616,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 +1697,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 +1755,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 +1945,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 +1958,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 +2302,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();
@@ -2483,11 +2555,20 @@ impl Task {
if let Some(title) = title {
// Check and write under one lock: a rename landing between them would be lost.
let mut s = self.state.lock();
if !s.title_renamed && s.task.title != title {
let user_named = update.get("userNamed").and_then(Value::as_bool) == Some(true);
let flag_changed = user_named && !s.title_renamed;
if user_named {
s.title_renamed = true;
}
if (user_named || !s.title_renamed) && s.task.title != title {
s.task.title = title.to_owned();
drop(s);
self.persist();
self.emit_task();
} else if flag_changed {
drop(s);
self.persist();
self.emit_task();
}
}
return;
@@ -2837,6 +2918,15 @@ struct Client {
impl Handler for Client {
fn on_notification(&self, method: &str, params: Value) {
if method == WARNING_NOTIFICATION {
if let Some(task) = self.task.upgrade()
&& let Some(message) = params.get("message").and_then(Value::as_str).filter(|s| !s.trim().is_empty())
{
task.push_entry(AgentEntry::Error { message: message.to_owned() });
task.persist();
}
return;
}
if method == "session/update"
&& let (Some(task), Some(update)) = (self.task.upgrade(), params.get("update"))
{
@@ -3047,9 +3137,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);
}
}
@@ -3196,13 +3290,20 @@ fn model_of(config: &[AgentConfigOption]) -> Option<String> {
config.iter().find(|o| o.category.as_deref() == Some("model")).and_then(|o| o.current.clone())
}
/// Commands the agent implements on its own and never lists in `availableCommands` —
/// its CLI builtins, passed through as prompt text (e.g. `/compact`). `(name, description)`.
fn builtin_commands(provider: &str) -> &'static [(&'static str, &'static str)] {
/// Commands the agent implements on its own and never lists in `availableCommands`.
fn builtin_commands(provider: &str) -> Vec<AgentCommand> {
match provider {
// Codex app-server has no command-list API, so the native adapter supplies its
// stable builtins and merges the session's dynamic skills separately.
"codex" => native::codex::builtin_commands(),
// OpenCode ACP handles `/compact` via session.summarize but omits it from its command list.
"opencode" => &[("compact", "compact the conversation")],
_ => &[],
"opencode" => vec![AgentCommand {
name: "compact".into(),
description: "compact the conversation".into(),
hint: None,
source: AgentCommandSource::Command,
}],
_ => Vec::new(),
}
}
+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)]
+22 -2
Переглянути файл
@@ -48,10 +48,17 @@ impl Settings {
.filter_map(|m| {
let s = |k: &str| m.get(k).and_then(Value::as_str).map(str::to_owned);
let value = s("value")?;
let resolved = s("resolvedModel");
// The default entry follows the account's default model, so "Default
// (recommended)" hides what actually runs: name the model it resolves to.
let name = match (value.as_str(), resolved.as_deref()) {
("default", Some(r)) if !r.is_empty() => format!("Default ({r})"),
_ => s("displayName").unwrap_or_else(|| value.clone()),
};
Some(Model {
name: s("displayName").unwrap_or_else(|| value.clone()),
name,
description: s("description"),
resolved: s("resolvedModel"),
resolved,
efforts: if m.get("supportsEffort").and_then(Value::as_bool) == Some(true) {
m.get("supportedEffortLevels")
.and_then(Value::as_array)
@@ -230,6 +237,19 @@ mod tests {
assert_eq!(s.model, "claude-x-1");
}
#[test]
fn the_default_entry_is_named_by_the_model_it_runs() {
let s = Settings::from_cli(&init(), &json!({"applied": {"model": "claude-sonnet-5-5"}}));
let names: Vec<_> = s.models.iter().map(|m| m.name.as_str()).collect();
assert_eq!(names, ["Default (claude-sonnet-5-5)", "Opus", "Haiku 4.5"]);
// Without a resolved model, the agent's own name stands.
let s = Settings::from_cli(
&json!({"models": [{"value": "default", "displayName": "Default (recommended)"}]}),
&json!({}),
);
assert_eq!(s.models[0].name, "Default (recommended)");
}
#[test]
fn options_follow_the_model() {
let mut s = Settings::from_cli(&init(), &json!({"applied": {"model": "claude-sonnet-5-5", "effort": "high"}}));
+155
Переглянути файл
@@ -0,0 +1,155 @@
//! Codex's built-in slash commands. `codex app-server` has no command-list API, so the
//! native adapter owns this stable compatibility table; skills stay dynamic via `skills/list`.
use serde_json::Value;
/// Menu metadata shared by agent_commands and the prompt dispatcher.
pub(crate) struct BuiltinCommandSpec {
pub name: &'static str,
pub description: &'static str,
pub hint: Option<&'static str>,
}
pub(crate) const BUILTIN_COMMANDS: &[BuiltinCommandSpec] = &[
BuiltinCommandSpec { name: "plan", description: "Turn plan mode on or off.", hint: None },
BuiltinCommandSpec {
name: "mcp",
description: "Show the status of the MCP servers, or reconnect them.",
hint: Some("[reconnect]"),
},
BuiltinCommandSpec { name: "skills", description: "List available skills.", hint: None },
BuiltinCommandSpec { name: "status", description: "Display session configuration and token usage.", hint: None },
BuiltinCommandSpec {
name: "review",
description: "Review uncommitted changes, or review with custom instructions.",
hint: Some("optional review instructions"),
},
BuiltinCommandSpec {
name: "review-branch",
description: "Review changes relative to a base branch.",
hint: Some("branch name"),
},
BuiltinCommandSpec { name: "review-commit", description: "Review a specific commit.", hint: Some("commit sha") },
BuiltinCommandSpec {
name: "compact",
description: "Summarize conversation to avoid hitting the context limit.",
hint: None,
},
BuiltinCommandSpec {
name: "goal",
description: "Set a goal to keep pursuing.",
hint: Some("[<objective>|clear|pause|resume]"),
},
BuiltinCommandSpec { name: "rename", description: "Rename the current session.", hint: Some("new name") },
BuiltinCommandSpec {
name: "logout",
description: "Sign out of Codex. This option is available when you are logged in via ChatGPT.",
hint: None,
},
];
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum BuiltinCommand {
Plan,
Mcp,
Skills,
Status,
Review,
ReviewBranch,
ReviewCommit,
Compact,
Goal,
Rename,
Logout,
}
impl BuiltinCommand {
fn from_name(name: &str) -> Option<Self> {
Some(match name {
"plan" => Self::Plan,
"mcp" => Self::Mcp,
"skills" => Self::Skills,
"status" => Self::Status,
"review" => Self::Review,
"review-branch" => Self::ReviewBranch,
"review-commit" => Self::ReviewCommit,
"compact" => Self::Compact,
"goal" => Self::Goal,
"rename" => Self::Rename,
"logout" => Self::Logout,
_ => return None,
})
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct ParsedCommand {
pub command: BuiltinCommand,
/// Everything after the command name, trimmed but otherwise unchanged.
pub rest: String,
}
impl ParsedCommand {
/// Commands that Codex completes as a turn. Missing review arguments stay local so the
/// adapter can print the command's usage without starting an unnecessary model request.
pub fn starts_turn(&self) -> bool {
matches!(self.command, BuiltinCommand::Compact | BuiltinCommand::Review)
|| (matches!(self.command, BuiltinCommand::ReviewBranch | BuiltinCommand::ReviewCommit)
&& !self.rest.is_empty())
}
}
/// A recognized Codex builtin at the start of the prompt. Unknown slash commands and
/// `$skill` invocations return `None`, so they continue through Codex as ordinary prompts.
pub(super) fn parse(prompt: &Value) -> Option<ParsedCommand> {
let text = prompt.as_array()?.first()?.get("text")?.as_str()?.trim();
let command_text = text.strip_prefix('/')?.trim();
let (name, rest) = command_text.split_once(char::is_whitespace).unwrap_or((command_text, ""));
let command = BuiltinCommand::from_name(&name.to_ascii_lowercase())?;
Some(ParsedCommand { command, rest: rest.trim().to_owned() })
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn text(value: &str) -> Value {
json!([{ "type": "text", "text": value }])
}
#[test]
fn every_builtin_is_registered_and_parsed() {
let expected = [
"plan",
"mcp",
"skills",
"status",
"review",
"review-branch",
"review-commit",
"compact",
"goal",
"rename",
"logout",
];
assert_eq!(BUILTIN_COMMANDS.iter().map(|c| c.name).collect::<Vec<_>>(), expected);
for name in expected {
assert!(parse(&text(&format!("/{name}"))).is_some(), "{name}");
}
}
#[test]
fn parsing_keeps_arguments_and_leaves_non_builtins_alone() {
let parsed = parse(&text(" /review-branch origin/main ")).unwrap();
assert_eq!(parsed.command, BuiltinCommand::ReviewBranch);
assert_eq!(parsed.rest, "origin/main");
assert!(parsed.starts_turn());
assert!(!parse(&text("/review-branch")).unwrap().starts_turn());
assert!(parse(&text("/$review check this")).is_none());
assert!(parse(&text("review")).is_none());
let prompt = json!([{ "type": "text", "text": "/compact" }, { "type": "image", "data": "AA==" }]);
assert_eq!(parse(&prompt).unwrap().command, BuiltinCommand::Compact);
}
}
+375 -21
Переглянути файл
@@ -2,7 +2,11 @@
//! translated to and from ACP. A codex thread is an ACP session; a subagent's thread is
//! a subagent session of the thread that spawned it.
mod commands;
mod translate;
mod trust;
pub(crate) use commands::BUILTIN_COMMANDS;
#[cfg(test)]
mod tests;
@@ -10,6 +14,8 @@ mod tests;
use super::Shim;
use crate::acp::AUTH_REQUIRED;
use crate::provider::ProviderSpec;
use crate::{AgentCommand, AgentCommandSource};
use commands::{BuiltinCommand, ParsedCommand};
use ide_jsonrpc::{Framing, Handler, Peer, RpcError, codes};
use parking_lot::Mutex;
use serde_json::{Value, json};
@@ -32,6 +38,19 @@ const EXIT_GRACE: Duration = Duration::from_millis(100);
const NAME_PROMPT: &str = "Name this conversation for a list of tasks: a short title of at most six words, in the \
language the user writes in. Reply with the title only, without quotes or a closing period.";
/// Slash-command metadata for provider discovery and sessions without an advertised list.
pub(crate) fn builtin_commands() -> Vec<AgentCommand> {
BUILTIN_COMMANDS
.iter()
.map(|command| AgentCommand {
name: command.name.to_owned(),
description: command.description.to_owned(),
hint: command.hint.map(str::to_owned),
source: AgentCommandSource::Command,
})
.collect()
}
pub(crate) fn connect(
spec: &ProviderSpec,
cwd: &Path,
@@ -183,6 +202,8 @@ struct State {
threads: HashMap<String, Thread>,
/// The last `account/rateLimits/updated` snapshot.
rate_limits: Option<Value>,
/// Project trust has been checked (and, when needed, asked about) on this connection.
trust_checked: HashSet<String>,
/// Codex exited.
gone: bool,
}
@@ -215,6 +236,8 @@ struct Thread {
early_cancel: Option<Instant>,
/// The latest agent message (a subagent's answer).
answer: String,
/// The latest `thread/tokenUsage/updated` payload, for the `/status` command.
token_usage: Option<Value>,
/// The thread has a name.
named: bool,
/// A name is being asked for.
@@ -320,6 +343,12 @@ impl CodexShim {
self.codex().request(method, params, None).await.map_err(from_codex)
}
fn warning(&self, message: impl Into<String>) {
if let Some(client) = self.client.get() {
let _ = client.notify(crate::WARNING_NOTIFICATION, json!({ "message": message.into() }));
}
}
async fn handle(&self, method: &str, params: Value) -> Result<Value, ResponseError> {
match method {
"initialize" => self.initialize().await,
@@ -403,6 +432,7 @@ impl CodexShim {
async fn new_session(&self, params: &Value) -> Result<Value, ResponseError> {
let models = self.models().await?;
self.prepare_project_trust(params).await;
let mut request = json!({ "cwd": params.get("cwd") });
if let Some(config) = translate::mcp_config(params) {
request["config"] = config;
@@ -420,6 +450,7 @@ impl CodexShim {
async fn load_session(&self, params: &Value) -> Result<Value, ResponseError> {
let id = str_param(params, "sessionId")?;
let models = self.models().await?;
self.prepare_project_trust(params).await;
let mut request = json!({ "threadId": id, "cwd": params.get("cwd") });
if let Some(config) = translate::mcp_config(params) {
request["config"] = config;
@@ -438,6 +469,7 @@ impl CodexShim {
async fn fork_session(&self, params: &Value) -> Result<Value, ResponseError> {
let source = str_param(params, "sessionId")?;
let models = self.models().await?;
self.prepare_project_trust(params).await;
let settings = self.state.lock().threads.get(source).and_then(|t| t.settings.clone());
let mut request = json!({ "threadId": source, "cwd": params.get("cwd") });
if let Some(config) = translate::mcp_config(params) {
@@ -471,11 +503,18 @@ impl CodexShim {
async fn prompt(&self, params: &Value) -> Result<Value, ResponseError> {
let session = str_param(params, "sessionId")?.to_owned();
let input = translate::user_input(params.get("prompt").unwrap_or(&Value::Null));
let prompt = params.get("prompt").unwrap_or(&Value::Null);
let command = commands::parse(prompt);
if let Some(command) = command.as_ref()
&& !command.starts_turn()
{
return self.local_command(&session, command).await;
}
let input = translate::user_input(prompt);
if input.is_empty() {
return Err(invalid("empty prompt"));
}
let models = self.models().await?;
let models = if command.is_none() { Some(self.models().await?) } else { None };
let (done, ended) = oneshot::channel();
let settings = {
let mut state = self.state.lock();
@@ -491,33 +530,213 @@ impl CodexShim {
t.error = None;
t.settings.clone()
};
let mut request = json!({ "threadId": session, "input": input, "summary": "auto" });
if let Some(s) = settings {
request["model"] = json!(s.model_slug(&models));
request["approvalPolicy"] = json!(s.mode.approval_policy());
request["sandboxPolicy"] = s.mode.sandbox_policy();
if let Some(effort) = &s.effort {
request["effort"] = json!(effort);
let started = match command.as_ref() {
Some(command) => match command.command {
BuiltinCommand::Compact => {
// Codex reports compaction as its own turn, using the same started/completed
// notifications that finish the pending session/prompt above.
self.call("thread/compact/start", json!({ "threadId": session })).await
}
BuiltinCommand::Review | BuiltinCommand::ReviewBranch | BuiltinCommand::ReviewCommit => {
self.call("review/start", json!({ "threadId": session, "target": review_target(command) })).await
}
_ => unreachable!("local commands return before a pending turn is created"),
},
None => {
let models = models.expect("ordinary prompts load the model catalog");
let mut request = json!({ "threadId": session, "input": input, "summary": "auto" });
if let Some(s) = &settings {
request["model"] = json!(s.model_slug(&models));
request["approvalPolicy"] = json!(s.mode.approval_policy());
request["sandboxPolicy"] = s.mode.sandbox_policy();
// Omit the default so older app-server versions keep accepting normal
// turns; selecting Plan opts into this newer request field.
if s.collaboration_mode == translate::PLAN_COLLABORATION_MODE
|| s.collaboration_mode_override.is_some()
{
request["collaborationMode"] = translate::collaboration_mode(s, &models);
}
if let Some(effort) = &s.effort {
request["effort"] = json!(effort);
}
}
self.call("turn/start", request).await
}
};
if let Ok(started) = &started
&& let Some(turn) = started.pointer("/turn/id").and_then(Value::as_str)
{
self.turn_known(&session, turn, false);
}
match self.call("turn/start", request).await {
Ok(started) => {
if let Some(turn) = started.pointer("/turn/id").and_then(Value::as_str) {
self.turn_known(&session, turn, false);
}
}
Err(e) => {
if let Some(t) = self.state.lock().threads.get_mut(&session) {
t.prompt = None;
}
return Err(e);
if started.is_ok()
&& command.is_none()
&& let Some(thread) = self.state.lock().threads.get_mut(&session)
&& let Some(settings) = thread.settings.as_mut()
{
// A Default override is needed only for the first turn that resets a resumed
// Plan thread; omitting it afterwards preserves compatibility with older Codex.
settings.collaboration_mode_override = None;
}
if let Err(e) = started {
if let Some(t) = self.state.lock().threads.get_mut(&session) {
t.prompt = None;
}
return Err(e);
}
let (turn, last_error) = ended.await.map_err(|_| error(codes::INTERNAL_ERROR, "Codex exited"))?;
let rate_limits = self.state.lock().rate_limits.clone();
stop_reason(&turn, last_error, rate_limits.as_ref())
}
/// Runs commands that codex-acp historically handled locally: configuration, status,
/// inventory, naming and account actions. They complete without starting a model turn.
async fn local_command(&self, session: &str, command: &ParsedCommand) -> Result<Value, ResponseError> {
let (settings, cwd, token_usage, rate_limits) = {
let state = self.state.lock();
if state.gone {
return Err(error(codes::INTERNAL_ERROR, "Codex exited"));
}
let thread = state.threads.get(session).ok_or_else(|| invalid(format!("no session {session}")))?;
if thread.prompt.is_some() || thread.turn.is_some() {
return Err(invalid("a turn is already running"));
}
(thread.settings.clone(), thread.cwd.clone(), thread.token_usage.clone(), state.rate_limits.clone())
};
match command.command {
BuiltinCommand::Plan => {
if !command.rest.is_empty() {
self.say(session, command_usage(BuiltinCommand::Plan));
return Ok(json!({ "stopReason": "end_turn" }));
}
let models = self.models().await?;
let options = {
let mut state = self.state.lock();
let thread =
state.threads.get_mut(session).ok_or_else(|| invalid(format!("no session {session}")))?;
let settings = thread.settings.as_mut().ok_or_else(|| invalid(format!("no session {session}")))?;
settings.collaboration_mode = if settings.collaboration_mode == translate::PLAN_COLLABORATION_MODE {
translate::DEFAULT_COLLABORATION_MODE.to_owned()
} else {
translate::PLAN_COLLABORATION_MODE.to_owned()
};
settings.collaboration_mode_override = Some(settings.collaboration_mode.clone());
translate::config_options(&models, settings)
};
self.emit(session, json!({ "sessionUpdate": "config_option_update", "configOptions": options }));
}
BuiltinCommand::Status => {
let text =
status_text(session, settings.as_ref(), cwd.as_deref(), token_usage.as_ref(), rate_limits.as_ref());
self.say(session, text);
}
BuiltinCommand::Skills => {
let cwd = cwd.ok_or_else(|| invalid(format!("no session {session}")))?;
let found = self.call("skills/list", json!({ "cwds": [cwd] })).await?;
self.say(session, skills_text(&found));
}
BuiltinCommand::Mcp => match command.rest.as_str() {
"" => self.say(session, self.mcp_text(session).await?),
rest if rest.eq_ignore_ascii_case("reconnect") => {
self.call("config/mcpServer/reload", json!({})).await?;
self.say(session, self.mcp_text(session).await?);
}
_ => self.say(session, command_usage(BuiltinCommand::Mcp)),
},
BuiltinCommand::Rename => {
if command.rest.is_empty() {
self.say(session, command_usage(BuiltinCommand::Rename));
} else {
self.call("thread/name/set", json!({ "threadId": session, "name": command.rest })).await?;
// User commands are authoritative over the automatic title, so the manager
// must retain this title through later generated-name updates.
self.emit(
session,
json!({ "sessionUpdate": "session_info_update", "title": command.rest, "userNamed": true }),
);
}
}
BuiltinCommand::Logout => {
self.call("account/logout", Value::Null).await?;
self.say(session, "Logged out from Codex account.");
}
BuiltinCommand::Goal => self.goal_command(session, &command.rest).await?,
BuiltinCommand::ReviewBranch | BuiltinCommand::ReviewCommit if command.rest.is_empty() => {
self.say(session, command_usage(command.command));
}
BuiltinCommand::ReviewBranch | BuiltinCommand::ReviewCommit => {
return Err(invalid("review command did not start a turn"));
}
BuiltinCommand::Review | BuiltinCommand::Compact => {
return Err(invalid("turn command reached the local command path"));
}
}
Ok(json!({ "stopReason": "end_turn" }))
}
async fn goal_command(&self, session: &str, rest: &str) -> Result<(), ResponseError> {
let argument = rest.trim();
if argument.is_empty() {
self.say(session, command_usage(BuiltinCommand::Goal));
return Ok(());
}
match argument.to_ascii_lowercase().as_str() {
"clear" => {
self.call("thread/goal/clear", json!({ "threadId": session })).await?;
self.say(session, "Goal cleared.");
}
"pause" => {
let response = self
.call("thread/goal/set", json!({ "threadId": session, "status": "paused", "origin": "user" }))
.await?;
self.say(
session,
format!(
"Goal is now {}.",
response.pointer("/goal/status").and_then(Value::as_str).unwrap_or("paused")
),
);
}
"resume" => {
let response = self
.call("thread/goal/set", json!({ "threadId": session, "status": "active", "origin": "user" }))
.await?;
self.say(
session,
format!(
"Goal is now {}.",
response.pointer("/goal/status").and_then(Value::as_str).unwrap_or("active")
),
);
}
_ if argument.chars().count() > 4000 => {
self.say(session, "Command \"/goal\" requires goal text of at most 4000 characters.");
}
_ => {
let response = self
.call(
"thread/goal/set",
json!({ "threadId": session, "objective": argument, "status": "active", "origin": "user" }),
)
.await?;
let status = response.pointer("/goal/status").and_then(Value::as_str).unwrap_or("active");
self.say(session, format!("Goal set and {status}."));
}
}
Ok(())
}
async fn mcp_text(&self, session: &str) -> Result<String, ResponseError> {
let response = self
.call("mcpServerStatus/list", json!({ "threadId": session, "detail": "toolsAndAuthOnly", "limit": 100 }))
.await?;
Ok(mcp_text(&response))
}
fn say(&self, session: &str, text: impl AsRef<str>) {
self.emit(session, translate::chunk("agent_message_chunk", text.as_ref()));
}
async fn steer(&self, params: &Value) -> Result<Value, ResponseError> {
let session = str_param(params, "sessionId")?;
let turn = self.state.lock().threads.get(session).and_then(|t| t.turn.clone());
@@ -643,6 +862,25 @@ impl CodexShim {
fn on_codex_notification(self: &Arc<Self>, method: &str, params: &Value) {
let thread = params.get("threadId").and_then(Value::as_str).unwrap_or_default();
match method {
"configWarning" => {
let Some(summary) = params.get("summary").and_then(Value::as_str).filter(|s| !s.trim().is_empty())
else {
return;
};
let mut message = summary.trim().to_owned();
for key in ["details", "path"] {
if let Some(value) = params.get(key).and_then(Value::as_str).filter(|s| !s.trim().is_empty()) {
message.push_str("\n\n");
message.push_str(value.trim());
}
}
self.warning(message);
}
"warning" => {
if let Some(message) = params.get("message").and_then(Value::as_str).filter(|s| !s.trim().is_empty()) {
self.warning(message);
}
}
"skills/changed" => {
let shim = self.clone();
let sessions: Vec<String> = self
@@ -693,7 +931,12 @@ impl CodexShim {
t.last_chunk = None;
Some(translate::plan(params))
}),
"thread/tokenUsage/updated" => self.with_thread(thread, |_, _| translate::usage(params)),
"thread/tokenUsage/updated" => self.with_thread(thread, |t, _| {
if let Some(usage) = params.get("tokenUsage") {
t.token_usage = Some(usage.clone());
}
translate::usage(params)
}),
"thread/name/updated" => self.with_thread(thread, |t, _| {
let title = params.get("threadName").and_then(Value::as_str)?;
t.named = true;
@@ -1182,3 +1425,114 @@ fn stop_reason(turn: &Value, last_error: Option<Value>, rate_limits: Option<&Val
};
Ok(json!({ "stopReason": stop }))
}
/// The `review/start` target of a parsed review command.
fn review_target(command: &ParsedCommand) -> Value {
match command.command {
BuiltinCommand::Review if command.rest.is_empty() => json!({ "type": "uncommittedChanges" }),
BuiltinCommand::Review => json!({ "type": "custom", "instructions": command.rest }),
BuiltinCommand::ReviewBranch => json!({ "type": "baseBranch", "branch": command.rest }),
BuiltinCommand::ReviewCommit => json!({ "type": "commit", "sha": command.rest, "title": null }),
_ => unreachable!("only review commands have review targets"),
}
}
fn command_usage(command: BuiltinCommand) -> String {
match command {
BuiltinCommand::Plan => "Command \"/plan\" accepts no arguments.".to_owned(),
BuiltinCommand::Mcp => "Command \"/mcp\" accepts no arguments, or `reconnect`.".to_owned(),
BuiltinCommand::ReviewBranch => "Command \"/review-branch\" requires branch name.".to_owned(),
BuiltinCommand::ReviewCommit => "Command \"/review-commit\" requires commit sha.".to_owned(),
BuiltinCommand::Goal => "Command \"/goal\" requires [<objective>|clear|pause|resume].".to_owned(),
BuiltinCommand::Rename => "Command \"/rename\" requires new name.".to_owned(),
_ => "This command does not accept arguments.".to_owned(),
}
}
fn status_text(
session: &str,
settings: Option<&Settings>,
cwd: Option<&str>,
token_usage: Option<&Value>,
rate_limits: Option<&Value>,
) -> String {
let mut lines = Vec::new();
if let Some(settings) = settings {
lines.push(format!("**Model:** {}", settings.model));
lines.push(format!("**Collaboration:** {}", settings.collaboration_mode));
lines.push(format!("**Approval:** {}", settings.mode.approval_policy()));
lines.push(format!("**Sandbox:** {}", settings.mode.sandbox_mode()));
}
if let Some(cwd) = cwd {
lines.push(format!("**Directory:** {cwd}"));
}
lines.push(format!("**Session:** `{session}`"));
if let Some(usage) = token_usage {
let total = usage.pointer("/total/totalTokens").and_then(Value::as_u64);
let used = usage.pointer("/last/totalTokens").and_then(Value::as_u64);
let window = usage.get("modelContextWindow").and_then(Value::as_u64).filter(|window| *window > 0);
if let (Some(total), Some(used), Some(window)) = (total, used, window) {
let percent = (used.saturating_mul(100) + window / 2) / window;
lines.push(format!("**Token usage:** {total} total"));
lines.push(format!("**Context window:** {used} / {window} ({percent}%)"));
}
}
if let Some(primary) = rate_limits.and_then(|r| r.get("primary"))
&& let Some(used) = primary.get("usedPercent").and_then(Value::as_f64)
{
lines.push(format!("**Rate limit:** {used:.0}% used"));
}
lines.join(" \n")
}
fn skills_text(response: &Value) -> String {
let mut seen = HashSet::new();
let names: Vec<String> = response
.get("data")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(|entry| entry.get("skills").and_then(Value::as_array))
.flatten()
.filter(|skill| skill.get("enabled") != Some(&Value::Bool(false)))
.filter_map(|skill| {
let name = skill.get("name").and_then(Value::as_str)?.trim();
if name.is_empty() || !seen.insert(name.to_owned()) {
return None;
}
let description = skill
.pointer("/interface/shortDescription")
.or_else(|| skill.get("shortDescription"))
.or_else(|| skill.get("description"))
.and_then(Value::as_str)
.unwrap_or_default();
Some(if description.is_empty() { name.to_owned() } else { format!("{name}: {description}") })
})
.collect();
if names.is_empty() {
"No skills configured.".to_owned()
} else {
format!("Available skills:\n{}", names.iter().map(|name| format!("- {name}")).collect::<Vec<_>>().join("\n"))
}
}
fn mcp_text(response: &Value) -> String {
let servers = response.get("data").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default();
if servers.is_empty() {
return "No MCP servers configured.".to_owned();
}
let lines = servers
.iter()
.filter_map(|server| {
let name = server.get("name").and_then(Value::as_str)?;
let status = server
.get("runtimeStatus")
.and_then(Value::as_str)
.or_else(|| server.get("authStatus").and_then(Value::as_str))
.unwrap_or("unknown");
let tools = server.get("tools").and_then(Value::as_object).map_or(0, serde_json::Map::len);
Some(format!("- {name}: {status}, {tools} tools"))
})
.collect::<Vec<_>>();
format!("MCP servers:\n{}", lines.join("\n"))
}
+419 -6
Переглянути файл
@@ -180,24 +180,38 @@ fn settings_follow_the_thread_and_the_models() {
let result = json!({"model": "big", "reasoningEffort": null, "approvalPolicy": "untrusted",
"sandbox": {"type": "workspaceWrite"}});
let mut s = Settings::of(&result, &models);
assert_eq!(s, Settings { model: "big".into(), effort: Some("low".into()), mode: Mode::Ask });
assert_eq!(
s,
Settings {
model: "big".into(),
effort: Some("low".into()),
mode: Mode::Ask,
collaboration_mode: DEFAULT_COLLABORATION_MODE.into(),
collaboration_mode_override: None,
}
);
let options = config_options(&models, &s);
let ids: Vec<&str> = options.as_array().unwrap().iter().map(|o| o["id"].as_str().unwrap()).collect();
assert_eq!(ids, [MODEL, EFFORT, MODE]);
assert_eq!(ids, [MODEL, EFFORT, MODE, COLLABORATION_MODE]);
assert_eq!(options[0]["options"].as_array().unwrap().len(), 2, "hidden models are left out");
assert_eq!(options[1]["category"], "thought_level");
assert_eq!(options[1]["options"][1]["name"], "Extra high");
assert_eq!(options[2]["currentValue"], "ask");
assert_eq!(options[3]["currentValue"], "default");
// A model without efforts drops the option; its slug is what codex gets.
s.set(&models, MODEL, "plain").unwrap();
assert_eq!((s.effort.as_deref(), s.model_slug(&models).as_str()), (None, "plain-slug"));
assert_eq!(config_options(&models, &s).as_array().unwrap().len(), 2);
assert_eq!(config_options(&models, &s).as_array().unwrap().len(), 3);
assert!(s.set(&models, EFFORT, "low").is_err());
assert!(s.set(&models, MODEL, "nope").is_err());
s.set(&models, MODE, "full-access").unwrap();
assert_eq!((s.mode.approval_policy(), s.mode.sandbox_policy()), ("never", json!({"type": "dangerFullAccess"})));
s.set(&models, COLLABORATION_MODE, PLAN_COLLABORATION_MODE).unwrap();
assert_eq!(collaboration_mode(&s, &models)["mode"], PLAN_COLLABORATION_MODE);
s.set(&models, COLLABORATION_MODE, DEFAULT_COLLABORATION_MODE).unwrap();
assert_eq!(collaboration_mode(&s, &models)["mode"], DEFAULT_COLLABORATION_MODE);
// A model codex runs that it doesn't list is still offered.
let s = Settings::of(&json!({"model": "custom", "sandbox": {"type": "readOnly"}}), &models);
@@ -226,6 +240,18 @@ fn prompts_become_user_input() {
);
}
#[test]
fn compact_is_recognized_with_completion_whitespace_and_attachments() {
// Completion leaves trailing whitespace and images can remain in the prompt. The first
// text block still names the command; unknown slash-shaped text continues normally.
assert_eq!(commands::parse(&text("/compact")).unwrap().command, BuiltinCommand::Compact);
assert_eq!(commands::parse(&text(" /compact \n")).unwrap().command, BuiltinCommand::Compact);
assert_eq!(commands::parse(&text("/compact now")).unwrap().rest, "now");
let prompt = json!([{"type": "text", "text": "/compact"}, {"type": "image", "data": "AA=="}]);
assert_eq!(commands::parse(&prompt).unwrap().command, BuiltinCommand::Compact);
assert!(commands::parse(&text("x/compact")).is_none());
}
#[test]
fn commands_are_titled_by_what_they_do() {
let cmd = |actions: Value| {
@@ -453,6 +479,7 @@ fn history_replays_turns() {
#[derive(Default)]
struct Client {
updates: Mutex<Vec<Value>>,
warnings: Mutex<Vec<Value>>,
asked: Mutex<Vec<Value>>,
/// Option ids to choose; `None` (or none left) cancels.
answers: Mutex<VecDeque<Option<&'static str>>>,
@@ -462,6 +489,8 @@ impl Handler for Client {
fn on_notification(&self, method: &str, params: Value) {
if method == "session/update" {
self.updates.lock().push(params);
} else if method == "_openidea/warning" {
self.warnings.lock().push(params);
}
}
@@ -527,6 +556,10 @@ async fn questions_share_one_card_and_keep_their_ids() {
#[derive(Clone, Copy, Debug, PartialEq)]
enum Scenario {
AuthFailure,
Command(&'static str),
Compact,
PlanThenPrompt,
PlanToggleThenPrompt,
Interrupt,
Resume,
Steer,
@@ -541,6 +574,10 @@ impl Scenario {
fn file(self) -> &'static str {
match self {
Scenario::AuthFailure => "auth_failure",
Scenario::Command(_) => "simple",
Scenario::Compact => "simple",
Scenario::PlanThenPrompt => "simple",
Scenario::PlanToggleThenPrompt => "simple",
Scenario::Interrupt => "interrupt",
Scenario::Resume => "resume",
Scenario::Steer => "steer",
@@ -598,6 +635,21 @@ async fn drive(scenario: Scenario, acp: &Peer, client: &Client, cwd: &str, threa
Scenario::AuthFailure | Scenario::Simple | Scenario::UsageLimit | Scenario::Subagent => {
out.push(("prompt", request(acp, "session/prompt", prompt("Reply with the single word: hi")).await));
}
Scenario::Compact => {
out.push(("prompt", request(acp, "session/prompt", prompt("/compact")).await));
}
Scenario::Command(command) => {
out.push(("prompt", request(acp, "session/prompt", prompt(command)).await));
}
Scenario::PlanThenPrompt => {
out.push(("plan", request(acp, "session/prompt", prompt("/plan")).await));
out.push(("prompt", request(acp, "session/prompt", prompt("Reply with the single word: hi")).await));
}
Scenario::PlanToggleThenPrompt => {
out.push(("plan", request(acp, "session/prompt", prompt("/plan")).await));
out.push(("default", request(acp, "session/prompt", prompt("/plan")).await));
out.push(("prompt", request(acp, "session/prompt", prompt("Reply with the single word: hi")).await));
}
Scenario::Interrupt => {
out.push(("mode", request(acp, "session/set_config_option", set(MODE, "read-only")).await));
let running = {
@@ -665,6 +717,37 @@ fn load(name: &str) -> Transcript {
Transcript { meta, frames }
}
/// The simple fixture through session setup. Local commands add only the app-server calls
/// they need after it; turn commands keep the fixture's turn notifications.
fn command_transcript(calls: &[(&'static str, Value)]) -> Transcript {
let mut transcript = load(Scenario::Simple.file());
let prompt = transcript
.frames
.iter()
.position(|(out, frame)| *out && frame["method"] == "turn/start")
.expect("the scenario starts a turn");
transcript.frames.truncate(prompt);
transcript.frames.push((true, json!({ "id": 4, "method": "skills/list" })));
transcript.frames.push((false, json!({ "id": 4, "result": { "data": [] } })));
for (index, (method, result)) in calls.iter().enumerate() {
let id = 10 + index;
transcript.frames.push((true, json!({ "id": id, "method": method })));
transcript.frames.push((false, json!({ "id": id, "result": result })));
}
transcript
}
fn turn_command_transcript(method: &str) -> Transcript {
let mut transcript = load(Scenario::Simple.file());
let start = transcript
.frames
.iter_mut()
.find(|(out, frame)| *out && frame["method"] == "turn/start")
.expect("the scenario starts a turn");
start.1["method"] = json!(method);
transcript
}
/// Plays codex: waits for each frame the shim should send, sends what codex sent.
/// Returns the frames the shim sent.
async fn play<R: AsyncRead + Unpin, W: AsyncWrite + Unpin>(
@@ -684,10 +767,10 @@ async fn play<R: AsyncRead + Unpin, W: AsyncWrite + Unpin>(
.unwrap()
.unwrap_or_else(|| panic!("the shim closed before {frame}"));
let actual: Value = serde_json::from_str(&line).unwrap();
// Older recordings predate skill discovery and thread naming; play an
// Older recordings predate config inspection, skill discovery and thread naming; play an
// unsupported server.
let method = actual["method"].as_str().unwrap_or_default();
if matches!(method, "skills/list" | "thread/sample") && frame["method"] != method {
if matches!(method, "config/read" | "skills/list" | "thread/sample") && frame["method"] != method {
let reply = json!({ "id": actual["id"], "error": { "code": -32601, "message": "unsupported" } });
write.write_all(format!("{reply}\n").as_bytes()).await.unwrap();
continue;
@@ -760,6 +843,149 @@ fn session_of(results: &Results, label: &str) -> String {
result(results, label).as_ref().unwrap()["sessionId"].as_str().unwrap().to_owned()
}
#[tokio::test(flavor = "multi_thread")]
async fn configuration_warnings_before_a_session_and_runtime_warnings_reach_the_client() {
let mut transcript = load(Scenario::Simple.file());
transcript.frames.insert(
0,
(
false,
json!({"method": "configWarning", "params": {
"summary": "Project-local config is disabled until the project is trusted.",
"details": "Update the project's trust setting.", "path": "/work/.codex/config.toml"
}}),
),
);
let at = transcript.frames.iter().position(|(out, f)| *out && f["method"] == "turn/start").unwrap();
transcript
.frames
.insert(at, (false, json!({"method": "warning", "params": {"message": "MCP server unavailable"}})));
let (results, client, frames, _, _codex) = replay_transcript(Scenario::Simple, transcript).await;
assert!(result(&results, "new").is_ok());
assert_eq!(
*client.warnings.lock(),
[
json!({"message": "Project-local config is disabled until the project is trusted.\n\nUpdate the project's trust setting.\n\n/work/.codex/config.toml"}),
json!({"message": "MCP server unavailable"}),
]
);
assert!(sent(&frames, "config/value/write").is_empty());
assert!(sent(&frames, "config/batchWrite").is_empty());
}
struct TrustServer {
cwd: String,
disabled: bool,
other_project: bool,
write_error: bool,
overridden: bool,
calls: Mutex<Vec<(String, Value)>>,
}
impl Handler for TrustServer {
fn on_notification(&self, _: &str, _: Value) {}
fn on_request(&self, method: &str, params: Value) -> Result<Value, (i64, String)> {
self.calls.lock().push((method.to_owned(), params));
match method {
"initialize" => Ok(json!({})),
"model/list" => Ok(json!({"data": []})),
"config/read" => {
let cwd =
if self.other_project { Path::new(&self.cwd).join("other") } else { PathBuf::from(&self.cwd) };
Ok(json!({"layers": [
{"name": {"type": "user", "profile": null}, "version": "original"},
{"name": {"type": "project", "dotCodexFolder": cwd.join(".codex")},
"disabledReason": self.disabled.then_some("Project config is disabled until trusted.")}
]}))
}
"config/value/write" if self.write_error => Err((-32001, "Config changed concurrently".into())),
"config/value/write" => Ok(json!({"status": if self.overridden {"okOverridden"} else {"ok"}})),
"thread/start" | "thread/resume" | "thread/fork" => {
Ok(json!({"thread": {"id": "s", "turns": []}, "cwd": self.cwd}))
}
"skills/list" => Ok(json!({"data": []})),
_ => Err((codes::METHOD_NOT_FOUND, method.to_owned())),
}
}
}
#[tokio::test(flavor = "multi_thread")]
async fn project_trust_is_confirmed_before_new_resumed_and_forked_sessions() {
for method in ["session/new", "session/load", "session/fork"] {
for (answer, disabled, other_project, write_error, overridden) in [
(Some("codex-trust-project"), true, false, false, false),
(Some("codex-keep-untrusted"), true, false, false, false),
(None, true, false, false, false),
(Some("codex-trust-project"), false, false, false, false),
(Some("codex-trust-project"), true, true, false, false),
(Some("codex-trust-project"), true, false, true, false),
(Some("codex-trust-project"), true, false, false, true),
] {
let tmp = tempfile::tempdir().unwrap();
let cwd = tmp.path().join("project.with.dots-项目").to_string_lossy().into_owned();
let server = Arc::new(TrustServer {
cwd: cwd.clone(),
disabled,
other_project,
write_error,
overridden,
calls: Mutex::default(),
});
let client = Arc::new(Client::default());
client.answers.lock().push_back(answer);
let (ours, theirs) = tokio::io::duplex(1 << 16);
let (read, write) = tokio::io::split(theirs);
let native = Peer::connect_framed(read, write, server.clone(), Framing::Lines);
let acp = attach(client.clone(), |events| {
let (read, write) = tokio::io::split(ours);
Ok(Peer::connect_framed(read, write, events, Framing::Lines))
})
.unwrap();
request(&acp, "initialize", json!({})).await.unwrap();
let params = json!({"cwd": cwd, "sessionId": "source", "mcpServers": []});
request(&acp, method, params.clone()).await.unwrap();
// The same connection must not ask repeatedly after a decline.
request(&acp, method, params).await.unwrap();
let approved = answer == Some("codex-trust-project") && disabled && !other_project;
{
let asked = client.asked.lock();
assert_eq!(asked.len(), usize::from(disabled && !other_project));
if let Some(permission) = asked.first() {
assert!(permission["toolCall"]["title"].as_str().unwrap().contains(&cwd));
assert_eq!(
permission["toolCall"]["kind"], "edit",
"side conversations must deny persistent trust changes"
);
assert_eq!(
permission["options"][0]["kind"], "allow_always",
"task bypass must not grant permanent trust"
);
}
let calls = server.calls.lock();
let writes: Vec<_> = calls.iter().filter(|(m, _)| m == "config/value/write").collect();
assert_eq!(writes.len(), usize::from(approved));
if let Some((_, write)) = writes.first() {
assert_eq!(
*write,
json!({"keyPath": format!("projects.{}.trust_level", json!(cwd)), "value": "trusted", "mergeStrategy": "replace", "expectedVersion": "original"})
);
let written = calls.iter().position(|(m, _)| m == "config/value/write").unwrap();
let started = calls.iter().position(|(m, _)| m.starts_with("thread/")).unwrap();
assert!(written < started, "the session must load config after the write");
}
}
// Drain notifications sent before the last response.
tokio::time::sleep(Duration::from_millis(20)).await;
if approved && (write_error || overridden) {
assert!(!client.warnings.lock().is_empty());
}
acp.kill();
native.kill();
}
}
}
#[tokio::test(flavor = "multi_thread")]
async fn auth_failure_names_auth() {
let (results, _client, frames, _) = replay(Scenario::AuthFailure).await;
@@ -771,7 +997,7 @@ async fn auth_failure_names_auth() {
let categories: Vec<&str> =
new["configOptions"].as_array().unwrap().iter().map(|o| o["category"].as_str().unwrap()).collect();
// The model the user's codex config names; codex doesn't list it, so its efforts are unknown.
assert_eq!(categories, ["model", "mode"]);
assert_eq!(categories, ["model", "mode", "collaboration_mode"]);
let model = new["configOptions"][0]["currentValue"].as_str().unwrap();
assert_eq!(model, "gpt-6-luna");
assert!(new["configOptions"][0]["options"].as_array().unwrap().iter().any(|o| o["value"] == model));
@@ -1011,6 +1237,7 @@ async fn settings_apply_to_the_next_turn() {
(starts[0]["params"]["model"].as_str(), starts[0]["params"]["effort"].as_str()),
(Some("gpt-5.6-luna"), Some("medium"))
);
assert!(starts[0]["params"].get("collaborationMode").is_none());
assert_eq!(
(starts[1]["params"]["model"].as_str(), starts[1]["params"]["effort"].as_str()),
(Some("gpt-5.5"), Some("high"))
@@ -1019,6 +1246,192 @@ async fn settings_apply_to_the_next_turn() {
assert_eq!(client.text(&session, "agent_message_chunk"), "oneOn it.\n\ntwo");
}
#[tokio::test(flavor = "multi_thread")]
async fn compact_is_started_through_its_app_server_method() {
// Play the ordinary-turn fixture with the request swapped: the notifications are the
// same, while this pins the user-visible command to `thread/compact/start`, not a prompt.
let mut transcript = load(Scenario::Simple.file());
let start = transcript
.frames
.iter_mut()
.find(|(out, frame)| *out && frame["method"] == "turn/start")
.expect("the scenario starts a turn");
start.1["method"] = json!("thread/compact/start");
let (results, _client, frames, _meta, _codex) = replay_transcript(Scenario::Compact, transcript).await;
assert_eq!(result(&results, "prompt").as_ref().unwrap(), &json!({"stopReason": "end_turn"}));
assert!(sent(&frames, "turn/start").is_empty());
assert_eq!(sent(&frames, "thread/compact/start").len(), 1);
}
#[tokio::test(flavor = "multi_thread")]
async fn review_commands_start_the_matching_review_target() {
for (prompt, target) in [
("/review", json!({ "type": "uncommittedChanges" })),
("/review focus on errors", json!({ "type": "custom", "instructions": "focus on errors" })),
("/review-branch origin/main", json!({ "type": "baseBranch", "branch": "origin/main" })),
("/review-commit abc123", json!({ "type": "commit", "sha": "abc123", "title": null })),
] {
let (results, _client, frames, _meta, _codex) =
replay_transcript(Scenario::Command(prompt), turn_command_transcript("review/start")).await;
assert_eq!(result(&results, "prompt").as_ref().unwrap(), &json!({ "stopReason": "end_turn" }), "{prompt}");
assert!(sent(&frames, "turn/start").is_empty(), "{prompt}");
assert_eq!(sent(&frames, "review/start")[0]["params"]["target"], target, "{prompt}");
}
}
#[tokio::test(flavor = "multi_thread")]
async fn plan_toggles_collaboration_mode_and_updates_the_composer() {
let (results, client, _frames, _meta, _codex) =
replay_transcript(Scenario::Command("/plan"), command_transcript(&[])).await;
let session = session_of(&results, "new");
assert_eq!(result(&results, "prompt").as_ref().unwrap(), &json!({ "stopReason": "end_turn" }));
let update = client.of(&session).into_iter().find(|u| u["sessionUpdate"] == "config_option_update").unwrap();
let plan =
update["configOptions"].as_array().unwrap().iter().find(|o| o["category"] == "collaboration_mode").unwrap();
assert_eq!(plan["currentValue"], "plan");
}
#[tokio::test(flavor = "multi_thread")]
async fn plan_applies_to_the_next_normal_turn() {
let (results, _client, frames, _meta, _codex) =
replay_transcript(Scenario::PlanThenPrompt, load(Scenario::Simple.file())).await;
assert_eq!(result(&results, "plan").as_ref().unwrap(), &json!({ "stopReason": "end_turn" }));
assert_eq!(result(&results, "prompt").as_ref().unwrap(), &json!({ "stopReason": "end_turn" }));
let start = sent(&frames, "turn/start")[0];
assert_eq!(start["params"]["collaborationMode"]["mode"], "plan");
assert_eq!(start["params"]["collaborationMode"]["settings"]["model"], "gpt-5.6-luna");
}
#[tokio::test(flavor = "multi_thread")]
async fn toggling_plan_off_sends_an_explicit_default_once() {
let (results, _client, frames, _meta, _codex) =
replay_transcript(Scenario::PlanToggleThenPrompt, load(Scenario::Simple.file())).await;
assert_eq!(result(&results, "default").as_ref().unwrap(), &json!({ "stopReason": "end_turn" }));
let start = sent(&frames, "turn/start")[0];
assert_eq!(start["params"]["collaborationMode"]["mode"], "default");
}
#[tokio::test(flavor = "multi_thread")]
async fn informational_commands_report_skills_mcp_and_status() {
let skills = json!({ "data": [{ "skills": [
{ "name": "review", "enabled": true, "description": "Review changes" },
{ "name": "hidden", "enabled": false, "description": "Hidden" }
] }] });
let servers = json!({ "data": [
{ "name": "github", "runtimeStatus": "connected", "authStatus": "oAuth", "tools": { "search": {} } },
{ "name": "docs", "runtimeStatus": "failed", "authStatus": "unknown", "tools": {} }
] });
for (prompt, method, response, expected) in [
("/skills", "skills/list", skills, "Available skills:\n- review: Review changes"),
(
"/mcp",
"mcpServerStatus/list",
servers,
"MCP servers:\n- github: connected, 1 tools\n- docs: failed, 0 tools",
),
("/status", "", Value::Null, "**Session:**"),
] {
let calls: &[(&str, Value)] = if method.is_empty() { &[] } else { &[(method, response)] };
let calls: Vec<(&'static str, Value)> = calls
.iter()
.map(|(method, response)| {
let method = match *method {
"skills/list" => "skills/list",
"mcpServerStatus/list" => "mcpServerStatus/list",
other => panic!("unexpected method {other}"),
};
(method, response.clone())
})
.collect();
let (results, client, _frames, _meta, _codex) =
replay_transcript(Scenario::Command(prompt), command_transcript(&calls)).await;
let session = session_of(&results, "new");
assert_eq!(result(&results, "prompt").as_ref().unwrap(), &json!({ "stopReason": "end_turn" }));
assert!(client.text(&session, "agent_message_chunk").contains(expected), "{prompt}");
}
}
#[tokio::test(flavor = "multi_thread")]
async fn rename_and_logout_use_their_app_server_actions() {
let (results, client, frames, _meta, _codex) = replay_transcript(
Scenario::Command("/rename Better name"),
command_transcript(&[("thread/name/set", json!({}))]),
)
.await;
let session = session_of(&results, "new");
assert_eq!(sent(&frames, "thread/name/set")[0]["params"], json!({ "threadId": session, "name": "Better name" }));
let info = client.of(&session).into_iter().find(|u| u["sessionUpdate"] == "session_info_update").unwrap();
assert_eq!((info["title"].as_str(), info["userNamed"].as_bool()), (Some("Better name"), Some(true)));
let (results, client, frames, _meta, _codex) =
replay_transcript(Scenario::Command("/logout"), command_transcript(&[("account/logout", json!({}))])).await;
let session = session_of(&results, "new");
assert_eq!(sent(&frames, "account/logout").len(), 1);
assert_eq!(client.text(&session, "agent_message_chunk"), "Logged out from Codex account.");
}
#[tokio::test(flavor = "multi_thread")]
async fn goal_commands_set_pause_resume_and_clear_through_app_server() {
for (prompt, method, params, result) in [
(
"/goal fix the failing tests",
"thread/goal/set",
json!({ "threadId": "s", "objective": "fix the failing tests", "status": "active", "origin": "user" }),
json!({ "goal": { "status": "active" } }),
),
(
"/goal pause",
"thread/goal/set",
json!({ "threadId": "s", "status": "paused", "origin": "user" }),
json!({ "goal": { "status": "paused" } }),
),
(
"/goal resume",
"thread/goal/set",
json!({ "threadId": "s", "status": "active", "origin": "user" }),
json!({ "goal": { "status": "active" } }),
),
("/goal clear", "thread/goal/clear", json!({ "threadId": "s" }), json!({ "cleared": true })),
] {
let (results, _client, frames, _meta, _codex) =
replay_transcript(Scenario::Command(prompt), command_transcript(&[(method, result)])).await;
let session = session_of(&results, "new");
let sent = sent(&frames, method);
assert_eq!(sent.len(), 1, "{prompt}");
let mut expected = params;
expected["threadId"] = json!(session);
assert_eq!(sent[0]["params"], expected, "{prompt}");
}
}
#[tokio::test(flavor = "multi_thread")]
async fn missing_review_arguments_print_usage_without_starting_a_turn() {
for prompt in ["/review-branch", "/review-commit", "/rename", "/goal"] {
let (results, client, frames, _meta, _codex) =
replay_transcript(Scenario::Command(prompt), command_transcript(&[])).await;
let session = session_of(&results, "new");
assert_eq!(result(&results, "prompt").as_ref().unwrap(), &json!({ "stopReason": "end_turn" }));
assert!(sent(&frames, "turn/start").is_empty());
assert!(client.text(&session, "agent_message_chunk").starts_with("Command \""), "{prompt}");
}
}
#[tokio::test(flavor = "multi_thread")]
async fn mcp_reconnect_reloads_before_reporting_status() {
let servers =
json!({ "data": [{ "name": "github", "runtimeStatus": "connected", "authStatus": "oAuth", "tools": {} }] });
let (results, client, frames, _meta, _codex) = replay_transcript(
Scenario::Command("/mcp reconnect"),
command_transcript(&[("config/mcpServer/reload", json!({})), ("mcpServerStatus/list", servers)]),
)
.await;
let session = session_of(&results, "new");
assert_eq!(sent(&frames, "config/mcpServer/reload").len(), 1);
assert_eq!(sent(&frames, "mcpServerStatus/list").len(), 1);
assert!(client.text(&session, "agent_message_chunk").contains("github: connected"));
}
#[tokio::test(flavor = "multi_thread")]
async fn approvals_are_asked_and_answered() {
let (results, client, frames, _) = replay(Scenario::Approvals).await;
+45
Переглянути файл
@@ -138,6 +138,12 @@ pub(super) struct Settings {
pub model: String,
pub effort: Option<String>,
pub mode: Mode,
/// Codex's Default/Plan collaboration mode. It is sent with each turn because it is
/// part of the turn contract rather than the sandbox permission mode above.
pub collaboration_mode: String,
/// A mode just chosen by the user, sent once even when it is Default so a resumed Plan
/// thread is explicitly reset. Subsequent default turns can omit the field again.
pub collaboration_mode_override: Option<String>,
}
impl Settings {
@@ -156,6 +162,12 @@ impl Settings {
result.get("approvalPolicy").unwrap_or(&Value::Null),
result.get("sandbox").unwrap_or(&Value::Null),
),
collaboration_mode: result
.pointer("/collaborationMode/mode")
.and_then(Value::as_str)
.unwrap_or(DEFAULT_COLLABORATION_MODE)
.to_owned(),
collaboration_mode_override: None,
};
s.fit_effort(models);
s
@@ -194,6 +206,13 @@ impl Settings {
self.effort = Some(value.to_owned());
}
MODE => self.mode = Mode::parse(value).ok_or_else(|| format!("unknown mode {value}"))?,
COLLABORATION_MODE => {
if !matches!(value, DEFAULT_COLLABORATION_MODE | PLAN_COLLABORATION_MODE) {
return Err(format!("unknown collaboration mode {value}"));
}
self.collaboration_mode = value.to_owned();
self.collaboration_mode_override = Some(value.to_owned());
}
_ => return Err(format!("unknown setting {option}")),
}
Ok(())
@@ -203,6 +222,9 @@ impl Settings {
pub(super) const MODEL: &str = "model";
pub(super) const EFFORT: &str = "reasoning_effort";
pub(super) const MODE: &str = "mode";
pub(super) const COLLABORATION_MODE: &str = "collaboration_mode";
pub(super) const DEFAULT_COLLABORATION_MODE: &str = "default";
pub(super) const PLAN_COLLABORATION_MODE: &str = "plan";
/// ACP `configOptions`: model, reasoning effort (for models that have it) and mode.
pub(super) fn config_options(models: &[ModelInfo], s: &Settings) -> Value {
@@ -235,9 +257,32 @@ pub(super) fn config_options(models: &[ModelInfo], s: &Settings) -> Value {
"id": MODE, "name": "Mode", "category": "mode", "type": "select", "currentValue": s.mode.id(),
"options": Mode::ALL.iter().map(|m| select_value(m.id(), m.name(), Some(m.description()))).collect::<Vec<_>>(),
}));
out.push(json!({
"id": COLLABORATION_MODE,
"name": "Collaboration mode",
"category": "collaboration_mode",
"type": "select",
"currentValue": s.collaboration_mode,
"options": [
select_value(DEFAULT_COLLABORATION_MODE, "Default", Some("Execute changes directly")),
select_value(PLAN_COLLABORATION_MODE, "Plan", Some("Plan before making changes")),
],
}));
Value::Array(out)
}
/// `turn/start.collaborationMode`: the preset plus the selected model settings.
pub(super) fn collaboration_mode(settings: &Settings, models: &[ModelInfo]) -> Value {
json!({
"mode": settings.collaboration_mode_override.as_deref().unwrap_or(&settings.collaboration_mode),
"settings": {
"model": settings.model_slug(models),
"reasoning_effort": settings.effort,
"developer_instructions": null,
},
})
}
fn select_value(value: &str, name: &str, description: Option<&str>) -> Value {
let mut v = json!({ "value": value, "name": name });
if let Some(d) = description {
+93
Переглянути файл
@@ -0,0 +1,93 @@
//! A project trusted by the IDE may still be untrusted by Codex. Ask before changing
//! Codex's own decision; only its config API writes the current project's trust entry.
use super::*;
fn disabled_project<'a>(config: &'a Value, cwd: &str) -> Option<&'a Value> {
let folder = Path::new(cwd).join(".codex");
config.get("layers")?.as_array()?.iter().find(|layer| {
layer.pointer("/name/type").and_then(Value::as_str) == Some("project")
&& layer
.pointer("/name/dotCodexFolder")
.and_then(Value::as_str)
.is_some_and(|path| Path::new(path) == folder)
&& layer.get("disabledReason").and_then(Value::as_str).is_some_and(|reason| !reason.trim().is_empty())
})
}
impl CodexShim {
pub(super) async fn prepare_project_trust(&self, params: &Value) {
let Some(cwd) = params.get("cwd").and_then(Value::as_str) else { return };
if !self.state.lock().trust_checked.insert(cwd.to_owned()) {
return;
}
// Old app-servers may not expose config layers. Their warnings still reach the UI.
let Ok(Ok(config)) = tokio::time::timeout(
Duration::from_secs(5),
self.call("config/read", json!({ "cwd": cwd, "includeLayers": true })),
)
.await
else {
return;
};
let Some(layer) = disabled_project(&config, cwd) else { return };
let Some(client) = self.client.get() else { return };
let title = format!(
"Trust project in Codex: {cwd}? This saves trust in your Codex user configuration and allows \
this project's MCP servers, hooks and exec policies to load."
);
let permission = json!({
"sessionId": params.get("sessionId").and_then(Value::as_str).unwrap_or_default(),
"toolCall": {
"toolCallId": format!("codex-project-trust:{cwd}"),
"title": title, "kind": "edit",
"rawInput": { "project": cwd },
},
"options": [
// Permanent trust must never be auto-approved by the task's allow-once bypass.
{ "optionId": "codex-trust-project", "name": "Trust Project in Codex", "kind": "allow_always" },
{ "optionId": "codex-keep-untrusted", "name": "Keep Untrusted", "kind": "reject_once" },
],
});
let answer: Result<Value, RpcError> = client.request("session/request_permission", permission, None).await;
let approved = answer.as_ref().is_ok_and(|answer| {
answer.pointer("/outcome/outcome").and_then(Value::as_str) == Some("selected")
&& answer.pointer("/outcome/optionId").and_then(Value::as_str) == Some("codex-trust-project")
});
if !approved {
if let Some(reason) = layer.get("disabledReason").and_then(Value::as_str) {
self.warning(reason);
}
return;
}
// Quote the path as one key segment: dots and Windows backslashes are literal.
let mut write = json!({
"keyPath": format!("projects.{}.trust_level", json!(cwd)),
"value": "trusted", "mergeStrategy": "replace",
});
if let Some(version) = config["layers"]
.as_array()
.and_then(|layers| {
layers.iter().find(|layer| {
layer.pointer("/name/type").and_then(Value::as_str) == Some("user")
&& layer.pointer("/name/profile").is_none_or(Value::is_null)
})
})
.and_then(|layer| layer.get("version"))
.filter(|version| version.is_string())
{
write["expectedVersion"] = version.clone();
}
match self.call("config/value/write", write).await {
Err(error) => self.warning(format!("Codex could not save trust for {cwd}: {}", error.message)),
Ok(reply) if reply["status"] == "okOverridden" => {
self.warning(format!(
"Codex saved trust for {cwd}, but a higher-priority configuration overrides it. \
Project configuration may remain disabled; check the Codex configuration or contact your administrator."
));
}
_ => {}
}
// start/resume/fork now load the updated config before creating the thread.
}
}
+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
}
+252 -4
Переглянути файл
@@ -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,14 +902,30 @@ 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();
wait_for(&mgr_a, &task.id, AgentStatus::NeedsInput).await;
assert_eq!(names(mgr_a.commands("claude", None).await.unwrap()), ["review", "triage"]);
assert_eq!(names(mgr_a.commands("claude", Some(&task.id)).await.unwrap()), ["review", "triage"]);
// Other agents get only what they offered.
assert!(mgr_a.commands("codex", None).await.unwrap().is_empty());
// Other agents get only what they offered, plus verified native builtins.
assert_eq!(
names(mgr_a.commands("codex", None).await.unwrap()),
[
"plan",
"mcp",
"skills",
"status",
"review",
"review-branch",
"review-commit",
"compact",
"goal",
"rename",
"logout",
]
);
mgr_a.cancel(&task.id, None).unwrap();
wait_for(&mgr_a, &task.id, AgentStatus::Ready).await;
mgr_a.shutdown();
@@ -910,9 +945,27 @@ async fn builtin_commands_only_fill_verified_gaps_and_preserve_advertised_metada
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
let mgr = manager_at(tmp.path(), &tmp.path().join("models.json"), agent);
for provider in ["claude", "claude-acp", "opencode2", "codex", "custom"] {
for provider in ["claude", "claude-acp", "opencode2", "custom"] {
assert!(mgr.commands(provider, None).await.unwrap().is_empty(), "{provider}");
}
let commands = mgr.commands("codex", None).await.unwrap();
assert_eq!(
commands.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(),
[
"plan",
"mcp",
"skills",
"status",
"review",
"review-branch",
"review-commit",
"compact",
"goal",
"rename",
"logout",
]
);
assert_eq!(commands[1].hint.as_deref(), Some("[reconnect]"));
let commands = mgr.commands("opencode", None).await.unwrap();
assert_eq!(commands.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["compact"]);
let task = mgr
@@ -923,6 +976,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 +1035,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 +1159,7 @@ async fn steers_through_session_steering() {
config: vec![],
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -1140,6 +1196,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 +1252,7 @@ async fn subagents_get_their_own_conversation() {
config: vec![],
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -1290,6 +1348,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 +1398,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 +1467,7 @@ async fn skipped_qwen_questions_cancel_the_request() {
config: vec![],
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -1446,6 +1507,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 +1529,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 +1579,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,11 +1630,18 @@ async fn renamed_titles_survive_updates_forks_and_restart() {
config: Vec::new(),
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let handle = mgr.task(&task.id).unwrap();
// `/rename` reports an explicit title through the same update; later automatic names
// must not replace it even though AgentManager.rename was not called.
handle
.on_update(None, &json!({"sessionUpdate": "session_info_update", "title": "Command title", "userNamed": true}));
handle.on_update(None, &json!({"sessionUpdate": "session_info_update", "title": "Automatic title"}));
assert_eq!(handle.state.lock().task.title, "Command title");
assert!(mgr.rename(&task.id, " ").is_err());
let initial = handle.state.lock().task.title.clone();
for title in [initial, "My task".to_owned(), "名".repeat(205)] {
@@ -1591,6 +1662,67 @@ async fn renamed_titles_survive_updates_forks_and_restart() {
restored.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn startup_warnings_survive_replay_and_restart_without_failing_the_task() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
let mgr = manager(tmp.path(), agent.clone());
let task = mgr
.create(NewAgentTask { provider: "claude".into(), prompt: text("again"), ..Default::default() })
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let handle = mgr.task(&task.id).unwrap();
handle.replaying.store(true, Ordering::Release);
handle.turn_started.store(false, Ordering::Release);
let client = Client { task: Arc::downgrade(&handle) };
client.on_notification(WARNING_NOTIFICATION, json!({"message": "Project MCP config is disabled until trusted."}));
client.on_notification(WARNING_NOTIFICATION, json!({"message": " "}));
client.on_notification(WARNING_NOTIFICATION, json!({}));
assert_eq!(handle.state.lock().task.status, AgentStatus::Ready);
assert!(!handle.turn_started.load(Ordering::Acquire));
mgr.shutdown();
let restored = manager(tmp.path(), agent);
let handle = restored.task(&task.id).unwrap();
assert_eq!(handle.state.lock().conversation.main.entries.iter().filter(|entry| matches!(entry, AgentEntry::Error {message} if message == "Project MCP config is disabled until trusted.")).count(), 1);
restored.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn persistent_project_trust_needs_confirmation_even_with_bypass_and_is_denied_in_side_chats() {
let tmp = tempfile::tempdir().unwrap();
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let task = mgr
.create(NewAgentTask { provider: "claude".into(), prompt: text("again"), ..Default::default() })
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let handle = mgr.task(&task.id).unwrap();
handle.state.lock().task.config = config::options_of(&json!({"configOptions": [{
"id": "mode", "category": "mode", "type": "select", "currentValue": "full-access",
"options": [{"value": "full-access", "name": "Full Access"}]
}]}));
assert!(config::bypass_approvals(&handle.state.lock().task.config));
let params = json!({"toolCall": {"toolCallId": "trust", "kind": "edit", "title": "Trust Project in Codex"},
"options": [
{"optionId": "codex-trust-project", "name": "Trust Project in Codex", "kind": "allow_always"},
{"optionId": "codex-keep-untrusted", "name": "Keep Untrusted", "kind": "reject_once"}
]});
let asking = {
let handle = handle.clone();
let params = params.clone();
tokio::task::spawn_blocking(move || handle.ask_permission(&params))
};
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
assert!(!asking.is_finished());
let id = *handle.permissions.lock().keys().next().unwrap();
mgr.respond(&task.id, id, Some("codex-keep-untrusted".into())).unwrap();
assert_eq!(asking.await.unwrap()["outcome"]["optionId"], "codex-keep-untrusted");
handle.state.lock().ephemeral = true;
assert_eq!(handle.ask_permission(&params)["outcome"]["optionId"], "codex-keep-untrusted");
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn forks_rollbacks_and_steering() {
let tmp = tempfile::tempdir().unwrap();
@@ -1603,6 +1735,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 +1815,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 +1869,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 +1904,7 @@ async fn thinking_levels_are_remembered_per_provider_and_model() {
config: vec![],
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -1815,6 +1951,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 +1993,7 @@ async fn upfront_effort_is_validated_after_changing_model_before_the_prompt() {
],
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -1887,6 +2025,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 +2050,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 +2086,7 @@ async fn reported_levels_refresh_even_without_a_model_option() {
config: vec![],
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -1999,6 +2140,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 +2194,7 @@ async fn bypass_approvals_keeps_both_question_dialects_pending_but_allows_permis
},
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -2113,6 +2256,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 +2299,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 +2324,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 +2346,7 @@ async fn a_full_access_mode_approves_tool_requests() {
config: Vec::new(),
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -2228,6 +2375,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 +2423,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 +2451,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 +2504,7 @@ async fn task_project_root_controls_local_and_worktree_repositories() {
config: vec![],
isolation,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -2560,6 +2711,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 +2790,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 +2825,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 +2878,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 +2966,7 @@ async fn delete_running_agent(no_load: bool) {
config: vec![],
isolation: Isolation::Worktree,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -2926,6 +3082,7 @@ async fn config_choice_shows_before_the_agent_answers() {
config: vec![],
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -3031,6 +3188,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 +3295,7 @@ impl Checkout {
config: Vec::new(),
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -3343,6 +3502,7 @@ async fn security_policy_auto_approves_whitelist_and_rejects_blacklist() {
config: vec![],
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -3373,6 +3533,7 @@ async fn security_policy_auto_approves_whitelist_and_rejects_blacklist() {
config: vec![],
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -3410,6 +3571,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 +3609,7 @@ async fn ephemeral_tasks_stay_in_memory_only() {
config: vec![],
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -3461,6 +3624,7 @@ async fn ephemeral_tasks_stay_in_memory_only() {
config: vec![],
isolation: Isolation::Local,
base: None,
..Default::default()
},
&source.id,
)
@@ -3562,6 +3726,7 @@ async fn ephemeral_tasks_deny_write_permissions() {
config: vec![],
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -3587,6 +3752,7 @@ async fn ephemeral_tasks_deny_write_permissions() {
config: vec![],
isolation: Isolation::Local,
base: None,
..Default::default()
},
&source.id,
)
@@ -3659,6 +3825,7 @@ async fn attention_finished_not_cancelled() {
config: Vec::new(),
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -3674,6 +3841,7 @@ async fn attention_finished_not_cancelled() {
config: Vec::new(),
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -3710,6 +3878,7 @@ async fn attention_failed() {
config: Vec::new(),
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -3735,6 +3904,7 @@ async fn attention_input_not_auto_bypass() {
config: Vec::new(),
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -3752,6 +3922,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 +3949,7 @@ async fn attention_not_emitted_on_restore() {
config: Vec::new(),
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
@@ -3794,6 +3966,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 +4139,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 +4163,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();
+107 -18
Переглянути файл
@@ -310,6 +310,8 @@ fn artifact_steps(
.find(|f| f.module == artifact.module || f.module.is_empty() && artifact.module == ".")
.or_else(|| ps.facets.iter().find(|f| f.kind == "web"));
let staging = cache.join("artifacts").join(file_name(&artifact.name));
// What the last build laid out in a folder the user chose, so the next one replaces only that.
let record = cache.join("artifacts").join(format!("{}.files", file_name(&artifact.name)));
let mut steps = Vec::new();
match (artifact.kind, war) {
(ArtifactKind::Jar, None) => {
@@ -324,7 +326,11 @@ fn artifact_steps(
manifest.push_str(&format!("Class-Path: {}\r\n", names.join(" ")));
}
steps.push(BuildStep::action(
Action::Layout { into: staging.clone(), entries: vec![(classes.to_path_buf(), PathBuf::new())] },
Action::Layout {
into: staging.clone(),
entries: vec![(classes.to_path_buf(), PathBuf::new())],
record: None,
},
root,
));
// The jar's Class-Path names the libraries next to it.
@@ -332,6 +338,7 @@ fn artifact_steps(
Action::Layout {
into: out.clone(),
entries: libraries.iter().map(|l| (l.clone(), file_of(l))).collect(),
record: Some(record),
},
root,
));
@@ -353,7 +360,9 @@ fn artifact_steps(
for lib in &libraries {
entries.push((lib.clone(), Path::new("WEB-INF/lib").join(file_of(lib))));
}
steps.push(BuildStep::action(Action::Layout { into: exploded.clone(), entries }, root));
// The exploded output may be a folder the user chose; the staging folder is the IDE's own.
let record = (exploded != staging).then_some(record);
steps.push(BuildStep::action(Action::Layout { into: exploded.clone(), entries, record }, root));
let archive = war
.map(Path::to_path_buf)
.or_else(|| (kind != ArtifactKind::WarExploded).then(|| artifact_file(root, artifact)));
@@ -407,8 +416,10 @@ pub(crate) enum Action {
/// relative paths; files that are already up to date are left alone.
CopyResources { from: Vec<PathBuf>, to: PathBuf },
/// Lays out an artifact in `into`: each folder's content or file goes to its relative
/// place (`""` = the top). What is no longer laid out is removed.
Layout { into: PathBuf, entries: Vec<(PathBuf, PathBuf)> },
/// place (`""` = the top). What is no longer laid out is removed: without `record`, `into`
/// is the IDE's own folder and is laid out afresh; with it, `into` is a folder the user chose
/// and only the files the previous layout recorded there are removed, never anything else.
Layout { into: PathBuf, entries: Vec<(PathBuf, PathBuf)>, record: Option<PathBuf> },
/// Zips the folder `from` into the archive `to`, with this manifest first.
Archive { from: PathBuf, to: PathBuf, manifest: Option<String> },
}
@@ -441,29 +452,31 @@ impl Action {
}
Ok(format!("{copied} resource file(s) copied"))
}
Action::Layout { into, entries } => {
// A fresh layout: files dropped from the sources must not linger in the artifact.
Action::Layout { into, entries, record } => {
if entries.iter().any(|(from, _)| from.starts_with(into)) {
return Err(IdeError::invalid(format!(
"The artifact output folder {} holds files the artifact is made of",
into.display()
)));
}
if into.exists() {
if record.is_none() && into.exists() {
fs::remove_dir_all(into)
.map_err(|e| IdeError::internal(format!("cannot delete {} ({e})", into.display())))?;
}
let mut copied = 0;
let mut written = Vec::new();
for (from, to) in entries {
let target = into.join(to);
if from.is_dir() {
copied += copy_tree(from, &target, cancel)?;
copy_tree(from, &target, &mut written, cancel)?;
} else if from.is_file() {
copy_file(from, &target)?;
copied += 1;
written.push(target);
}
}
Ok(format!("{copied} file(s) laid out"))
if let Some(record) = record {
replace_recorded(into, record, &written)?;
}
Ok(format!("{} file(s) laid out", written.len()))
}
Action::Archive { from, to, manifest } => {
archive(from, to, manifest.as_deref(), cancel)?;
@@ -482,23 +495,62 @@ fn copy_file(from: &Path, to: &Path) -> IdeResult<()> {
Ok(())
}
fn copy_tree(from: &Path, to: &Path, cancel: &CancellationToken) -> IdeResult<usize> {
fn copy_tree(from: &Path, to: &Path, written: &mut Vec<PathBuf>, cancel: &CancellationToken) -> IdeResult<()> {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let Ok(entries) = fs::read_dir(from) else { return Ok(0) };
let mut copied = 0;
let Ok(entries) = fs::read_dir(from) else { return Ok(()) };
for e in entries.flatten() {
let Ok(t) = e.file_type() else { continue };
let target = to.join(e.file_name());
if t.is_dir() {
copied += copy_tree(&e.path(), &target, cancel)?;
copy_tree(&e.path(), &target, written, cancel)?;
} else if t.is_file() {
copy_file(&e.path(), &target)?;
copied += 1;
written.push(target);
}
}
Ok(copied)
Ok(())
}
/// Removes the files the previous layout recorded in `into` that this one didn't write
/// (and the folders that leaves empty), then records `written` for the next layout.
fn replace_recorded(into: &Path, record: &Path, written: &[PathBuf]) -> IdeResult<()> {
let now: std::collections::HashSet<PathBuf> =
written.iter().filter_map(|p| p.strip_prefix(into).ok().map(Path::to_path_buf)).collect();
let before = fs::read_to_string(record).unwrap_or_default();
let mut lines = before.lines();
// The record names its folder first: one made for another output folder removes nothing.
let same = lines.next().is_some_and(|dir| Path::new(dir) == into);
for rel in lines.filter(|_| same).map(PathBuf::from) {
// Only plain relative paths inside `into`: a damaged record must not reach elsewhere.
if rel.as_os_str().is_empty()
|| now.contains(&rel)
|| rel.components().any(|c| !matches!(c, std::path::Component::Normal(_)))
{
continue;
}
let file = into.join(&rel);
if file.is_file() {
let _ = fs::remove_file(&file);
let mut dir = file.parent();
while let Some(d) = dir.filter(|d| *d != into && d.starts_with(into)) {
if fs::remove_dir(d).is_err() {
break;
}
dir = d.parent();
}
}
}
let mut list: Vec<String> = now.iter().map(|p| p.to_string_lossy().into_owned()).collect();
list.sort();
list.insert(0, into.to_string_lossy().into_owned());
if let Some(parent) = record.parent() {
fs::create_dir_all(parent)
.map_err(|e| IdeError::internal(format!("cannot create {} ({e})", parent.display())))?;
}
fs::write(record, list.join("\n"))
.map_err(|e| IdeError::internal(format!("cannot write {} ({e})", record.display())))
}
fn archive(from: &Path, to: &Path, manifest: Option<&str>, cancel: &CancellationToken) -> IdeResult<()> {
@@ -812,8 +864,45 @@ mod tests {
let tmp = tempfile::tempdir().unwrap();
let web = tmp.path().join("WebRoot");
write(&web.join("a.jsp"), "");
let action = Action::Layout { into: tmp.path().to_path_buf(), entries: vec![(web.clone(), PathBuf::new())] };
let action = Action::Layout {
into: tmp.path().to_path_buf(),
entries: vec![(web.clone(), PathBuf::new())],
record: None,
};
assert!(action.run(&CancellationToken::new()).is_err());
assert!(web.join("a.jsp").is_file());
}
#[test]
fn a_chosen_output_folder_keeps_what_the_artifact_did_not_put_there() {
let tmp = tempfile::tempdir().unwrap();
let project = tmp.path().join("project");
write(&project.join("src/A.java"), "class A {}");
write(&project.join(".git/HEAD"), "ref: refs/heads/main");
let libs = tmp.path().join("libs");
write(&libs.join("a.jar"), "a");
write(&libs.join("b.jar"), "b");
let record = tmp.path().join("cache/artifacts/app.files");
let layout = |names: &[&str]| Action::Layout {
into: project.clone(),
entries: names.iter().map(|n| (libs.join(n), PathBuf::from(n))).collect(),
record: Some(record.clone()),
};
layout(&["a.jar", "b.jar"]).run(&CancellationToken::new()).unwrap();
assert!(project.join("a.jar").is_file() && project.join("b.jar").is_file());
// A library dropped from the artifact goes; the project's own files stay.
layout(&["a.jar"]).run(&CancellationToken::new()).unwrap();
assert!(project.join("a.jar").is_file() && !project.join("b.jar").exists());
assert!(project.join("src/A.java").is_file() && project.join(".git/HEAD").is_file());
// A damaged record never reaches outside the folder.
write(&record, &format!("{}\n../outside.txt", project.display()));
write(&tmp.path().join("outside.txt"), "x");
layout(&["a.jar"]).run(&CancellationToken::new()).unwrap();
assert!(tmp.path().join("outside.txt").is_file());
// Nor does one made for another output folder.
write(&project.join("c.jar"), "mine");
write(&record, "/elsewhere\nc.jar");
layout(&["a.jar"]).run(&CancellationToken::new()).unwrap();
assert!(project.join("c.jar").is_file());
}
}
+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 });
+241
Переглянути файл
@@ -550,6 +550,24 @@ pub async fn lsp_implementations(
result
}
/// Refines the implementations `targets` of the method at `pos` to their declarations (Java
/// dependencies' class files point at the start of the class). Cancel with
/// `cancel_request(request)`.
pub async fn lsp_implementation_locations(
host: &Host,
window: &str,
request: RequestId,
doc: DocId,
pos: Pos,
targets: Vec<Location>,
) -> IdeResult<Vec<Location>> {
let lsp = host.project(window)?.lsp.clone();
let (_, cancel) = begin_position_request(host, window, request, doc, pos).await?;
let result = lsp.implementation_locations(doc, pos, targets, cancel).await;
host.end_request(request);
result
}
/// Go to Implementation of the symbol at `pos`. Implementations found before a slower
/// search for the rest (Java: the project's, before the dependencies') arrive on
/// `on_partial`; the result has them all. Cancel with `cancel_request(request)`.
@@ -1173,6 +1191,166 @@ 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 refactoring 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
}
/// The Java class to extract an interface from: its members and the packages for the interface.
pub async fn lsp_extract_interface_info(
host: &Host,
window: &str,
request: RequestId,
doc: DocId,
pos: Pos,
) -> IdeResult<ExtractInterfaceInfo> {
let project = host.project(window)?;
let cancel = host.begin_request(request);
let result = project.lsp.extract_interface_info(doc, pos, cancel).await;
host.end_request(request);
result
}
/// Checks extracting a Java interface and computes its edit without applying it; `destination`
/// is one of the info's packages.
#[allow(clippy::too_many_arguments)]
pub async fn lsp_extract_interface(
host: &Host,
window: &str,
request: RequestId,
doc: DocId,
pos: Pos,
members: Vec<String>,
name: String,
destination: String,
confirmation: Option<String>,
) -> IdeResult<ServerRefactored> {
let destination = json_argument(&destination)?;
let project = host.project(window)?;
let cancel = host.begin_request(request);
let result = project.lsp.extract_interface(doc, pos, members, name, destination, confirmation, cancel).await;
host.end_request(request);
let mut extracted = result?;
blocking(move || {
if let Some(edit) = &mut extracted.edit {
project.documents.prepare_workspace_edit(edit)?;
}
Ok(extracted)
})
.await
}
pub async fn lsp_rename(
host: &Host,
window: &str,
@@ -1827,6 +2005,17 @@ pub(crate) fn register(d: &mut Dispatcher) {
let on_partial = c.sender("onPartial")?;
lsp_goto_implementation(&c.host, &c.window, c.arg("request")?, c.arg("doc")?, c.arg("pos")?, on_partial).await
});
d.add("lsp_implementation_locations", |c| async move {
lsp_implementation_locations(
&c.host,
&c.window,
c.arg("request")?,
c.arg("doc")?,
c.arg("pos")?,
c.arg("targets")?,
)
.await
});
d.add(
"lsp_resolve_class_file",
|c| async move { lsp_resolve_class_file(&c.host, &c.window, c.arg("path")?).await },
@@ -1896,6 +2085,58 @@ 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_extract_interface_info", |c| async move {
lsp_extract_interface_info(&c.host, &c.window, c.arg("request")?, c.arg("doc")?, c.arg("pos")?).await
});
d.add("lsp_extract_interface", |c| async move {
lsp_extract_interface(
&c.host,
&c.window,
c.arg("request")?,
c.arg("doc")?,
c.arg("pos")?,
c.arg("members")?,
c.arg("name")?,
c.arg("destination")?,
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"
+3
Переглянути файл
@@ -19,10 +19,13 @@ use std::time::{Duration, Instant};
pub(crate) const SERVER: &str = "jdtls";
pub(crate) mod configuration;
mod extract_interface;
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);
+128
Переглянути файл
@@ -0,0 +1,128 @@
//! Extract Interface through jdtls' own requests: `java/checkExtractInterfaceStatus` lists the
//! members of the file's class an interface can declare and the packages it can go to,
//! `java/getRefactorEdit` (`extractInterface`) creates the interface, makes the class implement
//! it and uses it where possible. The UI picks the name, package and members and applies the edit.
use super::COMMAND_TIMEOUT;
use super::signature::{RefactorEdit, changed};
use crate::types::{ExtractInterfaceInfo, InterfaceMember, ProblemSeverity, RefactoringProblem, ServerRefactored};
use crate::{LspManager, convert};
use ide_core::{CancellationToken, DocId, IdeError, IdeResult, Pos};
use serde::Deserialize;
use serde_json::{Value, json};
const FEATURE: &str = "Extract Interface";
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Status {
#[serde(default)]
members: Vec<InterfaceMember>,
#[serde(default)]
sub_type_name: String,
#[serde(default)]
destination_response: Destinations,
}
#[derive(Default, Deserialize)]
#[serde(rename_all = "camelCase")]
struct Destinations {
#[serde(default)]
destinations: Vec<Value>,
}
fn info_of(status: Option<Status>) -> IdeResult<ExtractInterfaceInfo> {
let status = status
.filter(|s| !s.sub_type_name.is_empty())
.ok_or_else(|| IdeError::invalid("The file should declare a class"))?;
Ok(ExtractInterfaceInfo {
class_name: status.sub_type_name,
members: status.members,
packages: status.destination_response.destinations.iter().map(Value::to_string).collect(),
})
}
impl LspManager {
/// The class of the file at `doc`, its members and the packages for the interface.
pub async fn extract_interface_info(
&self,
doc: DocId,
pos: Pos,
cancel: CancellationToken,
) -> IdeResult<ExtractInterfaceInfo> {
let (snap, t) = self.jdtls_target(doc, FEATURE).await?;
let params = Self::signature_context(&snap, &t, pos);
let status: Option<Status> =
self.call(&t, "java/checkExtractInterfaceStatus", params, Some(&cancel), COMMAND_TIMEOUT).await?;
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
info_of(status)
}
/// Checks extracting `members` into the interface `name` in `package` (a package from
/// [`Self::extract_interface_info`]) and computes the edit without applying it.
#[allow(clippy::too_many_arguments)]
pub async fn extract_interface(
&self,
doc: DocId,
pos: Pos,
members: Vec<String>,
name: String,
package: Value,
confirmation: Option<String>,
cancel: CancellationToken,
) -> IdeResult<ServerRefactored> {
let (snap, t) = self.jdtls_target(doc, FEATURE).await?;
let mut params = json!({
"command": "extractInterface",
"context": Self::signature_context(&snap, &t, pos),
"options": { "tabSize": 4, "insertSpaces": true },
"commandArguments": [members, name, package],
});
if let Some(token) = confirmation {
params["confirmationToken"] = json!(token);
}
let answer: Option<RefactorEdit> =
self.call(&t, "java/getRefactorEdit", params, Some(&cancel), COMMAND_TIMEOUT).await?;
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
// jdtls answers nothing when its checks fail, and reports why in a message of its own.
let Some(answer) = answer else {
return Ok(ServerRefactored {
problems: vec![RefactoringProblem {
severity: ProblemSeverity::Fatal,
message: "The interface could not be extracted".to_owned(),
}],
edit: None,
confirmation: None,
});
};
let conv = self.conv(t.enc());
Ok(changed(answer, |e| convert::workspace_edit(&conv, e)))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reads_the_members_and_packages() {
let status: Status = serde_json::from_value(json!({
"members": [
{ "name": "area", "typeName": "double", "parameters": [], "handleIdentifier": "=p/src<a{Shape.java[Shape~area" },
{ "name": "UNIT", "typeName": "int", "handleIdentifier": "=p/src<a{Shape.java[Shape^UNIT" },
],
"subTypeName": "Shape",
"destinationResponse": { "destinations": [{ "displayName": "a", "isParentOfSelectedFile": true }] },
}))
.unwrap();
let info = info_of(Some(status)).unwrap();
assert_eq!(info.class_name, "Shape");
assert_eq!(info.members[0].parameters.as_deref(), Some(&[][..]));
assert_eq!(info.members[1].parameters, None);
assert_eq!(serde_json::from_str::<Value>(&info.packages[0]).unwrap()["displayName"], "a");
assert!(info_of(None).is_err());
}
}
+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))
}
pub(super) 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());
}
}
+96
Переглянути файл
@@ -434,6 +434,11 @@ async fn library_sources(snap: &DocSnap, root: &Path, pos: Pos, locs: Vec<Locati
const JAVA_IMPLEMENTATIONS: &str = "openidea.java.implementations";
/// jdtls' locations of the implementations of the method at a position in the classes named
/// with it, for implementation classes in dependencies: its standard request puts those at the
/// start of the decompiled class instead of at the method.
const JAVA_IMPLEMENTATION_LOCATIONS: &str = "openidea.java.implementationLocations";
/// The answer of [`JAVA_IMPLEMENTATIONS`]: `complete` when the type is declared in the
/// sources, so no dependency can implement it.
#[derive(serde::Deserialize)]
@@ -442,6 +447,13 @@ struct SourceImplementations {
complete: bool,
}
/// The answer of [`JAVA_IMPLEMENTATION_LOCATIONS`]: one entry per requested class, `None` when
/// it has no implementation of the method.
#[derive(serde::Deserialize)]
struct TargetImplementations {
locations: Vec<Option<lsp::Location>>,
}
/// Receives the implementations found so far, before a slower search for the rest.
type Partial<'a> = Option<&'a (dyn Fn(Vec<Location>) + Send + Sync)>;
@@ -1810,6 +1822,84 @@ impl LspManager {
out
}
/// jdtls: where the implementation methods of the method at `pos` are declared in the
/// dependency classes `locs` point at. Its standard request answers those with `0:0`, the
/// start of the class file's decompiled source; [`JAVA_IMPLEMENTATION_LOCATIONS`] resolves
/// the declaration itself.
async fn java_implementation_locations(
&self,
snap: &DocSnap,
t: &Target,
pos: Pos,
locs: Vec<Location>,
cancel: Option<&CancellationToken>,
) -> Vec<Location> {
if t.server.name != "jdtls" || !t.caps().commands().iter().any(|c| c == JAVA_IMPLEMENTATION_LOCATIONS) {
return locs;
}
let targets: Vec<(usize, String)> = locs
.iter()
.enumerate()
.filter_map(|(i, l)| {
let uri = l.uri.as_deref()?;
(virtual_doc::scheme(uri) == "jdt" && l.range.start.line == 0).then(|| (i, uri.to_owned()))
})
.collect();
if targets.is_empty() {
return locs;
}
let params = snap.pos_params(t, pos);
let arguments = json!([
params["textDocument"]["uri"],
params["position"]["line"],
params["position"]["character"],
targets.iter().map(|(_, uri)| uri).collect::<Vec<_>>(),
]);
let result: IdeResult<TargetImplementations> = self
.call(
t,
"workspace/executeCommand",
json!({ "command": JAVA_IMPLEMENTATION_LOCATIONS, "arguments": arguments }),
cancel,
LONG_TIMEOUT,
)
.await;
let found = match result {
Ok(found) if found.locations.len() == targets.len() => found,
Ok(_) => return locs,
Err(e) => {
tracing::debug!("{JAVA_IMPLEMENTATION_LOCATIONS}: {}", e.message);
return locs;
}
};
let mut out = locs;
for ((i, _), loc) in targets.into_iter().zip(found.locations) {
if let Some(loc) = loc.as_ref().and_then(|l| self.conv(t.enc()).location(l)) {
out[i] = loc;
}
}
out
}
/// Refines the implementation `locs` of the method at `pos`: jdtls puts an implementation in
/// a dependency at the start of its decompiled class instead of at the method, which matters
/// when the gutter marker's targets are opened one by one.
pub async fn implementation_locations(
&self,
doc: DocId,
pos: Pos,
locs: Vec<Location>,
cancel: CancellationToken,
) -> IdeResult<Vec<Location>> {
let (_, cap, feature) = goto_method(GotoKind::Implementation);
let (snap, targets) = self.doc_targets(doc, feature, |c| c.has(cap)).await?;
let mut out = locs;
for t in &targets {
out = self.java_implementation_locations(&snap, t, pos, out, Some(&cancel)).await;
}
Ok(out)
}
async fn goto_in(
&self,
snap: &DocSnap,
@@ -1849,6 +1939,12 @@ impl LspManager {
Ok(Some(r)) => {
let locs = convert::goto_response(&self.conv(t.enc()), r);
let locs = library_sources(snap, &self.project_root, pos, locs).await;
// Only explicit Go to Implementation: gutter markers ask for every line.
let locs = if method == "textDocument/implementation" && partial.is_some() {
self.java_implementation_locations(snap, t, pos, locs, cancel).await
} else {
locs
};
self.note_virtual(&t.server, locs.iter().map(|l| l.uri.as_deref()));
self.note_arduino_sources(&t.server, &locs);
let locs = self.jdt_library_classes(snap, pos, locs).await;
+68
Переглянути файл
@@ -504,6 +504,74 @@ 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 member Extract Interface can declare in the new interface.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct InterfaceMember {
pub name: String,
/// The method's return type or the field's type.
pub type_name: String,
/// The method's parameter types; `None` for a field.
pub parameters: Option<Vec<String>>,
/// The server's handle of the member, passed back unchanged.
pub handle_identifier: String,
}
/// What Extract Interface starts from: the file's class, the members the interface can declare and
/// the packages it can go to (as JSON, passed back unchanged).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct ExtractInterfaceInfo {
pub class_name: String,
pub members: Vec<InterfaceMember>,
pub packages: Vec<String>,
}
/// A refactoring checked by the server (Change Signature, Move, Extract Interface): 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 {
+46
Переглянути файл
@@ -3483,6 +3483,52 @@ async fn java_implementations_come_from_sources_first() {
assert_eq!(s.requested("textDocument/implementation").len(), 3);
}
#[tokio::test(flavor = "multi_thread")]
async fn java_dependency_implementations_point_at_the_method() {
let caps = json!({
"textDocumentSync": 1,
"implementationProvider": true,
"executeCommandProvider": { "commands": ["openidea.java.implementations", "openidea.java.implementationLocations"] },
});
let h = harness_for("java", "java", &[("jdtls", caps)], &[]);
let (doc, _) = h.open("Repo.java", "interface Repo {\n void save(String item);\n}\n");
h.wait_status("jdtls", ServerStatus::Ready).await;
let s = h.launcher.state("jdtls");
let class_uri = "jdt://contents/lib.jar/zoo/RepoImpl.java?=p/lib.jar%3Czoo%28RepoImpl.class";
let method = json!({
"uri": class_uri,
"range": {"start":{"line":4,"character":4},"end":{"line":6,"character":5}},
});
let at_zero = json!({
"uri": class_uri,
"range": {"start":{"line":0,"character":0},"end":{"line":0,"character":0}},
});
let refined = method.clone();
*s.responder.lock() = Some(Arc::new(move |_, method, params| match method {
"workspace/executeCommand" if params["command"] == "openidea.java.implementations" => {
Some(json!({ "locations": [], "complete": false }))
}
"workspace/executeCommand" if params["command"] == "openidea.java.implementationLocations" => {
assert_eq!(params["arguments"][3], json!([class_uri]));
Some(json!({ "locations": [refined] }))
}
"textDocument/implementation" => Some(json!([at_zero])),
_ => None,
}));
let partial = Mutex::new(Vec::new());
let found = h
.mgr
.goto_implementation(doc, Pos::new(1, 9), Default::default(), &|locs| partial.lock().push(locs.to_vec()))
.await
.unwrap();
assert_eq!(found.len(), 1);
assert_eq!(found[0].uri.as_deref(), Some(class_uri));
assert_eq!(found[0].range.start.line, 4);
assert_eq!(s.requested("textDocument/implementation").len(), 1);
let commands = s.requested("workspace/executeCommand");
assert!(commands.iter().any(|r| r["command"] == "openidea.java.implementationLocations"));
}
#[tokio::test(flavor = "multi_thread")]
async fn navigation_rename_format_and_decorations() {
let h = harness(&[("mock", incremental_caps())]);
+19 -1
Переглянути файл
@@ -745,7 +745,8 @@ pub fn native_tsdk(root: &Path, s: &Settings) -> Option<PathBuf> {
}
}
const PYTHON_SERVERS: [&str; 7] = ["basedpyright", "pyright", "ty", "pyrefly", "pylsp", "jedi-language-server", "ruff"];
const PYTHON_SERVERS: [&str; 8] =
["basedpyright", "pyright", "ty", "pyrefly", "pylsp", "jedi-language-server", "ruff", "djlsp"];
pub(crate) fn merge(base: &mut Value, layer: Value) {
match (base, layer) {
@@ -979,6 +980,16 @@ pub fn resolve_run_command(config: &mut RunConfig, root: &Path, s: &Settings) {
}
}
/// The environment folder holding `python` (`<env>/bin/python`, `<env>/Scripts/python.exe`):
/// a virtualenv, or a conda or pixi environment.
fn environment_of(python: &Path) -> Option<PathBuf> {
venv_of(python).or_else(|| {
let bin = python.parent()?;
let env = bin.parent()?;
matches!(bin.file_name()?.to_str()?, "bin" | "Scripts").then(|| env.to_path_buf())
})
}
pub fn configure_server(cfg: &mut LanguageServerConfig, root: &Path, server_root: &Path, s: &Settings) {
let mut path_dirs: Vec<PathBuf> = Vec::new();
if let Some(custom) = tool_command(root, s, &cfg.command) {
@@ -1002,6 +1013,13 @@ pub fn configure_server(cfg: &mut LanguageServerConfig, root: &Path, server_root
"basedpyright" | "pyright" => merge_init_options(cfg, json!({ "python": { "pythonPath": p } })),
"pylsp" => merge_init_options(cfg, json!({ "pylsp": { "plugins": { "jedi": { "environment": p } } } })),
"jedi-language-server" => merge_init_options(cfg, json!({ "workspace": { "environmentPath": p } })),
// Django's template tags, filters and template folders are read by running a script
// with the interpreter in one of these environment folders.
"djlsp" => {
if let Some(env) = environment_of(&python) {
merge_init_options(cfg, json!({ "env_directories": [env.to_string_lossy()] }));
}
}
_ => {}
}
if let Some(venv) = venv_of(&python) {
+1 -1
Переглянути файл
@@ -1588,7 +1588,7 @@ pub fn usages_bundle(data_dir: &Path) -> Option<PathBuf> {
install_bundle(
data_dir,
"java-usages",
"1.14.0",
"1.15.0",
include_bytes!("../../../java/java-usages/openidea-java-usages.jar"),
)
}
+12
Переглянути файл
@@ -190,6 +190,18 @@ fn pyright_gets_python_path_and_venv_env() {
assert!(cfg.env["PATH"].starts_with(&*tmp.path().join(".venv").join(bin_dir()).to_string_lossy()));
}
#[test]
fn djlsp_reads_django_from_the_project_environment() {
let tmp = tempfile::tempdir().unwrap();
let python = fake_venv(tmp.path(), "venvs/web");
let mut s = Settings::default();
s.languages.python.interpreter = python.to_string_lossy().into_owned();
let mut cfg = server("djlsp");
configure_server(&mut cfg, tmp.path(), tmp.path(), &s);
let opts = serde_json::to_value(cfg.initialization_options.unwrap()).unwrap();
assert_eq!(opts["env_directories"], serde_json::json!([tmp.path().join("venvs/web").to_string_lossy()]));
}
#[test]
fn a_run_target_interpreter_hides_local_pythons() {
let tmp = tempfile::tempdir().unwrap();
+11
Переглянути файл
@@ -322,6 +322,17 @@ pub static TOOLS: &[ToolSpec] = &[
homepage: "https://docs.astral.sh/ruff/",
needs: &[],
},
ToolSpec {
name: "djlsp",
display: "Django Template LSP",
kind: LanguageServer,
commands: &["djlsp"],
method: Method::PipVenv { package: "django-template-lsp" },
fallback: None,
version: ver("djlsp"),
homepage: "https://github.com/fourdigits/django-template-lsp",
needs: &[],
},
ToolSpec {
name: "bash-language-server",
display: "Bash Language Server",
+11
Переглянути файл
@@ -32,6 +32,8 @@ These agents are built in. Install the agent's own CLI and sign in once in a ter
Agents are unavailable in a project you have not marked as trusted.
Codex keeps its own project trust decision. If it disables the current project's `.codex` configuration, the task asks whether to **Trust Project in Codex** or **Keep Untrusted**. Trusting saves only that project's trust entry through Codex's configuration API before the session loads its configuration, including MCP servers, hooks and exec policies. This confirmation is required even in Full Access mode; declining keeps the configuration disabled and shows the reason without stopping the conversation. Codex configuration and runtime warnings also appear in the task.
## Start a task
| Action | macOS | Windows / Linux |
@@ -121,6 +123,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).
+12 -3
Переглянути файл
@@ -18,12 +18,13 @@ 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 |
| **Introduce Parameter…** | `⌥⌘P` | `Ctrl+Alt+P` | Language server |
| **Extract Method…** | `⌥⌘M` | `Ctrl+Alt+M` | Language server |
| **Extract Interface…** | — | — | Java |
| **Inline…** | `⌥⌘N` | `Ctrl+Alt+N` | Language server |
| **Move…** | `F6` | `F6` | Language server (symbols); the IDE (files and folders) |
| **Safe Delete…** | `⌘⌦` | `Alt+Delete` | The IDE, using the server's references |
@@ -63,7 +64,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 +83,14 @@ 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.
## Extract Interface
In Java, **Refactor › Extract Interface…** creates an interface from the class of the current file. In the dialog, enter the interface name, choose its package and check the methods (and constants) it should declare. **Refactor** creates the interface, makes the class implement it, replaces the class with the interface wherever that is possible, and opens the new file; **Preview** lists the changes first.
## 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 +98,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 -1
Переглянути файл
@@ -107,7 +107,7 @@ The table lists every built-in language definition. Server and debugger names in
| D | `d` | `.d`, `.di` | Yes | — | serve-d | — |
| Dart | `dart` | `.dart` | Yes | Yes | dart | dart |
| Diff | `diff` | `.diff`, `.patch`, `.rej` | Yes | — | — | — |
| Django Template | `django-html` | `.djhtml`, `templates/*.html`, `*.txt` | Yes | Yes | **vscode-html-language-server** | — |
| Django Template | `django-html` | `.djhtml`, `templates/*.html`, `*.txt` | Yes | Yes | **vscode-html-language-server**, **djlsp** | — |
| Dockerfile | `dockerfile` | `.dockerfile`, `.containerfile` | Yes | — | **dockerfile-language-server** | — |
| Elixir | `elixir` | `.ex`, `.exs` | Yes | Yes | **elixir-ls** | **elixir-ls-debugger** |
| ERB | `erb` | `.erb`, `.html.erb`, `.rhtml`, `.js.erb`, `.text.erb`, … | Yes | — | — | — |
+2
Переглянути файл
@@ -140,6 +140,8 @@ Django is the only framework with dedicated support: the `manage.py runserver` a
The HTML and text files in a `templates` folder of a Django project (one with a `manage.py` above it) open as **Django Template** files: the template tags, variables, filters and comments are highlighted on top of the HTML, and block tags (`{% block %}`, `{% if %}`, `{% for %}`, `{% with %}` and the others of Django and its contrib libraries) fold, indent their content and highlight their end tag. Typing `{%`, `{{` or `{#` closes the pair, finishing a block tag adds its end tag, and `{% end` completes the end tags of the open blocks. **Comment with Line Comment** puts each line in its own `{# … #}`, and **Comment with Block Comment** over several lines uses `{% comment %}`. The HTML language server and Emmet work in the markup between the tags.
With **Django Template LSP** (`djlsp`, installed from **Settings › Languages & Frameworks › Language Servers**), the template tags, filters, template names (`{% extends %}`, `{% include %}`), static files and URL names of the project complete, show their documentation on hover, and **Go to Declaration** opens the template or the tag's Python source. It reads them by running Django with the project interpreter, so Django has to be installed there.
An HTML file elsewhere with Django tags shows a banner that switches it to Django Template or keeps it as HTML; either choice is the file's **Override File Type**.
## Limitations
+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` |
+11
Переглянути файл
@@ -32,6 +32,8 @@ OpenIDEA 本身不带模型或账号:它启动你已安装并登录的 agent
未被标记为受信任的项目中无法使用 agent。
Codex 有自己的项目信任设置。如果它禁用了当前项目的 `.codex` 配置,任务会询问选择**在 Codex 中信任项目**还是**保持不信任**。选择信任后,会在会话加载配置(包括 MCP 服务器、hooks 和 exec policies)之前,通过 Codex 的配置 API 只写入这个项目的信任条目。即使在 Full Access 模式下也需要这一步确认;选择不信任时配置保持禁用,任务中会显示原因,对话照常进行。Codex 的配置警告和运行时警告也会显示在任务中。
## 新建任务
| 操作 | macOS | Windows / Linux |
@@ -121,6 +123,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)。
+12 -3
Переглянути файл
@@ -18,12 +18,13 @@ 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` | 语言服务器 |
| **引入参数…** | `⌥⌘P` | `Ctrl+Alt+P` | 语言服务器 |
| **提取方法…** | `⌥⌘M` | `Ctrl+Alt+M` | 语言服务器 |
| **提取接口…** | — | — | Java |
| **内联…** | `⌥⌘N` | `Ctrl+Alt+N` | 语言服务器 |
| **移动…** | `F6` | `F6` | 语言服务器(符号);IDE(文件和文件夹) |
| **安全删除…** | `⌘⌦` | `Alt+Delete` | IDE,借助服务器查找引用 |
@@ -58,7 +59,7 @@ description: "重命名、引入与提取、内联、移动、更改签名和安
在项目视图中,**重命名…**(`⇧F6` / `Shift+F6`)、**移动…**(`F6`、拖放或剪切后粘贴)和 **复制…**(`F5`、复制后粘贴,或按住 `⌥` / `Alt` 拖动)会打开对话框。勾选 **搜索引用** 后,支持此功能的语言服务器会更新对该文件的引用(例如 TypeScript 的 import);**在注释和字符串中搜索** 会把注释和字符串也算进去。改动会先显示预览。
在编辑器中对符号执行 **移动…**,会调用该语言服务器的移动重构(如果有的话)。
在编辑器中对符号执行 **移动…**,会调用该语言服务器的移动重构(如果有的话)。在 Java 中会先询问目标:顶层类移动到其他包(包声明、import 和所有引用随之更新),静态成员或嵌套类移动到其他类,实例方法移动到其某个字段或形参的类;有警告时先在 **检测到问题** 中确认。
## 安全删除
@@ -75,6 +76,14 @@ description: "重命名、引入与提取、内联、移动、更改签名和安
用于在类和它的父类或子类之间移动字段和方法:支持 Java,以及使用 Phoxite 作为 PHP 服务器时的 PHP(方法、属性和常量)。在对话框中选择成员和目标类;移动会引起的问题会先在 **检测到问题** 中列出,再决定是否继续。Java 由 OpenIDEA 自带的扩展提供,PHP 由 Phoxite 提供;其他语言和其他 PHP 服务器不可用。
## 提取接口
在 Java 中,**重构 › 提取接口…** 会从当前文件的类创建一个接口。在对话框中输入接口名称,选择所在软件包,并勾选接口要声明的方法(以及常量)。**重构** 会创建接口、让该类实现它、在可行的地方把对该类的使用替换为接口,并打开新文件;**预览** 会先列出所有改动。
## 更改签名
在 Java 方法上执行 **更改签名…**(`⌘F6`)会打开对话框,可以修改可见性、返回类型和方法名,添加、删除和调整形参顺序。新形参需要填写默认值,所有已有调用处都会传入这个值;勾选 **通过重载方法委托** 会保留旧签名作为重载并调用新方法。签名预览显示修改后的声明。**重构** 会一次更新方法本身、覆盖它的方法和所有调用;**预览** 先列出改动。其他语言在服务器把签名重写作为代码操作提供时才会出现。
## 撤销
一次重构就是一步撤销,即使它改了多个文件。多文件重构完成后,通知中会提供 **撤消**(撤销后变为 **重做**)。
@@ -82,5 +91,5 @@ description: "重命名、引入与提取、内联、移动、更改签名和安
## 限制
- 除了重命名、安全删除和基于语法树的兜底实现,其他重构都需要语言服务器运行并提供相应功能。缺少时先看状态栏的 **语言服务** 微件。
- 只有当服务器把签名重写作为代码操作提供时,才会出现更改签名。
- 除 Java 外,只有当服务器把签名重写作为代码操作提供时,才会出现更改签名。
- 这个菜单里没有结构化搜索替换;见 [代码检查](/zh/guide/inspections) 中的 **编辑 › 查找 › 结构化替换…**。
+1 -1
Переглянути файл
@@ -102,7 +102,7 @@ IDE 安装工具从不需要 `sudo`。工具装在本地数据目录下 IDE 自
| D | `d` | `.d`, `.di` | 是 | — | serve-d | — |
| Dart | `dart` | `.dart` | 是 | 是 | dart | dart |
| Diff | `diff` | `.diff`, `.patch`, `.rej` | 是 | — | — | — |
| Django Template | `django-html` | `.djhtml`, `templates/*.html`, `*.txt` | 是 | 是 | **vscode-html-language-server** | — |
| Django Template | `django-html` | `.djhtml`, `templates/*.html`, `*.txt` | 是 | 是 | **vscode-html-language-server**, **djlsp** | — |
| Dockerfile | `dockerfile` | `.dockerfile`, `.containerfile` | 是 | — | **dockerfile-language-server** | — |
| Elixir | `elixir` | `.ex`, `.exs` | 是 | 是 | **elixir-ls** | **elixir-ls-debugger** |
| ERB | `erb` | `.erb`, `.html.erb`, `.rhtml`, `.js.erb`, `.text.erb`, … | 是 | — | — | — |
+2
Переглянути файл
@@ -140,6 +140,8 @@ Python 调试使用 debugpy。开始调试时如果缺少 debugpy,OpenIDEA 会
Django 项目(上层目录有 `manage.py`)中 `templates` 目录里的 HTML 和文本文件以 **Django Template** 打开:模板标签、变量、过滤器和注释在 HTML 之上高亮,块标签(`{% block %}`、`{% if %}`、`{% for %}`、`{% with %}` 以及 Django 和其 contrib 库的其他块标签)可以折叠、缩进内容并高亮对应的结束标签。输入 `{%`、`{{` 或 `{#` 会自动补全成对符号,写完块标签会自动添加结束标签,输入 `{% end` 会补全当前打开块的结束标签。**使用行注释** 会把每一行放进各自的 `{# … #}`,多行的 **使用块注释** 则用 `{% comment %}`。HTML 语言服务器和 Emmet 在标签之间的标记中照常工作。
安装 **Django Template LSP**(`djlsp`,在 **设置 › 语言和框架 › 语言服务器** 中安装)后,项目的模板标签、过滤器、模板名(`{% extends %}`、`{% include %}`)、静态文件和 URL 名可以补全、悬停查看文档,**转到声明** 会打开对应模板或标签的 Python 源码。它通过项目解释器运行 Django 读取这些信息,因此解释器中需要装有 Django。
其他位置含有 Django 标签的 HTML 文件会显示一个横幅,可以切换为 Django Template 或保留为 HTML;两种选择都会成为该文件的 **覆盖文件类型**。
## 限制
+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` |
+64
Переглянути файл
@@ -60,6 +60,70 @@ const entries: AgentEntry[] = [
},
];
for (const choice of ["codex-trust-project", "codex-keep-untrusted"]) {
test(`project trust has explicit choices and submits ${choice}`, async ({ page }, testInfo) => {
await page.setViewportSize({ width: 1050, height: 800 });
await page.goto("/");
await page.getByRole("tree", { name: "Project" }).waitFor();
await page.evaluate(
async ({ task }) => {
const path = "/src/features/agents/store.ts";
const store = await import(path);
store.useAgents.setState({
loaded: true,
tasks: new Map([[task.id, task]]),
entries: new Map([
[
task.id,
[
{ type: "user", text: "Load the project's MCP configuration.", attachments: [], steered: false },
{ type: "error", message: "Project-local config is disabled until the project is trusted in Codex." },
{
type: "permission",
id: 2,
title:
"Trust project in Codex: /dev/acme-api? This saves trust in your Codex user configuration and allows this project's MCP servers, hooks and exec policies to load.",
command: null,
options: [
{ id: "codex-trust-project", name: "Trust Project in Codex", kind: "allow_always" },
{ id: "codex-keep-untrusted", name: "Keep Untrusted", kind: "reject_once" },
],
chosen: null,
},
],
],
]),
});
store.openTaskInEditorLocation(task.id);
const ipcPath = "/src/platform/ipc.ts";
(await import(ipcPath)).commands.agentRespond = async (task: string, permission: number, option: string) => {
(window as unknown as { trustAnswer: unknown }).trustAnswer = { task, permission, option };
return { status: "ok", data: null };
};
},
{ task },
);
const card = page.getByRole("region", { name: "Trust Project in Codex" });
await expect(card).toBeVisible();
await expect(
page.getByText("Project-local config is disabled until the project is trusted in Codex."),
).toBeVisible();
await expect(card.getByRole("button")).toHaveText(["Trust Project in Codex", "Keep Untrusted"]);
await expect(card).toContainText("MCP servers, hooks and exec policies");
expect(await page.evaluate(() => (window as unknown as { trustAnswer?: unknown }).trustAnswer)).toBeUndefined();
await page.screenshot({ path: testInfo.outputPath("project-trust-confirmation.png"), animations: "disabled" });
await card
.getByRole("button", {
name: choice === "codex-trust-project" ? "Trust Project in Codex" : "Keep Untrusted",
exact: true,
})
.click();
await expect
.poll(() => page.evaluate(() => (window as unknown as { trustAnswer?: unknown }).trustAnswer))
.toEqual({ task: task.id, permission: 2, option: choice });
});
}
for (const theme of ["dark", "light"] as const) {
for (const width of [760, 1400]) {
test(`approval is asked above the composer at ${width}px in ${theme}`, async ({ page }) => {
+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();
});
+46
Переглянути файл
@@ -167,3 +167,49 @@ test("terminal ⌘F highlights active/inactive search matches and seeds with a n
await expect(input).toHaveValue("gamma");
await expect(search.locator("[aria-live=polite]")).toHaveText(/\d+\/2/);
});
test("terminal shows URLs in the link colour with an underline without hovering, in light and dark themes", async ({
workbench: page,
}) => {
await page.evaluate(async () => {
const path = "/src/workbench/toolwindows/store.ts";
const layout = await import(path);
layout.showToolWindow("terminal", true);
});
const terminal = page.getByRole("region", { name: "Terminal", exact: true });
await expect(terminal.locator(".xterm-helper-textarea")).toBeFocused();
await page.evaluate(async () => {
const path = "/src/features/terminal/runtime.ts";
const { activeSession } = await import(path);
const s = activeSession()!;
s.term.reset();
await new Promise<void>((resolve) =>
s.term.write(
" ➜ Local: http://localhost:5173/\r\n文档 https://example.com/docs 和 https://example.org/a\r\nno link\r\n",
resolve,
),
);
});
const links = terminal.locator(".openidea-terminal-link");
await expect(links).toHaveCount(3);
for (const theme of ["light", "dark"]) {
const link = await page.evaluate(async (theme) => {
const path = "/src/workbench/theme.ts";
const { setTheme } = await import(path);
await setTheme(theme);
const probe = document.createElement("span");
probe.style.color = "var(--link)";
document.body.append(probe);
const color = getComputedStyle(probe).color;
probe.remove();
return color;
}, theme);
await expect(page.locator("html")).toHaveAttribute("data-theme", theme);
// The underline and the recoloured text both follow the theme's `--link`.
await expect(links.first()).toHaveCSS("border-bottom-color", link);
await expect(terminal.locator(".xterm-rows span", { hasText: /^h$/ }).first()).toHaveCSS("color", link);
if (process.env.OPENIDEA_TERMINAL_SHOTS)
await terminal.screenshot({ path: `${process.env.OPENIDEA_TERMINAL_SHOTS}/terminal-links-${theme}.png` });
}
});
+1 -1
Переглянути файл
@@ -2,7 +2,7 @@ Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: OpenIDEA Java usages
Bundle-SymbolicName: ai.openidea.usages;singleton:=true
Bundle-Version: 1.14.0
Bundle-Version: 1.15.0
Bundle-RequiredExecutionEnvironment: JavaSE-21
Require-Bundle: org.eclipse.jdt.ls.core,org.eclipse.jdt.core,
org.eclipse.jdt.core.manipulation,org.eclipse.core.runtime,
+4 -1
Переглянути файл
@@ -88,7 +88,7 @@ is not a claim of full IntelliJ feature parity.
## Rebuild and delivery
The checked-in jar is embedded by ide-sdk `include_bytes!`, installed as
`java-usages-1.13.0.jar`, and added alongside existing initialization bundles.
`java-usages-1.15.0.jar`, and added alongside existing initialization bundles.
Users need no compiler, Maven or Python. Manifest/install version must change
when replacing the bundle because OSGi caches bundles.
@@ -133,6 +133,9 @@ its reproducible SHA-256 is
Version 1.12.0 caches usages answers until the Java model or an unsaved edit changes and adds
`openidea.workspace.coveredRoots`; its reproducible SHA-256 is
`c1bd28d7b956cb64af3e936aac0553413a5dc5fd373a043ddba003009e0ea783`.
Version 1.15.0 adds `openidea.java.implementationLocations`, which resolves the method an
implementation in a dependency declares (the standard request starts at its class file); its
reproducible SHA-256 is `c29e5455c02c245523b2e7a5861e00ae670cefc66cda33ec19fdce280f94c40c`.
```sh
export PATH=/path/to/jdk25/bin:$PATH
Бінарний файл не відображається.
+3
Переглянути файл
@@ -20,6 +20,9 @@
<delegateCommandHandler class="ai.openidea.archives.RefreshArchivesCommand">
<command id="openidea.java.refreshArchives"/>
</delegateCommandHandler>
<delegateCommandHandler class="ai.openidea.implementations.ImplementationTargetsCommand">
<command id="openidea.java.implementationLocations"/>
</delegateCommandHandler>
<delegateCommandHandler class="ai.openidea.hierarchy.HierarchyCommand">
<command id="openidea.java.hierarchy.members"/>
<command id="openidea.java.hierarchy.refactor"/>
+63
Переглянути файл
@@ -0,0 +1,63 @@
package ai.openidea.implementations;
import ai.openidea.Documents;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.jdt.core.*;
import org.eclipse.jdt.internal.corext.util.MethodOverrideTester;
import org.eclipse.jdt.ls.core.internal.IDelegateCommandHandler;
import org.eclipse.jdt.ls.core.internal.JDTUtils;
import org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin;
import org.eclipse.lsp4j.Location;
/**
* Where the implementations of the method at a position declare it, in the classes named by the
* caller: one location per target URI, or null when the target has no such method. The standard
* implementation request answers with the start of a class file's decompiled source for an
* implementation in a dependency; this resolves the method's own declaration there.
*/
public final class ImplementationTargetsCommand implements IDelegateCommandHandler {
@Override
public Object executeCommand(String command, List<Object> arguments, IProgressMonitor monitor) throws Exception {
Documents.awaitChanges(monitor);
String uri = (String) arguments.get(0);
int line = ((Number) arguments.get(1)).intValue();
int column = ((Number) arguments.get(2)).intValue();
@SuppressWarnings("unchecked")
List<String> targets = (List<String>) arguments.get(3);
ITypeRoot root = JDTUtils.resolveTypeRoot(uri, true, monitor);
if (root == null) return Map.of("locations", List.of());
try {
var preferences = JavaLanguageServerPlugin.getPreferencesManager();
IJavaElement element = JDTUtils.findElementAtSelection(root, line, column, preferences, monitor);
if (!(element instanceof IMethod method)) return Map.of("locations", List.of());
List<Location> locations = new ArrayList<>(targets.size());
for (String targetUri : targets) {
if (monitor.isCanceled()) throw new OperationCanceledException();
locations.add(find(method, targetUri, monitor));
}
return Map.of("locations", locations);
} finally {
JDTUtils.discardClassFileWorkingCopy(root);
}
}
/** The declaration of {@code method}'s implementation in the class {@code targetUri}, or null. */
private static Location find(IMethod method, String targetUri, IProgressMonitor monitor) throws JavaModelException {
ITypeRoot targetRoot = JDTUtils.resolveTypeRoot(targetUri);
if (targetRoot == null) return null;
IType target = targetRoot.findPrimaryType();
if (target == null) return null;
ITypeHierarchy hierarchy = target.newSupertypeHierarchy(monitor);
// Seen from the subtype, so its type arguments substitute the method's type variables.
IMethod found = new MethodOverrideTester(target, hierarchy).findOverridingMethodInType(target, method);
if (found == null || Flags.isAbstract(found.getFlags())) return null;
IClassFile classFile = found.getClassFile();
if (classFile == null) return JDTUtils.toLocation(found);
List<Location> decompiled = JDTUtils.searchDecompiledSources(found, classFile, true, true, monitor);
return decompiled.isEmpty() ? null : decompiled.get(0);
}
}
+66 -1
Переглянути файл
@@ -23,9 +23,30 @@ config_source = next(home / name / 'config.ini' for name in config_names if (hom
(config / 'config.ini').write_bytes(config_source.read_bytes())
project = work / 'project'
(project / 'src/zoo').mkdir(parents=True)
(project / 'lib').mkdir()
libs = work / 'libsrc/zoo'
libs.mkdir(parents=True)
(libs / 'ExternalRepo.java').write_text('''package zoo;
public interface ExternalRepo {
String find(String id, int limit);
}
''')
(libs / 'ExternalImpl.java').write_text('''package zoo;
public class ExternalImpl implements ExternalRepo {
public String find(String id, int limit) {
return id + limit;
}
}
''')
lib_classes = work / 'libclasses'
lib_classes.mkdir()
subprocess.run(['javac', '--release', '8', '-d', str(lib_classes)] + [str(p) for p in libs.glob('*.java')], check=True)
subprocess.run(['jar', 'cf', str(project / 'lib/external-api.jar'), '-C', str(lib_classes), '.'], check=True)
(project / '.project').write_text('<projectDescription><name>zoo</name><buildSpec><buildCommand><name>org.eclipse.jdt.core.javabuilder</name></buildCommand></buildSpec><natures><nature>org.eclipse.jdt.core.javanature</nature></natures></projectDescription>')
# `kotlin`: the project's compiled Kotlin classes, as the Kotlin bridge attaches them.
(project / '.classpath').write_text('<classpath><classpathentry kind="src" path="src"/><classpathentry kind="lib" path="kotlin"><attributes><attribute name="ai.openidea.kotlin" value="true"/></attributes></classpathentry><classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/><classpathentry kind="output" path="bin"/></classpath>')
(project / '.classpath').write_text('<classpath><classpathentry kind="src" path="src"/><classpathentry kind="lib" path="lib/external-api.jar"/><classpathentry kind="lib" path="kotlin"><attributes><attribute name="ai.openidea.kotlin" value="true"/></attributes></classpathentry><classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/><classpathentry kind="output" path="bin"/></classpath>')
sources = {
'Repo.java': '''package zoo;
@@ -87,6 +108,14 @@ public class Anon {
};
}
}
''',
'UseExternal.java': '''package zoo;
public class UseExternal {
void use(ExternalRepo repo) {
repo.find("x", 1);
}
}
''',
'Use.java': '''package zoo;
@@ -180,6 +209,28 @@ def implementations(file, needle):
return sorted(names), found['complete']
def definition(file, needle):
line, col = position(file, needle)
return request('textDocument/definition', {'textDocument': {'uri': uri(file)}, 'position': {'line': line, 'character': col}})
def class_contents(class_uri):
return request('java/classFileContents', {'uri': class_uri})
def standard_implementations(class_uri, line, col):
found = request('textDocument/implementation', {'textDocument': {'uri': class_uri}, 'position': {'line': line, 'character': col}})
return found or []
def implementation_locations(class_uri, line, col, targets):
found = command('openidea.java.implementationLocations', class_uri, line, col, targets)
return [
(pathlib.Path(urllib.parse.unquote(urllib.parse.urlparse(loc['uri']).path)).name, loc['range']['start']['line'])
for loc in found['locations'] if loc is not None
]
try:
init = request('initialize', {'processId': None, 'rootUri': project.as_uri(), 'workspaceFolders': [{'uri': project.as_uri(), 'name': 'zoo'}], 'capabilities': {}, 'initializationOptions': {'bundles': [str(bundle)], 'extendedClientCapabilities': {'classFileContentsSupport': True}, 'settings': {'java': {'import': {'gradle': {'enabled': False}, 'maven': {'enabled': False}}}}}})
assert 'openidea.java.implementations' in init['capabilities']['executeCommandProvider']['commands']
@@ -207,6 +258,20 @@ try:
if actual != expected:
failures.append((file, needle, expected, actual))
assert not failures, failures
# An interface in a dependency: the standard request starts at the class file, and the
# extension resolves the implementing method's declaration in the dependency.
defs = definition('UseExternal.java', 'ExternalRepo repo')
class_uri = defs[0]['uri']
text = class_contents(class_uri)
method_line = next(i for i, line in enumerate(text.splitlines()) if 'find(' in line)
method_col = text.splitlines()[method_line].index('find')
std = standard_implementations(class_uri, method_line, method_col)
targets = [loc['uri'] for loc in std]
resolved = implementation_locations(class_uri, method_line, method_col, targets)
print('dependency implementation:', resolved)
expected = [(pathlib.Path(urllib.parse.unquote(urllib.parse.urlparse(targets[0]).path)).name, 7)]
assert resolved == expected, (resolved, expected)
print('ok')
finally:
proc.kill()
+9
Переглянути файл
@@ -21,3 +21,12 @@ command = "vscode-html-language-server"
args = ["--stdio"]
initialization-options = { embeddedLanguages = { css = true, javascript = true } }
install-hint = "npm i -g vscode-langservers-extracted"
# Template tags, filters, template names and URL names of the project: completion,
# hover and go to definition. It reads them by running Django with the project
# interpreter.
[[language-servers]]
name = "djlsp"
command = "djlsp"
root-markers = ["manage.py"]
install-hint = "uv tool install django-template-lsp (or: pip install django-template-lsp)"
+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]
+134
Переглянути файл
@@ -97,6 +97,22 @@ pub async fn lsp_goto_implementation(
ide_host::ops::lsp::lsp_goto_implementation(&state.host, window.label(), request, doc, pos, on_partial).await
}
/// Refines the implementations `targets` of the method at `pos` to their declarations (Java
/// dependencies' class files point at the start of the class). Cancel with
/// `cancel_request(request)`.
#[tauri::command]
#[specta::specta]
pub async fn lsp_implementation_locations(
window: Window,
state: State<'_, AppState>,
request: RequestId,
doc: DocId,
pos: Pos,
targets: Vec<Location>,
) -> IdeResult<Vec<Location>> {
ide_host::ops::lsp::lsp_implementation_locations(&state.host, window.label(), request, doc, pos, targets).await
}
/// Implementations of the symbols at `positions`, one list per position (the
/// editor's "is implemented / overridden" gutter markers). Cancel with
/// `cancel_request(request)`.
@@ -317,6 +333,124 @@ 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_extract_interface_info(
window: Window,
state: State<'_, AppState>,
request: RequestId,
doc: DocId,
pos: Pos,
) -> IdeResult<ExtractInterfaceInfo> {
ide_host::ops::lsp::lsp_extract_interface_info(&state.host, window.label(), request, doc, pos).await
}
#[tauri::command]
#[specta::specta]
#[allow(clippy::too_many_arguments)]
pub async fn lsp_extract_interface(
window: Window,
state: State<'_, AppState>,
request: RequestId,
doc: DocId,
pos: Pos,
members: Vec<String>,
name: String,
destination: String,
confirmation: Option<String>,
) -> IdeResult<ServerRefactored> {
ide_host::ops::lsp::lsp_extract_interface(
&state.host,
window.label(),
request,
doc,
pos,
members,
name,
destination,
confirmation,
)
.await
}
#[tauri::command]
#[specta::specta]
pub async fn lsp_format(
+13
Переглянути файл
@@ -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,
@@ -282,6 +287,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
lsp::lsp_goto,
lsp::lsp_implementations,
lsp::lsp_goto_implementation,
lsp::lsp_implementation_locations,
lsp::lsp_virtual_document,
lsp::lsp_can_download_sources,
lsp::lsp_library_sources,
@@ -297,6 +303,13 @@ 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_extract_interface_info,
lsp::lsp_extract_interface,
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,
+2
Переглянути файл
@@ -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"),
@@ -593,6 +594,7 @@ pub fn spec(os: Os) -> Vec<Entry> {
act("refactor.extractField", "Introduce Field…"),
act("refactor.extractParameter", "Introduce Parameter…"),
act("refactor.extractMethod", "Extract Method…"),
act("refactor.extractInterface", "Extract Interface…"),
act("refactor.inline", "Inline…"),
SEP,
act("refactor.pullMembersUp", "Pull Members Up…"),
+13
Переглянути файл
@@ -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
@@ -300,15 +306,21 @@ lsp_document_highlights trusted project_host bin
lsp_document_links trusted project_host bindings async
lsp_execute_code_action trusted project_host bindings async
lsp_execute_command trusted project_host bindings async
lsp_extract_interface trusted project_host bindings async
lsp_extract_interface_info trusted project_host bindings async
lsp_format trusted project_host bindings async
lsp_goto trusted project_host bindings async
lsp_goto_implementation trusted project_host bindings async
lsp_hierarchy_members trusted project_host bindings async
lsp_hierarchy_refactor trusted project_host bindings async
lsp_hover trusted project_host bindings async
lsp_implementation_locations trusted project_host bindings async
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 +336,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
+235 -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,
@@ -584,6 +597,12 @@ export const commands = {
* Cancel with `cancel_request(request)`.
*/
lspGotoImplementation: (request: RequestId, doc: DocId, pos: Pos, onPartial: Channel<Location[]>) => typedError<Location[], IdeError>(__TAURI_INVOKE("lsp_goto_implementation", { request, doc, pos, onPartial })),
/**
* Refines the implementations `targets` of the method at `pos` to their declarations (Java
* dependencies' class files point at the start of the class). Cancel with
* `cancel_request(request)`.
*/
lspImplementationLocations: (request: RequestId, doc: DocId, pos: Pos, targets: Location[]) => typedError<Location[], IdeError>(__TAURI_INVOKE("lsp_implementation_locations", { request, doc, pos, targets })),
/**
* Contents of a read-only language-server document, including JDT library
* classes and disk class files. Cached per project.
@@ -629,6 +648,13 @@ 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 })),
lspExtractInterfaceInfo: (request: RequestId, doc: DocId, pos: Pos) => typedError<ExtractInterfaceInfo, IdeError>(__TAURI_INVOKE("lsp_extract_interface_info", { request, doc, pos })),
lspExtractInterface: (request: RequestId, doc: DocId, pos: Pos, members: string[], name: string, destination: string, confirmation: string | null) => typedError<ServerRefactored, IdeError>(__TAURI_INVOKE("lsp_extract_interface", { request, doc, pos, members, name, destination, 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 +2137,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 +2529,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 +2575,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. */
@@ -5288,6 +5391,16 @@ export type ExternalTool = {
openConsole?: boolean,
};
/**
* What Extract Interface starts from: the file's class, the members the interface can declare and
* the packages it can go to (as JSON, passed back unchanged).
*/
export type ExtractInterfaceInfo = {
className: string,
members: InterfaceMember[],
packages: string[],
};
/** Framework facet attached to a module (Project Structure › Facets). */
export type FacetConfig = {
/** `"web"` | `"spring"` | `"jpa"`. */
@@ -6679,6 +6792,17 @@ export type IntellijThemeSource = {
themes: IntellijThemeFile[],
};
/** A member Extract Interface can declare in the new interface. */
export type InterfaceMember = {
name: string,
/** The method's return type or the field's type. */
typeName: string,
/** The method's parameter types; `None` for a field. */
parameters: string[] | null,
/** The server's handle of the member, passed back unchanged. */
handleIdentifier: string,
};
/** Optional parts of the invalidation; the symbol index is always rebuilt. */
export type InvalidateCachesOptions = {
/** Local History of every project. */
@@ -7646,12 +7770,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 +7840,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 +7915,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 +8026,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 +8113,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 +10083,16 @@ export type ServerInfo = {
label?: string | null,
};
/**
* A refactoring checked by the server (Change Signature, Move, Extract Interface): 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 +10342,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 -1
Переглянути файл
@@ -34,7 +34,7 @@ import type { LineEnding } from "@/platform/ipc";
import { create } from "zustand";
import { maybeEditorService } from "@/workbench/contributions";
import { cornerInset } from "@/editor/core/cm/cornerInset";
export { iconAreaSource, type IconAreaSource } from "@/editor/core/cm/iconArea";
export { iconAreaSource, mapLineStart, type IconAreaSource } from "@/editor/core/cm/iconArea";
/** Documents above this size (UTF-16 units) skip per-line decorations. */
export const HEAVY_LIMIT = 8_000_000;
+99 -3
Переглянути файл
@@ -1,8 +1,8 @@
import { afterEach, expect, it, vi } from "vitest";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { fireEvent } from "@testing-library/react";
import { EditorState, RangeSet } from "@codemirror/state";
import { EditorState, RangeSet, StateEffect, StateField } from "@codemirror/state";
import { EditorView, GutterMarker } from "@codemirror/view";
import { iconAreaExtension, iconAreaSource } from "./iconArea";
import { SETTLE_MS, iconAreaExtension, iconAreaSource, mapLineStart } from "./iconArea";
class Dot extends GutterMarker {
constructor(readonly name: string) {
@@ -73,3 +73,99 @@ it("keeps an icon's width only while a source asks for it", () => {
const v = open([{ order: 1, markers: () => RangeSet.empty, reserve: () => true }]);
expect(v.dom.querySelector(".cm-openidea-iconArea .cm-openidea-iconSpacer")).toBeTruthy();
});
describe("while edits place icons again", () => {
// Line numbers each source has an icon on, as set by the test.
const setRun = StateEffect.define<number[]>();
const setImpl = StateEffect.define<number[]>();
const linesField = (effect: typeof setRun, initial: number[]) =>
StateField.define<number[]>({
create: () => initial,
update: (value, tr) => tr.effects.find((e) => e.is(effect))?.value ?? value,
});
const run = linesField(setRun, [2]);
const impl = linesField(setImpl, [2]);
const dots = (name: string, field: StateField<number[]>) => (view: EditorView) =>
RangeSet.of(view.state.field(field).map((l) => new Dot(name).range(lineStart(view.state, l))));
const spacerIcons = (v: EditorView) => v.dom.querySelectorAll(".cm-openidea-iconSpacer").length;
beforeEach(() => vi.useFakeTimers());
afterEach(() => vi.useRealTimers());
function openTwoSources() {
view = new EditorView({
state: EditorState.create({
doc: DOC,
extensions: [
run,
impl,
iconAreaExtension,
iconAreaSource.of({ order: 10, markers: dots("run", run) }),
iconAreaSource.of({ order: 50, markers: dots("impl", impl) }),
],
}),
parent: document.body,
});
return view;
}
// Enter at the start of line 2: the run icon moves to line 3 first, the inheritance icon later.
const pressEnter = (v: EditorView) => v.dispatch({ changes: { from: lineStart(v.state, 2), insert: "\n" } });
it("keeps the widest line's width while a line's icons are apart, then narrows once they settle", () => {
const v = openTwoSources();
expect(spacerIcons(v)).toBe(2);
pressEnter(v);
v.dispatch({ effects: setRun.of([3]) });
expect(spacerIcons(v)).toBe(2);
vi.advanceTimersByTime(SETTLE_MS - 1);
v.dispatch({ effects: setImpl.of([3]) });
expect(spacerIcons(v)).toBe(2);
// An icon that really went away: the area narrows only after nothing changed for a while.
v.dispatch({ effects: setImpl.of([]) });
vi.advanceTimersByTime(SETTLE_MS - 1);
expect(spacerIcons(v)).toBe(2);
vi.advanceTimersByTime(1);
expect(spacerIcons(v)).toBe(1);
});
it("does not narrow while typing goes on", () => {
const v = openTwoSources();
v.dispatch({ effects: setImpl.of([]) });
for (let i = 0; i < 5; i++) {
vi.advanceTimersByTime(SETTLE_MS / 2);
pressEnter(v);
expect(spacerIcons(v)).toBe(2);
}
vi.advanceTimersByTime(SETTLE_MS);
expect(spacerIcons(v)).toBe(1);
});
it("widens at once", () => {
const v = openTwoSources();
v.dispatch({ effects: setImpl.of([]) });
vi.advanceTimersByTime(SETTLE_MS);
expect(spacerIcons(v)).toBe(1);
pressEnter(v);
v.dispatch({ effects: setImpl.of([2]) });
expect(spacerIcons(v)).toBe(2);
});
});
it("moves a line's marker down with its text when Enter is pressed at the line's start", () => {
const state = EditorState.create({ doc: "a\nclass B {}\nc" });
const lineB = state.doc.line(2).from;
const tr = state.update({ changes: { from: lineB, insert: "\n" } });
expect(mapLineStart(tr, lineB)).toBe(tr.state.doc.line(3).from);
const after = (from: number, insert: string, to = from) =>
mapLineStart(state.update({ changes: { from, to, insert } }), lineB);
// Other edits keep it at the start of its line.
expect(after(lineB, " ")).toBe(lineB);
expect(after(1, "\nnew")).toBe(lineB + 4);
expect(after(lineB + 5, "\n")).toBe(lineB);
// Joined into the line above, it goes with its text.
expect(after(1, "", lineB)).toBe(0);
});
+94 -11
Переглянути файл
@@ -3,8 +3,16 @@
* rendered-doc toggle share one column, as wide as the most icons on any line, instead of a
* column per kind that stays empty on the lines where another kind has its icon.
*/
import { Facet, type EditorState, type Extension, type RangeSet } from "@codemirror/state";
import { EditorView, GutterMarker, gutter, type BlockInfo, type ViewUpdate, type WidgetType } from "@codemirror/view";
import { Facet, type EditorState, type Extension, type RangeSet, type Transaction } from "@codemirror/state";
import {
EditorView,
GutterMarker,
ViewPlugin,
gutter,
type BlockInfo,
type ViewUpdate,
type WidgetType,
} from "@codemirror/view";
export interface IconAreaSource {
/** Left to right within a line: lower first. */
@@ -20,23 +28,94 @@ export interface IconAreaSource {
mousedown?(view: EditorView, block: BlockInfo, event: MouseEvent): boolean;
}
/**
* Where a marker on the line starting at `pos` goes after `tr`: the start of the line its text is
* on now. An Enter at the start of the line moves the marker down with its text, as every source
* must agree; one left on the new blank line until its source refreshes would split a line's icons
* and briefly narrow the area, shifting the code.
*/
export function mapLineStart(tr: Transaction, pos: number): number {
return tr.state.doc.lineAt(tr.changes.mapPos(pos, 1)).from;
}
export const iconAreaSource = Facet.define<IconAreaSource, readonly IconAreaSource[]>({
combine: (sources) => [...sources].sort((a, b) => a.order - b.order),
});
/** The width of one icon, for the reserved column. Hidden; not a button. */
/** `count` icons of width, the room the area keeps. Hidden; not buttons. */
class IconSpacer extends GutterMarker {
constructor(readonly count: number) {
super();
}
override eq(other: GutterMarker): boolean {
return other instanceof IconSpacer && other.count === this.count;
}
override toDOM(): Node {
const el = document.createElement("span");
el.className = "cm-openidea-iconSpacer";
el.className = "cm-openidea-iconAreaSpacer";
for (let i = 0; i < this.count; i++)
el.appendChild(document.createElement("span")).className = "cm-openidea-iconSpacer";
return el;
}
}
const iconSpacer = new IconSpacer();
const noSpacer = new (class extends GutterMarker {})();
const reserved = (state: EditorState) => state.facet(iconAreaSource).some((s) => s.reserve?.(state));
/** The most icons on one line, at least one while a source reserves room. */
function mostIcons(view: EditorView): number {
const sources = view.state.facet(iconAreaSource);
const lines = new Map<number, number>();
let most = sources.some((s) => s.reserve?.(view.state)) ? 1 : 0;
for (const s of sources)
for (const it = s.markers(view).iter(); it.value; it.next()) {
const line = view.state.doc.lineAt(it.from).from;
const n = (lines.get(line) ?? 0) + 1;
lines.set(line, n);
most = Math.max(most, n);
}
return most;
}
/** How long the text and its icons stay unchanged before the area may narrow. */
export const SETTLE_MS = 2000;
/**
* After an edit each source places its icons again on its own schedule (a run icon before the
* language server's inheritance icons), so a line's icons briefly part. The area widens at once
* but narrows only once nothing changed for `SETTLE_MS`, so the text does not shift back and forth.
*/
const areaWidth = ViewPlugin.fromClass(
class {
private holdUntil = 0;
/** The most icons on a line now, and the icons of width the spacer keeps. */
private icons = 0;
private kept = 0;
private timer: ReturnType<typeof setTimeout> | undefined;
constructor(readonly view: EditorView) {}
spacer(prev: GutterMarker | null, update: ViewUpdate | null): GutterMarker {
const icons = mostIcons(this.view);
const now = Date.now();
if (update && (update.docChanged || icons !== this.icons)) {
this.holdUntil = now + SETTLE_MS;
clearTimeout(this.timer);
// Once settled, any update asks for the spacer again.
this.timer = setTimeout(() => this.kept > this.icons && this.view.dispatch({}), SETTLE_MS);
}
this.icons = icons;
if (prev && now < this.holdUntil && icons < this.kept) return prev;
this.kept = icons;
return icons ? new IconSpacer(icons) : noSpacer;
}
destroy() {
clearTimeout(this.timer);
}
},
);
const spacer = (view: EditorView, prev: GutterMarker | null, update: ViewUpdate | null) =>
view.plugin(areaWidth)?.spacer(prev, update) ?? noSpacer;
const areaGutter = gutter({
class: "cm-openidea-iconArea",
@@ -51,8 +130,8 @@ const areaGutter = gutter({
lineMarkerChange: (update) =>
update.startState.facet(iconAreaSource) !== update.state.facet(iconAreaSource) ||
update.state.facet(iconAreaSource).some((s) => s.lineMarkerChange?.(update)),
initialSpacer: (view) => (reserved(view.state) ? iconSpacer : noSpacer),
updateSpacer: (_spacer, update) => (reserved(update.state) ? iconSpacer : noSpacer),
initialSpacer: (view) => spacer(view, null, null),
updateSpacer: (prev, update) => spacer(update.view, prev, update),
domEventHandlers: {
mousedown: (view, block, event) =>
view.state.facet(iconAreaSource).some((s) => s.mousedown?.(view, block, event as MouseEvent) ?? false),
@@ -67,10 +146,14 @@ const areaTheme = EditorView.baseTheme({
gap: "2px",
},
// Room around the icons, not the element: an area without icons takes no width.
".cm-openidea-iconArea .cm-gutterElement > *": { margin: "0 1px" },
".cm-openidea-iconArea .cm-gutterElement > :first-child": { marginLeft: "5px" },
".cm-openidea-iconArea .cm-gutterElement > *, .cm-openidea-iconAreaSpacer > *": { margin: "0 1px" },
".cm-openidea-iconArea .cm-gutterElement > :first-child, .cm-openidea-iconAreaSpacer > :first-child": {
marginLeft: "5px",
},
// The spacer's icons are laid out as the line's own.
".cm-openidea-iconAreaSpacer": { display: "contents" },
".cm-openidea-iconSpacer": { display: "inline-block", width: "14px" },
});
/** Installed in every editor; empty (no width) while no source has markers or reserves room. */
export const iconAreaExtension: Extension = [areaGutter, areaTheme];
export const iconAreaExtension: Extension = [areaWidth, areaGutter, areaTheme];
+4 -17
Переглянути файл
@@ -5,6 +5,7 @@
*/
import { writeClipboardText } from "@/platform/clipboard";
import { pasteEditorClipboard } from "./cm/clipboard";
import { saveOnBlur } from "./saveOnBlur";
import type { ReactNode } from "react";
import { EditorSelection } from "@codemirror/state";
import { create } from "zustand";
@@ -808,19 +809,7 @@ export class EditorController implements SlotHost {
setContext("editorTextFocus", false);
if (!this.autoSave()) return;
const save = () => void slot.model.save("auto").catch(() => {});
if (typeof document === "undefined") return save();
// A popup (intentions, completion, …) belongs to the editor: saving under it would change
// the text (save cleanup) its items were computed for. Save once focus leaves it elsewhere.
setTimeout(() => {
if (slot.view?.hasFocus) return;
if (!inPopup(document.activeElement)) return save();
const onFocusIn = (e: FocusEvent) => {
if (inPopup(e.target)) return;
document.removeEventListener("focusin", onFocusIn);
if (!slot.view?.hasFocus) save();
};
document.addEventListener("focusin", onFocusIn);
});
saveOnBlur(() => !!slot.view?.hasFocus, save);
}
onSelection(slot: EditorSlot, navigatedFrom?: { line: number; col: number }) {
@@ -917,6 +906,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" },
@@ -948,6 +938,7 @@ export class EditorController implements SlotHost {
{ kind: "action", action: "refactor.extractVariable" },
{ kind: "action", action: "refactor.extractConstant" },
{ kind: "action", action: "refactor.extractMethod" },
{ kind: "action", action: "refactor.extractInterface" },
{ kind: "action", action: "refactor.inline" },
{ kind: "action", action: "refactor.pullMembersUp" },
{ kind: "action", action: "refactor.pushMembersDown" },
@@ -2347,7 +2338,3 @@ let controller: EditorController | null = null;
export function editorController(): EditorController {
return (controller ??= new EditorController());
}
function inPopup(target: EventTarget | null): boolean {
return target instanceof Element && !!target.closest("[data-popup]");
}
+140 -2
Переглянути файл
@@ -1,7 +1,9 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { EditorView } from "@codemirror/view";
import { EditorState } from "@codemirror/state";
import { history, undo } from "@codemirror/commands";
import { editorsFor } from "@/editor/api";
import type { Settings } from "@/bindings";
import { createMemoryBackend } from "../backend";
import { _resetLanguages } from "../cm/languages";
import { attachDocument } from "./attachment";
@@ -20,11 +22,13 @@ async function settle() {
for (let i = 0; i < 10; i++) await new Promise((r) => setTimeout(r, 0));
}
function setup(files: Record<string, string>) {
function setup(files: Record<string, string>, settings: Settings = {}) {
_resetLanguages();
const backend = createMemoryBackend(files);
const scheduled: Array<() => void> = [];
const manager = new DocumentManager(backend, { settings: () => ({}), notify: vi.fn() }, (fn) => scheduled.push(fn));
const manager = new DocumentManager(backend, { settings: () => settings, notify: vi.fn() }, (fn) =>
scheduled.push(fn),
);
manager.start();
const frame = async () => {
scheduled.splice(0).forEach((f) => f());
@@ -36,6 +40,140 @@ function setup(files: Record<string, string>) {
afterEach(() => useDocMeta.setState({}, true));
describe("attached document views (editable diff side)", () => {
it.each([
{ autoSave: true, tabOpen: false, ensureFinalNewline: false },
{ autoSave: false, tabOpen: false, ensureFinalNewline: false },
{ autoSave: true, tabOpen: true, ensureFinalNewline: false },
{ autoSave: true, tabOpen: true, ensureFinalNewline: true },
])(
"saves reverted diff edits on blur respecting $autoSave / $tabOpen / $ensureFinalNewline",
async ({ autoSave, tabOpen, ensureFinalNewline }) => {
const { backend, manager, frame } = setup(
{ "/p/a.txt": "original\n" },
{ files: { autoSave, ensureFinalNewline } },
);
const att = await attachDocument(manager, "/p/a.txt");
const tab = tabOpen ? new EditorSlot(manager.get("/p/a.txt")!, "t1", host) : null;
const parent = document.createElement("div");
const elsewhere = document.createElement("button");
document.body.append(parent, elsewhere);
const view = new EditorView({ parent, doc: att.text(), extensions: [att.extension] });
try {
view.focus();
view.dispatch({ changes: { from: 8, to: 9 }, userEvent: "delete.backward" });
elsewhere.focus();
await frame();
expect(backend.docs.get(att.doc)?.saved).toBe(autoSave && !ensureFinalNewline ? "original" : "original\n");
expect(att.dirty()).toBe(!autoSave);
if (!autoSave) {
await att.save();
expect(backend.docs.get(att.doc)?.saved).toBe("original");
}
} finally {
view.destroy();
att.release();
tab?.dispose();
manager.stop();
parent.remove();
elsewhere.remove();
}
},
);
it("cancels popup-delayed autosave when an attached view is destroyed", async () => {
const { backend, manager, frame } = setup({ "/p/a.txt": "original\n" });
const att = await attachDocument(manager, "/p/a.txt");
const parent = document.createElement("div");
const popup = document.createElement("button");
popup.setAttribute("data-popup", "");
const elsewhere = document.createElement("button");
document.body.append(parent, popup, elsewhere);
const view = new EditorView({ parent, doc: att.text(), extensions: [att.extension] });
try {
view.focus();
view.dispatch({ changes: { from: 8, to: 9 } });
popup.focus();
await frame();
view.destroy();
elsewhere.focus();
await frame();
expect(backend.docs.get(att.doc)?.saved).toBe("original\n");
} finally {
view.destroy();
att.release();
manager.stop();
parent.remove();
popup.remove();
elsewhere.remove();
}
});
it("waits until focus leaves an editor popup before autosaving a diff", async () => {
const { backend, manager, frame } = setup({ "/p/a.txt": "original\n" });
const att = await attachDocument(manager, "/p/a.txt");
const parent = document.createElement("div");
const popup = document.createElement("div");
popup.setAttribute("data-popup", "");
const item = document.createElement("button");
popup.append(item);
const elsewhere = document.createElement("button");
document.body.append(parent, popup, elsewhere);
const view = new EditorView({ parent, doc: att.text(), extensions: [att.extension] });
try {
view.focus();
view.dispatch({ changes: { from: 8, to: 9 } });
item.focus();
await frame();
expect(backend.docs.get(att.doc)?.saved).toBe("original\n");
view.focus();
await frame();
expect(att.dirty()).toBe(true);
item.focus();
await frame();
elsewhere.focus();
await frame();
expect(backend.docs.get(att.doc)?.saved).toBe("original");
expect(att.dirty()).toBe(false);
} finally {
view.destroy();
att.release();
manager.stop();
parent.remove();
popup.remove();
elsewhere.remove();
}
});
it("does not save another view's edits when leaving a read-only preview", async () => {
const { backend, manager, frame } = setup({ "/p/a.txt": "original\n" });
const model = await manager.acquire("/p/a.txt");
const tab = new EditorSlot(model, "t1", host);
const att = await attachDocument(manager, "/p/a.txt");
const parent = document.createElement("div");
const elsewhere = document.createElement("button");
document.body.append(parent, elsewhere);
const view = new EditorView({
parent,
doc: att.text(),
extensions: [att.extension, EditorState.readOnly.of(true)],
});
try {
tab.dispatchLocal({ changes: { from: 8, to: 9 } });
view.focus();
elsewhere.focus();
await frame();
expect(backend.docs.get(att.doc)?.saved).toBe("original\n");
expect(att.dirty()).toBe(true);
} finally {
view.destroy();
att.release();
tab.dispose();
manager.stop();
parent.remove();
elsewhere.remove();
}
});
it("can save a confirmed merge result without trimming or adding a final newline", async () => {
const { backend, manager } = setup({ "/p/merge.txt": "old\n" });
const att = await attachDocument(manager, "/p/merge.txt");
+17
Переглянути файл
@@ -25,6 +25,7 @@ import {
type TextEditorHandle,
} from "@/editor/api";
import type { DocAttachmentTarget, DocumentManager } from "./document";
import { saveOnBlur } from "../saveOnBlur";
class AttachedView implements DocAttachmentTarget {
view: EditorView | null = null;
@@ -62,6 +63,7 @@ export async function attachDocument(
}
model.attach(target);
let released = false;
let cancelBlurSave: (() => void) | undefined;
let detachHistory: (() => void) | null = null;
const historyTarget = {
path,
@@ -93,6 +95,7 @@ export async function attachDocument(
return {
destroy() {
destroyed = true;
cancelBlurSave?.();
if (!options.sharedHistory) {
detachHistory?.();
detachHistory = null;
@@ -143,6 +146,19 @@ export async function attachDocument(
}
},
extension: [
EditorView.domEventHandlers({
blur: (_event, view) => {
cancelBlurSave?.();
if (view.state.readOnly || !view.state.facet(EditorView.editable)) return;
cancelBlurSave = saveOnBlur(
() => view.hasFocus,
() => {
if (released || model.closed || manager.settings()?.files?.autoSave === false) return;
void model.save("auto").catch((e) => console.warn(`autosave of ${path} failed`, e));
},
);
},
}),
options.sharedHistory ? target.history.of(history()) : [],
options.sharedHistory
? EditorView.domEventHandlers({
@@ -187,6 +203,7 @@ export async function attachDocument(
release: () => {
if (released) return;
released = true;
cancelBlurSave?.();
detachHistory?.();
detachHistory = null;
target.view = null;
+22
Переглянути файл
@@ -0,0 +1,22 @@
/** Popups belong to the editor; defer save cleanup until focus leaves them too. */
export function saveOnBlur(hasFocus: () => boolean, save: () => void): () => void {
if (typeof document === "undefined") {
save();
return () => {};
}
const inPopup = (target: EventTarget | null) => target instanceof Element && !!target.closest("[data-popup]");
const onFocusIn = (event: FocusEvent) => {
if (inPopup(event.target)) return;
document.removeEventListener("focusin", onFocusIn);
if (!hasFocus()) save();
};
const timer = setTimeout(() => {
if (hasFocus()) return;
if (inPopup(document.activeElement)) document.addEventListener("focusin", onFocusIn);
else save();
});
return () => {
clearTimeout(timer);
document.removeEventListener("focusin", onFocusIn);
};
}
+1
Переглянути файл
@@ -230,6 +230,7 @@ function PaneView({ paneId }: { paneId: string }) {
color: colors[i] || undefined,
tint:
tints[i] || (fileColors && t.input.kind === "file" && t.input.path ? fileColors(t.input.path) : undefined),
tintStrength: tints[i] ? undefined : "var(--file-tint-strength)",
tooltip: virtualTooltip(t.input) ?? (showFullPathOnHover ? (t.input.path ?? name) : undefined),
trailing:
kindMark || pin ? (
+3
Переглянути файл
@@ -320,6 +320,9 @@ export function registerLspActions(): () => void {
editorAction("refactor.extractParameter", "Introduce Parameter…", "Refactor", (v) =>
runRefactoring(v, "extractParameter"),
),
editorAction("refactor.extractInterface", "Extract Interface…", "Refactor", (v) =>
runRefactoring(v, "extractInterface"),
),
editorAction("refactor.move", "Move…", "Refactor", (v) => runRefactoring(v, "move")),
editorAction("refactor.changeSignature", "Change Signature…", "Refactor", (v) =>
runRefactoring(v, "changeSignature"),
+11 -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,13 @@ 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,
ExtractInterfaceDialog,
HierarchyDialog,
JAVA_REFACTORING_COMMAND,
runJavaRefactoringCommand,
} from "@/editor/refactor";
export function lspExtensions(ctx: EditorDocContext): Extension[] {
return [
@@ -116,6 +122,9 @@ 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 }),
registerOverlay({ id: "editor-lsp.extractInterfaceDialog", component: ExtractInterfaceDialog }),
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;
+16 -18
Переглянути файл
@@ -195,27 +195,25 @@ export async function locationItems(locs: readonly DeclarationTarget[]): Promise
const root = useProject.getState().project?.root ?? "";
const names = locs.map((l) => targetLabel(files.get(l.path)?.[l.range.start.line] ?? "", l.range.start.col));
const indexed = await indexContainers(locs, names);
return locs.map((l, i) => {
const rows = locs.map((l, i) => {
const where = chooserWhere(root, l.path, l.range.start.line + 1);
// Index symbols carry their container; server targets take the index's answer or the enclosing type.
if (l.kind && l.name)
return {
id: `${i}`,
label: l.name,
detail: [l.container, where].filter(Boolean).join(" · "),
symbol: l.kind,
location: { path: l.path, line: l.range.start.line },
run: () => navigateTo(l),
};
return {
id: `${i}`,
label: l.name ?? names[i] ?? basename(l.path),
detail: [indexed.get(i) ?? enclosingType(files.get(l.path), l), where].filter(Boolean).join(" · "),
icon: fileIconName(basename(l.path), l.path),
location: { path: l.path, line: l.range.start.line },
run: () => navigateTo(l),
};
const indexSymbol = !!(l.kind && l.name);
const label = indexSymbol ? l.name! : (l.name ?? names[i] ?? basename(l.path));
const container = indexSymbol ? l.container : (indexed.get(i) ?? enclosingType(files.get(l.path), l));
return { l, where, label, container: container || null, indexSymbol };
});
// Targets that all share one name (the implementations of a method) are told apart, and
// speed-searched, by their containers, which become the rows' text.
const byContainer = rows.length > 1 && rows.every((r) => r.container && r.label === rows[0]!.label);
return rows.map(({ l, where, label, container, indexSymbol }, i) => ({
id: `${i}`,
label: byContainer ? container! : label,
detail: (byContainer ? [where] : [container, where]).filter(Boolean).join(" · "),
...(indexSymbol ? { symbol: l.kind! } : { icon: fileIconName(basename(l.path), l.path) }),
location: { path: l.path, line: l.range.start.line },
run: () => navigateTo(l),
}));
}
/** "Choose Implementation of foo (3 found)". */
+18
Переглянути файл
@@ -187,6 +187,24 @@ describe("locationItems", () => {
expect(item.detail).toBe("config · src/mod.py:1");
});
it("names same-named targets (a method's implementations) by their containers", async () => {
const lines = (cls: string) => ["", `class ${cls}(Base):`, "", " def refresh(self) -> None:"];
readManyFileLines.mockResolvedValue(
new Map([
["/p/src/a.py", lines("Cached")],
["/p/src/b.py", lines("Remote")],
]),
);
project("/p");
const items = await locationItems([target("/p/src/a.py", "refresh", 3), target("/p/src/b.py", "refresh", 3)]);
expect(items.map((i) => [i.label, i.detail])).toEqual([
["Cached", "src/a.py:4"],
["Remote", "src/b.py:4"],
]);
// A single target, or targets with different names, keep their own names.
expect((await locationItems([target("/p/src/a.py", "refresh", 3)]))[0]!.label).toBe("refresh");
});
it("does not query the index for index symbols, which carry their container", async () => {
readManyFileLines.mockResolvedValue(new Map());
project("/p");
+4 -3
Переглянути файл
@@ -585,9 +585,10 @@ describe("navigation wiring", () => {
if (popup?.kind !== "list") return;
expect(popup.title).toBe("Choose Declaration of run (2 found, based on syntax)");
expect(popup.pin?.label).toBe("Open in Find Tool Window");
expect(popup.items.map((i) => [i.label, i.symbol, i.detail?.split(" · ")[0]])).toEqual([
["run", "method", "A"],
["run", "method", "B"],
// Same-named candidates read by their containers.
expect(popup.items.map((i) => [i.label, i.symbol, i.detail])).toEqual([
["A", "method", "p/a.ts:4"],
["B", "method", "p/b.ts:4"],
]);
expect(openFile).not.toHaveBeenCalled();
});
+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 }));
}
+39 -8
Переглянути файл
@@ -16,7 +16,7 @@
*/
import { RangeSet, StateEffect, StateField, type Extension, type Text } from "@codemirror/state";
import { EditorView, GutterMarker, ViewPlugin, type ViewUpdate } from "@codemirror/view";
import { iconAreaSource } from "@/editor/core/cm/iconArea";
import { iconAreaSource, mapLineStart } from "@/editor/core/cm/iconArea";
import { shownAgain, type EditorDocContext } from "@/editor/api";
import { docOf, debounce, isUnavailable, lspRequest } from "@/editor/lsp/lsp";
import { featureBackoff, onServerSettled } from "@/editor/lsp/availability";
@@ -29,6 +29,7 @@ import {
nextRequestId,
onIdeEvent,
type ClassInheritance,
type DocId,
type HierarchyItem,
type Location,
type OutlineItem,
@@ -324,6 +325,8 @@ export async function fillMarkers(
entry(c).supers = {
kind: "overriding",
line: c.line,
col: c.col,
method: c.method,
name: c.name,
targets: [...known.map((s) => s.location), ...extra],
tooltip: tx`Overrides method in ${owners.join(", ")}`,
@@ -510,18 +513,46 @@ export function cachedMarkers(
return out;
}
/**
* A dependency's implementation (Java) starts at `0:0` of the class file: the server resolves
* the method's declaration when the marker is opened, not for every marker in the gutter.
*/
async function markerTargets(marker: LineMarker, doc: DocId | null): Promise<Location[]> {
if (
doc === null ||
doc < 0 ||
!marker.method ||
(marker.kind !== "implemented" && marker.kind !== "overridden") ||
!marker.targets.some((t) => t.range.start.line === 0 && t.uri?.startsWith("jdt:"))
)
return marker.targets;
const request = nextRequestId();
try {
return await lspRequest(() =>
commands.lspImplementationLocations(request, doc, { line: marker.line, col: marker.col }, marker.targets),
);
} catch {
return marker.targets;
}
}
/** Opens the single target, or the chooser over several. */
export async function openMarkerTargets(marker: LineMarker, anchor: { x: number; y: number }) {
if (marker.targets.length === 1) {
await navigateTo(marker.targets[0]!);
export async function openMarkerTargets(
marker: LineMarker,
anchor: { x: number; y: number },
doc: DocId | null = null,
) {
const targets = await markerTargets(marker, doc);
if (targets.length === 1) {
await navigateTo(targets[0]!);
return;
}
openPopup({
kind: "list",
anchor,
title: marker.chooserTitle,
items: await locationItems(marker.targets),
pin: pinToFind(marker.name, marker.targets),
items: await locationItems(targets),
pin: pinToFind(marker.name, targets),
});
}
@@ -541,7 +572,7 @@ const markersField = StateField.define<PlacedMarker[]>({
update(value, tr) {
for (const e of tr.effects) if (e.is(setMarkers)) return e.value;
if (!tr.docChanged || !value.length) return value;
return value.map((m) => ({ ...m, pos: tr.state.doc.lineAt(tr.changes.mapPos(m.pos, -1)).from }));
return value.map((m) => ({ ...m, pos: mapLineStart(tr, m.pos) }));
},
});
@@ -785,7 +816,7 @@ export function implementationGutter(ctx: EditorDocContext): Extension {
if (!marker) return false;
e.preventDefault();
const rect = (target.closest(`.${styles.marker}`) ?? target).getBoundingClientRect();
void openMarkerTargets(marker, { x: rect.left, y: rect.bottom + 2 });
void openMarkerTargets(marker, { x: rect.left, y: rect.bottom + 2 }, ctx.doc);
return true;
},
}),
+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";
+39 -1
Переглянути файл
@@ -1,6 +1,7 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import {
IpcError,
commands,
type ClassInheritance,
type HierarchyItem,
type Location,
@@ -498,13 +499,48 @@ describe("clicking a marker", () => {
it("navigates to a single target", async () => {
const target = loc("/p/Circle.java", 0, 13);
await openMarkerTargets(
{ kind: "implemented", line: 0, name: "Shape", targets: [target], tooltip: "", chooserTitle: "" },
{
kind: "implemented",
line: 0,
col: 17,
method: false,
name: "Shape",
targets: [target],
tooltip: "",
chooserTitle: "",
},
{ x: 1, y: 2 },
);
expect(nav.navigateTo).toHaveBeenCalledWith(target);
expect(nav.openPopup).not.toHaveBeenCalled();
});
it("resolves a dependency's implementation at its method", async () => {
vi.stubGlobal("__TAURI_INTERNALS__", {});
const zero = loc("jdt://contents/lib.jar/zoo/Impl.java?=p/lib.jar", 0, 0);
zero.uri = zero.path;
const method = { ...zero, range: { start: { line: 5, col: 4 }, end: { line: 7, col: 5 } } };
const spy = vi.spyOn(commands, "lspImplementationLocations").mockResolvedValue({ status: "ok", data: [method] });
await openMarkerTargets(
{
kind: "implemented",
line: 1,
col: 9,
method: true,
name: "save",
targets: [zero],
tooltip: "",
chooserTitle: "",
},
{ x: 1, y: 2 },
7,
);
expect(spy).toHaveBeenCalledWith(expect.any(Number), 7, { line: 1, col: 9 }, [zero]);
expect(nav.navigateTo).toHaveBeenCalledWith(method);
spy.mockRestore();
vi.unstubAllGlobals();
});
it("opens the chooser over several targets", async () => {
const targets = [loc("/p/Circle.java", 0, 13), loc("/p/Square.java", 0, 13)];
expect(candidateKey(candidate())).toBe("0:17:Shape");
@@ -512,6 +548,8 @@ describe("clicking a marker", () => {
{
kind: "implemented",
line: 0,
col: 17,
method: false,
name: "Shape",
targets,
tooltip: "",
+18 -1
Переглянути файл
@@ -48,6 +48,10 @@ export interface MarkerCandidate {
export interface LineMarker {
kind: MarkerKind;
line: number;
/** UTF-16 column of the declaration's identifier, the position implementation requests use. */
col: number;
/** A method (not a type): its implementations are methods, not classes. */
method: boolean;
/** Name of the declaration the marker is on. */
name: string;
targets: Location[];
@@ -249,7 +253,16 @@ export function inheritorsMarker(
? tx`Choose Implementation of ${c.name} (${n} found)`
: tx`Choose Overriding Method of ${c.name} (${n} found)`;
}
return { kind, line: c.line, name: c.name, targets: [...targets], tooltip, chooserTitle };
return {
kind,
line: c.line,
col: c.col,
method: c.method,
name: c.name,
targets: [...targets],
tooltip,
chooserTitle,
};
}
/** ↑ marker of a Go type or method from the interfaces (methods) it satisfies; null without any. */
@@ -264,6 +277,8 @@ export function implementsMarker(
return {
kind: "implementing",
line: c.line,
col: c.col,
method: c.method,
name: c.name,
targets: [...targets],
tooltip: c.method ? tx`Implements method in ${names}` : tx`Implements ${names}`,
@@ -293,6 +308,8 @@ export function supersMarker(
return {
kind: implementing ? "implementing" : "overriding",
line: c.line,
col: c.col,
method: true,
name: c.name,
targets: supers.map((s) => s.location),
tooltip: implementing ? tx`Implements method in ${owners}` : tx`Overrides method in ${owners}`,
+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>
);
}
+88
Переглянути файл
@@ -0,0 +1,88 @@
.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);
}
.field {
flex: none;
display: flex;
flex-direction: column;
gap: var(--space-1-5);
}
.source {
font-family: var(--font-mono);
color: var(--fg-muted);
overflow-wrap: anywhere;
}
.table {
display: flex;
flex-direction: column;
border: 1px solid var(--border);
border-radius: 4px;
flex: 1 1 auto;
min-height: 0;
}
.head,
.row {
display: grid;
grid-template-columns: 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);
}
.member {
min-width: 0;
}
.label {
font-family: var(--font-mono);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.error {
flex: none;
color: var(--danger);
font-size: var(--fs-small);
overflow-wrap: anywhere;
}
.busy {
display: flex;
align-items: center;
gap: var(--space-1-5);
color: var(--fg-muted);
}
+137
Переглянути файл
@@ -0,0 +1,137 @@
/** IDEA's Extract Interface dialog for Java classes (`extractInterface.ts`). */
import { useState } from "react";
import { Checkbox, Dialog, Input, Select, Spinner, T } from "@/ui";
import { useTx } from "@/platform/i18n";
import {
extractInterface,
interfaceProblem,
memberLabel,
useExtractInterfaceDialog,
type InterfaceRequest,
} from "./extractInterface";
import styles from "./ExtractInterfaceDialog.module.css";
export function ExtractInterfaceDialog() {
const request = useExtractInterfaceDialog((s) => s.request);
if (!request) return null;
return <ExtractInterfaceDialogInner key={request.seq} request={request} />;
}
function ExtractInterfaceDialogInner({ request }: { request: InterfaceRequest }) {
const tx = useTx();
const { info, packages } = request;
const [name, setName] = useState("");
const [pkg, setPkg] = useState(() =>
String(
Math.max(
0,
packages.findIndex((p) => p.current),
),
),
);
const [checked, setChecked] = useState<ReadonlySet<string>>(new Set());
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const trimmed = name.trim();
const problem = interfaceProblem(trimmed, info.className, checked.size);
const target = packages[Number(pkg)];
const ready = !busy && !problem && !!target;
const allChecked = checked.size === info.members.length;
const close = () => {
useExtractInterfaceDialog.setState({ request: null });
request.view.focus();
};
const toggle = (id: string, on: boolean) =>
setChecked((all) => {
const next = new Set(all);
if (on) next.add(id);
else next.delete(id);
return next;
});
const submit = async (preview: boolean) => {
if (!ready) return;
setBusy(true);
setError(null);
const members = info.members.map((m) => m.handleIdentifier).filter((id) => checked.has(id));
const outcome = await extractInterface(request, trimmed, target, members, preview);
if (useExtractInterfaceDialog.getState().request !== request) return;
setBusy(false);
if (outcome.status === "done") close();
else if (outcome.error) setError(outcome.error);
};
return (
<Dialog
open
onClose={close}
title="Extract Interface"
className={styles.dialog}
width={560}
minHeight={360}
maxHeight={600}
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.field}>
<T>Extract interface from:</T>
<span className={styles.source}>{info.className}</span>
</div>
<label className={styles.field}>
<T>Interface name:</T>
<Input mono autoFocus value={name} onChange={(e) => setName(e.target.value)} />
</label>
<label className={styles.field}>
<T>Package for new interface:</T>
<Select
aria-label="Package for new interface"
value={pkg}
options={packages.map((p, i) => ({ value: String(i), label: p.name, icon: "package" }))}
onChange={setPkg}
/>
</label>
<div className={styles.table} role="table" aria-label={tx("Members to Form Interface")}>
<div className={styles.head} role="row">
<Checkbox
checked={allChecked}
indeterminate={checked.size > 0 && !allChecked}
onChange={(on) => setChecked(on ? new Set(info.members.map((m) => m.handleIdentifier)) : new Set())}
label={<T>Members to Form Interface</T>}
/>
</div>
<div className={styles.rows}>
{info.members.map((m) => (
<div key={m.handleIdentifier} className={styles.row} role="row">
<Checkbox
className={styles.member}
checked={checked.has(m.handleIdentifier)}
onChange={(on) => toggle(m.handleIdentifier, on)}
label={<span className={styles.label}>{memberLabel(m)}</span>}
/>
</div>
))}
</div>
</div>
{(error ?? (trimmed && problem)) && (
<span className={styles.error} role="alert">
{tx(error ?? problem!)}
</span>
)}
</div>
</Dialog>
);
}
+10 -1
Переглянути файл
@@ -2,7 +2,8 @@
* IDEA's refactorings and how language-server code actions map onto them:
* `refactor.extract.*` → Extract Method / Introduce Variable…, `refactor.inline*`
* → Inline, `refactor.move*` → Move, signature rewrites → Change Signature.
* Pull Members Up / Push Members Down come from the Java extension, not code actions.
* Pull Members Up / Push Members Down come from the Java extension, Extract Interface from jdtls
* requests, not code actions.
* Pure; used by Refactor This (⌃T) and the Refactor menu actions.
*/
import type { CodeAction } from "@/bindings";
@@ -17,6 +18,7 @@ export type RefactoringId =
| "extractConstant"
| "extractField"
| "extractParameter"
| "extractInterface"
| "inline"
| "pullMembersUp"
| "pushMembersDown";
@@ -96,6 +98,13 @@ export const REFACTORINGS: readonly Refactoring[] = [
reason: (sel) =>
sel ? "Selected block should represent an expression" : "Caret should be inside an expression in a function",
},
{
id: "extractInterface",
action: "refactor.extractInterface",
label: "Extract Interface…",
kind: null,
reason: () => "Caret should be inside a class",
},
{ id: "inline", action: "refactor.inline", label: "Inline…", kind: "refactor.inline", reason: () => AT_NAME },
{
id: "pullMembersUp",
+29
Переглянути файл
@@ -0,0 +1,29 @@
import { describe, expect, it } from "vitest";
import { interfaceProblem, memberLabel, packageChoices } from "./extractInterface";
describe("extract interface", () => {
it("labels methods with their parameter types and fields with their type", () => {
const m = { name: "area", typeName: "double", parameters: ["int", "String"], handleIdentifier: "m" };
expect(memberLabel(m)).toBe("area(int, String): double");
expect(memberLabel({ ...m, parameters: [] })).toBe("area(): double");
expect(memberLabel({ name: "UNIT", typeName: "int", parameters: null, handleIdentifier: "f" })).toBe("UNIT: int");
});
it("keeps each package's server JSON and marks the file's own package", () => {
const json = [
JSON.stringify({ displayName: "com.a", path: "src/com/a", isParentOfSelectedFile: true }),
JSON.stringify({ displayName: "", path: "src" }),
];
const [own, root] = packageChoices(json);
expect(own).toMatchObject({ name: "com.a", current: true, json: json[0] });
expect(root).toMatchObject({ name: "(default package)", current: false });
});
it("needs a valid name other than the class's and at least one member", () => {
expect(interfaceProblem("", "Shape", 1)).toBe("No interface name specified");
expect(interfaceProblem("1x", "Shape", 1)).toBe("Interface name is not a valid identifier");
expect(interfaceProblem("Shape", "Shape", 1)).toBe("Interface name should differ from the class name");
expect(interfaceProblem("HasArea", "Shape", 0)).toBe("Select the members to form the interface");
expect(interfaceProblem("HasArea", "Shape", 2)).toBeNull();
});
});
+173
Переглянути файл
@@ -0,0 +1,173 @@
/**
* Extract Interface for Java: jdtls lists the members of the file's class and the packages, the
* dialog (`ExtractInterfaceDialog.tsx`) picks the interface's name, package and members, and
* jdtls creates the interface, makes the class implement it and uses it where possible.
*/
import type { Text } from "@codemirror/state";
import type { EditorView } from "@codemirror/view";
import { create } from "zustand";
import type { ExtractInterfaceInfo, InterfaceMember, Pos, ServerRefactored } from "@/bindings";
import { whenSynced } from "@/editor/api";
import { docOf, isUnavailable, lspRequest } 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 { editorService } from "@/workbench/contributions";
import { cannotPerform } from "./catalog";
import { applyEdit, confirmProblems } from "./signature";
/** Languages whose server extracts interfaces through the dialog. */
export const EXTRACT_INTERFACE_LANGUAGES = new Set(["java"]);
type Json = Record<string, unknown>;
/** A package the interface can go to; `json` is passed back to the server unchanged. */
export interface PackageChoice {
name: string;
path: string;
current: boolean;
json: string;
}
export function packageChoices(packages: readonly string[]): PackageChoice[] {
return packages.map((json) => {
const p = JSON.parse(json) as Json;
const text = (v: unknown) => (typeof v === "string" ? v : "");
return {
name: text(p.displayName) || "(default package)",
path: text(p.path),
current: !!p.isParentOfSelectedFile,
json,
};
});
}
/** `area(double): double` for a method, `UNIT: int` for a field. */
export function memberLabel(m: InterfaceMember): string {
const params = m.parameters ? `(${m.parameters.join(", ")})` : "";
return `${m.name}${params}: ${m.typeName}`;
}
const JAVA_NAME = /^[A-Za-z_$][\w$]*$/;
/** Why the interface can't be extracted yet, or null. */
export function interfaceProblem(name: string, className: string, members: number): string | null {
if (!name) return "No interface name specified";
if (!JAVA_NAME.test(name)) return "Interface name is not a valid identifier";
if (name === className) return "Interface name should differ from the class name";
if (!members) return "Select the members to form the interface";
return null;
}
export interface InterfaceRequest {
seq: number;
view: EditorView;
doc: number;
pos: Pos;
/** The document `pos` refers to. */
text: Text;
info: ExtractInterfaceInfo;
packages: PackageChoice[];
}
export const useExtractInterfaceDialog = create<{ request: InterfaceRequest | 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);
}
/** Extract Interface…: reads the file's class, then opens the dialog. */
export async function startExtractInterface(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.lspExtractInterfaceInfo(request, ctx.doc, pos));
if (run.signal.aborted || view.state.doc !== state.doc) return;
if (!info.members.length) {
showHint(view, cannotPerform("The class has no members to form an interface"));
return;
}
const packages = packageChoices(info.packages);
useExtractInterfaceDialog.setState({
request: { seq: ++seq, view, doc: ctx.doc, pos, text: state.doc, info, packages },
});
} 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 type InterfaceOutcome = { status: "done" } | { status: "stay"; error?: string };
/** Checks the extraction, confirms its problems and applies the edit (opening the new interface), or previews it. */
export async function extractInterface(
request: InterfaceRequest,
name: string,
pkg: PackageChoice,
members: readonly string[],
preview: boolean,
): Promise<InterfaceOutcome> {
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 extracted: ServerRefactored;
try {
for (;;) {
await whenSynced(view);
const token: string | null = confirmation;
extracted = await lspRequest(() =>
commands.lspExtractInterface(nextRequestId(), request.doc, request.pos, [...members], name, pkg.json, token),
);
const fatal = extracted.problems.find((p) => p.severity === "fatal");
if (fatal || (!extracted.edit && !extracted.confirmation))
return { status: "stay", error: fatal?.message ?? "Nothing to change" };
if (!extracted.confirmation) break;
if (!(await confirmProblems(extracted.problems.map((p) => p.message)))) return { status: "stay" };
confirmation = extracted.confirmation;
}
} catch (e) {
if (isCancelled(e)) return { status: "stay" };
return { status: "stay", error: errorText(e) };
}
const edit = extracted.edit!;
const summary = summarizeWorkspaceEdit(edit);
if (!summary.files) return { status: "stay", error: "Nothing to change" };
const created = edit.files.find((f) => f.kind === "create")?.path;
const apply = async () => {
await applyEdit(view, edit);
if (created) await editorService().openFile(created, { focus: true });
};
if (preview) {
openPopup({
kind: "preview",
title: tx`Extract Interface from '${request.info.className}'`,
summary,
confirmLabel: "Do Refactor",
onConfirm: () => void apply(),
});
} else {
await apply();
}
return { status: "done" };
}
+3
Переглянути файл
@@ -1,4 +1,7 @@
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";
export { ExtractInterfaceDialog } from "./ExtractInterfaceDialog";
+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 -2
Переглянути файл
@@ -66,6 +66,8 @@ const safeDelete = vi.fn();
vi.mock("./safeDelete", () => ({ safeDelete }));
const startHierarchyRefactoring = vi.fn();
vi.mock("./hierarchy", () => ({ startHierarchyRefactoring }));
const startExtractInterface = vi.fn();
vi.mock("./extractInterface", () => ({ EXTRACT_INTERFACE_LANGUAGES: new Set(["java"]), startExtractInterface }));
const { classifyAction, kindAdvertised, cannotPerform } = await import("./catalog");
const { refactorThis, runRefactoring } = await import("./refactorThis");
@@ -195,19 +197,27 @@ describe("Refactor This", () => {
expect(lspCodeActionQuery.mock.calls[0]![3]).toEqual(["refactor"]);
});
it("offers Pull Members Up / Push Members Down in Java files, after IDEA's other refactorings", async () => {
it("offers Extract Interface, Pull Members Up and Push Members Down in Java files, after IDEA's other refactorings", async () => {
query = answer([action("Convert to switch expression", "refactor.rewrite")]);
const v = editor("class Dog extends Animal { int price; }", "java");
await refactorThis(v, vi.fn());
expect(labels()).toEqual(["Pull Members Up…", "Push Members Down…", "Convert to switch expression"]);
expect(labels()).toEqual([
"Extract Interface…",
"Pull Members Up…",
"Push Members Down…",
"Convert to switch expression",
]);
const items = (useLspPopup.getState().popup as { items: { label: string; run: () => void }[] }).items;
items.find((i) => i.label === "Push Members Down…")!.run();
expect(startHierarchyRefactoring).toHaveBeenCalledWith(v, "pushDown");
items.find((i) => i.label === "Extract Interface…")!.run();
expect(startExtractInterface).toHaveBeenCalledWith(v);
closePopup();
v.destroy();
// Other languages have no server for them; nor does Java while its server is down.
await refactorThis(editor(), vi.fn());
expect(labels()).not.toContain("Pull Members Up…");
expect(labels()).not.toContain("Extract Interface…");
query = async () => unavailable;
await refactorThis(editor("class Dog {}", "java"), vi.fn());
expect(labels()).toEqual(["Nothing here"]);
+28 -3
Переглянути файл
@@ -40,6 +40,8 @@ import {
} from "./serverIntroduce";
import { safeDelete } from "./safeDelete";
import { startHierarchyRefactoring } from "./hierarchy";
import { SIGNATURE_LANGUAGES, startChangeSignature } from "./signature";
import { EXTRACT_INTERFACE_LANGUAGES, startExtractInterface } from "./extractInterface";
/** 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 +155,15 @@ 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;
}
if (id === "extractInterface") {
if (EXTRACT_INTERFACE_LANGUAGES.has(ctx.language)) await startExtractInterface(view);
else showHint(view, cannotPerform(`Extract Interface is not supported for ${await languageName(ctx.language)}`));
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 +230,13 @@ 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; extractInterface?: boolean },
run: {
rename: (view: EditorView) => unknown;
safeDelete: (view: EditorView) => unknown;
hierarchy?: (view: EditorView, kind: "pullUp" | "pushDown") => unknown;
signature?: (view: EditorView) => unknown;
extractInterface?: (view: EditorView) => unknown;
},
): ListPopupItem[] {
const { mapped, other } = groupActions(answer.status === "ok" ? answer.query.actions : []);
@@ -237,6 +250,10 @@ 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 (r.id === "extractInterface" && facts.extractInterface && serverUsable && run.extractInterface)
go = () => run.extractInterface!(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 +295,19 @@ 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;
const extractInterface = EXTRACT_INTERFACE_LANGUAGES.has(ctx.language) && !ctx.readOnly;
items = refactorThisItems(
view,
answer,
{ symbol, expression, hierarchy },
{ rename, safeDelete, hierarchy: startHierarchyRefactoring },
{ symbol, expression, hierarchy, signature, extractInterface },
{
rename,
safeDelete,
hierarchy: startHierarchyRefactoring,
signature: startChangeSignature,
extractInterface: startExtractInterface,
},
);
} 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;
Loaded 100 of 143 files, more files were not shown because too many files have changed in this diff. Show more