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

..
Автор SHA1 Повідомлення Дата
l0ng-ai 2bb14c9704 fix(database): keep unsubmitted result edits while another result tab is shown
The result pane remounts when another result tab is selected, so its pending
cell edits, added and deleted rows were dropped. They are now kept by the rows
they were made on, so switching back restores them; a re-run or another page
still starts over.
2026-11-13 17:00:14 +08:00
50 змінених файлів з 138 додано та 958 видалено

No files matched your search

-9
Переглянути файл
@@ -270,13 +270,6 @@ fn run(
/// The first error lines of a failed build, for the tool window.
pub(crate) fn error_summary(text: &str) -> String {
// The JVM's "could not find or load main class" (localized) when `gradlew` has no jar.
if text.contains("org.gradle.wrapper.GradleWrapperMain") {
return "gradle/wrapper/gradle-wrapper.jar is missing (often excluded by a `*.jar` rule in .gitignore). \
Restore it, run `gradle wrapper` with an installed Gradle, or choose Distribution: Local installation \
in Settings › Build, Execution, Deployment › Gradle."
.to_owned();
}
let lines: Vec<&str> = text
.lines()
.filter(|l| {
@@ -916,8 +909,6 @@ mod tests {
let text = "[INFO] x\n[ERROR] Failed to execute goal\n[ERROR] \n[ERROR] Re-run Maven using -X\n";
assert_eq!(error_summary(text), "Failed to execute goal");
assert_eq!(error_summary("one\nlast line\n\n"), "last line");
let missing_jar = "错误: 找不到或无法加载主类 org.gradle.wrapper.GradleWrapperMain\n";
assert!(error_summary(missing_jar).starts_with("gradle/wrapper/gradle-wrapper.jar is missing"));
}
#[test]
-3
Переглянути файл
@@ -77,9 +77,6 @@ pub enum IdeEvent {
WorkspaceEditApplied {
id: u32,
paths: Vec<crate::IpcPath>,
/// Made by an agent through the MCP server's tools: undoable like a refactoring, but
/// not announced as one.
by_agent: bool,
},
/// An open document's language changed (Settings › File Types, Override File
/// Type), or its UI mode (a framework's root marker appeared or went).
+1 -20
Переглянути файл
@@ -300,30 +300,11 @@ pub struct McpServerSettings {
pub agent_tab_limit: u32,
/// Archived agent tabs kept; older ones are closed.
pub agent_archive_limit: u32,
/// Listen on [`Self::port`] in every run, rather than a free port each time, so HTTP clients and
/// port forwards keep working after a restart.
pub fixed_port: bool,
/// The port of [`Self::fixed_port`].
pub port: u16,
/// Keep the bearer token across runs (in the app data, readable by this user only) rather than
/// make a new one each run.
pub fixed_token: bool,
}
/// The default of [`McpServerSettings::port`].
pub const DEFAULT_MCP_PORT: u16 = 26371;
impl Default for McpServerSettings {
fn default() -> Self {
Self {
enabled: false,
run_without_confirmation: false,
agent_tab_limit: 1,
agent_archive_limit: 999,
fixed_port: true,
port: DEFAULT_MCP_PORT,
fixed_token: false,
}
Self { enabled: false, run_without_confirmation: false, agent_tab_limit: 1, agent_archive_limit: 999 }
}
}
+3 -3
Переглянути файл
@@ -87,7 +87,7 @@ async fn create_or_replace(call: &Call, path: PathBuf, text: Option<String>, ove
return Ok(());
}
let edit = crate::ops::lsp::prepare_workspace_edit(&call.host, call.window(), edit).await?;
crate::ops::lsp::apply_agent_workspace_edit(&call.host, call.window(), edit).await
crate::ops::lsp::apply_workspace_edit(&call.host, call.window(), edit).await
}
/// The open document of `path`, or a transient one (`true`: close it after use).
@@ -317,7 +317,7 @@ async fn apply_op(call: &Call, op: FileOp, notes: &mut Vec<String>) -> IdeResult
preconditions: Vec::new(),
};
let edit = crate::ops::lsp::prepare_workspace_edit(&host, call.window(), edit).await?;
crate::ops::lsp::apply_agent_workspace_edit(&host, call.window(), edit).await
crate::ops::lsp::apply_workspace_edit(&host, call.window(), edit).await
}
FileOp::Update { path: first, move_to, hunks, or } => {
// A plain diff's other names count when its `+++` path does not exist.
@@ -400,7 +400,7 @@ async fn apply_op(call: &Call, op: FileOp, notes: &mut Vec<String>) -> IdeResult
edit.files.push(FileEdit::Rename { from: path.into(), to: to.into() });
}
let edit = crate::ops::lsp::prepare_workspace_edit(&host, call.window(), edit).await?;
crate::ops::lsp::apply_agent_workspace_edit(&host, call.window(), edit).await?;
crate::ops::lsp::apply_workspace_edit(&host, call.window(), edit).await?;
if dirty {
notes.push(format!("{shown}: patched the unsaved editor buffer"));
}
+1 -1
Переглянути файл
@@ -385,7 +385,7 @@ targetIndex, or narrow the call with a contextSnippet that shows the one you mea
_ => None,
});
let (h, w) = (host.clone(), window.to_owned());
let written = crate::ops::lsp::apply_agent_workspace_edit(&h, &w, edit).await;
let written = crate::ops::lsp::apply_workspace_edit(&h, &w, edit).await;
if let Err(e) = written {
let hint = format!("The rename stopped while it wrote. {} Read the files again before you retry.", e.message);
return Ok(RenameResult::failed("write_failed", hint).with_symbol(symbol));
+12 -27
Переглянути файл
@@ -1483,38 +1483,23 @@ pub async fn lsp_restart_named(host: &Host, name: &str) -> IdeResult<()> {
pub async fn apply_workspace_edit(host: &Host, window: &str, edit: WorkspaceEdit) -> IdeResult<()> {
let project = host.project(window)?;
blocking(move || {
record_before_multi_file_edit(&project, &edit);
// Multi-file refactorings leave a Local History point to go back to.
let paths: Vec<&std::path::Path> = edit
.files
.iter()
.filter_map(|f| match f {
ide_core::FileEdit::Edit { path, .. } => Some(&**path),
_ => None,
})
.collect();
if edit.files.len() > 1 {
project.record_before_refactoring(&paths, "Apply changes");
}
apply_edit(&project.documents, &edit)
})
.await
}
/// [`apply_workspace_edit`] for the MCP server's tools: undoable the same way, but the UI does
/// not announce it as a refactoring.
pub async fn apply_agent_workspace_edit(host: &Host, window: &str, edit: WorkspaceEdit) -> IdeResult<()> {
let project = host.project(window)?;
blocking(move || {
record_before_multi_file_edit(&project, &edit);
project.documents.apply_agent_workspace_edit(&edit)
})
.await
}
/// Multi-file edits leave a Local History point to go back to.
fn record_before_multi_file_edit(project: &crate::Project, edit: &WorkspaceEdit) {
let paths: Vec<&std::path::Path> = edit
.files
.iter()
.filter_map(|f| match f {
ide_core::FileEdit::Edit { path, .. } => Some(&**path),
_ => None,
})
.collect();
if edit.files.len() > 1 {
project.record_before_refactoring(&paths, "Apply changes");
}
}
pub async fn prepare_workspace_edit(host: &Host, window: &str, mut edit: WorkspaceEdit) -> IdeResult<WorkspaceEdit> {
let project = host.project(window)?;
blocking(move || {
+1 -5
Переглянути файл
@@ -231,11 +231,7 @@ async fn mutations_preserve_unsaved_text_and_reject_metadata_and_escapes() {
.iter()
.rev()
.find_map(|event| match event {
// Undoable like a refactoring, but marked as the agent's, so it isn't announced as one.
IdeEvent::WorkspaceEditApplied { id, by_agent, .. } => {
assert!(*by_agent, "an MCP edit is the agent's");
Some(*id)
}
IdeEvent::WorkspaceEditApplied { id, .. } => Some(*id),
_ => None,
})
.unwrap();
+5 -9
Переглянути файл
@@ -223,8 +223,6 @@ impl ClientHandler {
if self.server.running_gen(self.generation).is_some_and(|run| !run.caps.read().restriction.diagnostics()) {
return;
}
let mut params = params;
crate::virtual_doc::normalize_uris(&mut params);
let params: lsp::PublishDiagnosticsParams = match serde_json::from_value(params) {
Ok(p) => p,
Err(e) => {
@@ -324,13 +322,11 @@ impl ClientHandler {
}
fn apply_edit(&self, mgr: &LspManager, params: Value) -> Result<Value, (i64, String)> {
let edit: lsp::WorkspaceEdit =
params.get("edit").cloned().ok_or_else(|| (codes::INVALID_PARAMS, "missing edit".to_owned())).and_then(
|mut e| {
crate::virtual_doc::normalize_uris(&mut e);
serde_json::from_value(e).map_err(|e| (codes::INVALID_PARAMS, e.to_string()))
},
)?;
let edit: lsp::WorkspaceEdit = params
.get("edit")
.cloned()
.ok_or_else(|| (codes::INVALID_PARAMS, "missing edit".to_owned()))
.and_then(|e| serde_json::from_value(e).map_err(|e| (codes::INVALID_PARAMS, e.to_string())))?;
// Convert before calling the hook: it re-enters document sync.
let edit = convert::workspace_edit(&mgr.conv(self.encoding()), edit);
let applied = match mgr.apply_edit_hook() {
+7 -3
Переглянути файл
@@ -1440,9 +1440,13 @@ impl LspManager {
let params = serde_json::to_value(params).map_err(|e| IdeError::internal(e.to_string()))?;
let stamp = self.injected_request_stamp(&params);
let fut = async {
let mut value = t.run.peer.request::<Value, Value>(method, params, cancel.cloned()).await?;
virtual_doc::normalize_uris(&mut value);
serde_json::from_value(value).map_err(|e| RpcError::Protocol(format!("{method}: {e}")))
if t.server.name == "csharp-ls" {
let mut value = t.run.peer.request::<Value, Value>(method, params, cancel.cloned()).await?;
virtual_doc::normalize_csharp_uris(&mut value);
serde_json::from_value(value).map_err(|e| RpcError::Protocol(format!("{method}: {e}")))
} else {
t.run.peer.request::<Value, R>(method, params, cancel.cloned()).await
}
};
let result = match tokio::time::timeout(timeout, fut).await {
Ok(r) => r.map_err(|e| rpc_err(&t.server.name, method, e)),
+10 -58
Переглянути файл
@@ -18,36 +18,23 @@ const URI_ESCAPES: &AsciiSet = &CONTROLS
.add(b'|')
.add(b'}');
/// Servers can leave spaces and Unicode unescaped in document URIs: csharp-ls uses .NET
/// `Uri.ToString()`, and Java servers build some URIs with `java.net.URI.toString()` (which keeps
/// non-ASCII characters), e.g. jdtls in a refactoring's edit for a project under a Chinese path.
/// Escape them in document URI fields (and `WorkspaceEdit.changes` keys) before lsp-types' strict
/// URI deserialization, which otherwise rejects the whole response.
pub(crate) fn normalize_uris(value: &mut serde_json::Value) {
/// csharp-ls uses .NET Uri.ToString(), which can leave spaces and Unicode unescaped.
/// Normalize only document URI fields, before lsp-types' strict URI deserialization.
pub(crate) fn normalize_csharp_uris(value: &mut serde_json::Value) {
match value {
serde_json::Value::Array(values) => values.iter_mut().for_each(normalize_uris),
serde_json::Value::Array(values) => values.iter_mut().for_each(normalize_csharp_uris),
serde_json::Value::Object(fields) => {
for (key, value) in fields.iter_mut() {
for (key, value) in fields {
// Opaque payloads must survive resolve/execute round trips unchanged.
if matches!(key.as_str(), "data" | "arguments") {
continue;
}
if matches!(key.as_str(), "uri" | "targetUri" | "oldUri" | "newUri")
&& let Some(uri) = value.as_str().and_then(escaped_uri)
if matches!(key.as_str(), "uri" | "targetUri")
&& let Some(uri) = value.as_str().filter(|s| s.starts_with("csharp:"))
{
*value = uri.into();
} else if key == "changes"
&& let serde_json::Value::Object(changes) = value
{
*changes = std::mem::take(changes)
.into_iter()
.map(|(uri, mut edits)| {
normalize_uris(&mut edits);
(escaped_uri(&uri).unwrap_or(uri), edits)
})
.collect();
*value = utf8_percent_encode(uri, URI_ESCAPES).to_string().into();
} else {
normalize_uris(value);
normalize_csharp_uris(value);
}
}
}
@@ -55,16 +42,6 @@ pub(crate) fn normalize_uris(value: &mut serde_json::Value) {
}
}
/// `uri` with the characters a URI can't hold escaped; `None` when nothing changes or it is
/// not a document URI this applies to (other schemes are passed back to servers as given).
fn escaped_uri(uri: &str) -> Option<String> {
if !(uri.starts_with("file:") || uri.starts_with("csharp:")) {
return None;
}
let escaped = utf8_percent_encode(uri, URI_ESCAPES).to_string();
(escaped != uri).then_some(escaped)
}
#[derive(serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct CSharpMetadata {
@@ -225,7 +202,7 @@ mod tests {
{ "data": { "uri": uri }, "command": { "arguments": [{ "targetUri": uri }] } }
]);
let original = response.clone();
normalize_uris(&mut response);
normalize_csharp_uris(&mut response);
assert_eq!(response[0]["uri"], encoded);
assert_eq!(response[0]["source"], uri);
assert_eq!(response[1]["location"]["targetUri"], encoded);
@@ -233,31 +210,6 @@ mod tests {
assert!(encoded.parse::<lsp_types::Uri>().is_ok());
}
/// #3089: jdtls's Introduce Variable edit for a project under a Chinese path names the file
/// with the characters unescaped, and the resolved code action failed to deserialize.
#[test]
fn file_uris_with_unicode_and_spaces_deserialize_in_workspace_edits() {
let uri = "file:///C:/项目/my app/src/A.java";
let encoded = "file:///C:/%E9%A1%B9%E7%9B%AE/my%20app/src/A.java";
let edit = serde_json::json!([{ "range": { "start": { "line": 0, "character": 0 }, "end": { "line": 0, "character": 0 } }, "newText": "x" }]);
let mut action = serde_json::json!({
"title": "Extract to local variable",
"edit": {
"documentChanges": [{ "textDocument": { "uri": uri, "version": 3 }, "edits": edit }],
"changes": { (uri): edit },
},
"data": { "uri": uri },
});
assert!(serde_json::from_value::<lsp_types::CodeAction>(action.clone()).is_err());
normalize_uris(&mut action);
let action: lsp_types::CodeAction = serde_json::from_value(action.clone()).unwrap();
let edit = action.edit.unwrap();
let Some(lsp_types::DocumentChanges::Edits(edits)) = edit.document_changes else { panic!() };
assert_eq!(edits[0].text_document.uri.as_str(), encoded);
assert_eq!(edit.changes.unwrap().keys().next().unwrap().as_str(), encoded);
assert_eq!(action.data.unwrap()["uri"], uri, "opaque data is passed back unchanged");
}
#[test]
fn jdt_titles() {
assert_eq!(title(JDT, true), "SpringApplication.class");
+9 -56
Переглянути файл
@@ -1,7 +1,6 @@
//! `<app-data>/mcp/server.json`: where the running IDE's server listens and
//! its token, for the stdio bridge. Readable only by the user; removed when
//! the server stops. `<app-data>/mcp/token` keeps the token across runs when
//! the user chose a fixed token.
//! the server stops.
use serde::{Deserialize, Serialize};
use std::io;
@@ -15,28 +14,6 @@ pub fn discovery_path(app_data: &Path) -> PathBuf {
app_data.join(DISCOVERY_FILE)
}
/// The kept token, relative to the app data directory.
pub const TOKEN_FILE: &str = "mcp/token";
/// The kept token of the IDE whose app data directory is `app_data`.
pub fn token_path(app_data: &Path) -> PathBuf {
app_data.join(TOKEN_FILE)
}
/// The token kept at `path`; a new one is made and kept there when there is none (or the
/// file doesn't hold one). Readable only by the user.
pub fn kept_token(path: &Path) -> io::Result<String> {
if let Ok(text) = std::fs::read_to_string(path) {
let token = text.trim();
if token.len() == 64 && token.bytes().all(|b| b.is_ascii_hexdigit()) {
return Ok(token.to_owned());
}
}
let token = crate::server::new_token()?;
write_atomic(path, token.as_bytes())?;
Ok(token)
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Discovery {
pub port: u16,
@@ -55,8 +32,15 @@ impl Discovery {
/// Writes the file atomically, readable only by the user.
pub fn write(&self, path: &Path) -> io::Result<()> {
let dir = path.parent().ok_or_else(|| io::Error::other("no parent directory"))?;
std::fs::create_dir_all(dir)?;
let tmp = path.with_extension(format!("tmp{}", std::process::id()));
let bytes = serde_json::to_vec_pretty(self).map_err(io::Error::other)?;
write_atomic(path, &bytes)
let written = write_private(&tmp, &bytes).and_then(|()| std::fs::rename(&tmp, path));
if written.is_err() {
let _ = std::fs::remove_file(&tmp);
}
written
}
/// Removes the file at `path` if it still describes this process's server.
@@ -67,18 +51,6 @@ impl Discovery {
}
}
/// Writes `bytes` to `path` atomically, readable only by the user.
fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> {
let dir = path.parent().ok_or_else(|| io::Error::other("no parent directory"))?;
std::fs::create_dir_all(dir)?;
let tmp = path.with_extension(format!("tmp{}", std::process::id()));
let written = write_private(&tmp, bytes).and_then(|()| std::fs::rename(&tmp, path));
if written.is_err() {
let _ = std::fs::remove_file(&tmp);
}
written
}
#[cfg(unix)]
fn write_private(path: &Path, bytes: &[u8]) -> io::Result<()> {
use std::io::Write;
@@ -119,23 +91,4 @@ mod tests {
Discovery::remove_if_ours(&path);
assert!(!path.exists());
}
#[test]
fn keeps_one_token_until_its_file_is_removed() {
let tmp = tempfile::tempdir().unwrap();
let path = token_path(tmp.path());
let first = kept_token(&path).unwrap();
assert_eq!(first.len(), 64);
assert_eq!(kept_token(&path).unwrap(), first, "the same token on the next run");
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
}
std::fs::write(&path, "not a token").unwrap();
let replaced = kept_token(&path).unwrap();
assert_ne!(replaced, first);
std::fs::remove_file(&path).unwrap();
assert_ne!(kept_token(&path).unwrap(), replaced, "a removed token is made anew");
}
}
+2 -2
Переглянути файл
@@ -22,8 +22,8 @@ mod protocol;
mod server;
pub mod stdio;
pub use discovery::{DISCOVERY_FILE, Discovery, TOKEN_FILE, discovery_path, kept_token, token_path};
pub use server::{McpServer, ServerOptions};
pub use discovery::{DISCOVERY_FILE, Discovery, discovery_path};
pub use server::McpServer;
pub use tokio_util::sync::CancellationToken;
use std::path::{Path, PathBuf};
+3 -43
Переглянути файл
@@ -49,25 +49,12 @@ struct Shared {
/// removes its discovery file.
pub struct McpServer {
port: u16,
/// Why the port asked for in [`ServerOptions::port`] was not used.
port_unavailable: Option<String>,
token: String,
discovery: Option<PathBuf>,
shutdown: watch::Sender<bool>,
cancel: CancellationToken,
}
/// How [`McpServer::start_with`] listens.
#[derive(Clone, Debug, Default)]
pub struct ServerOptions {
/// Listen on `127.0.0.1:<port>`. When it can't be bound (in use, or reserved by the
/// system), a free port is taken instead and [`McpServer::port_unavailable`] says why.
/// `None`: a free port.
pub port: Option<u16>,
/// The bearer token; `None`: a new one.
pub token: Option<String>,
}
impl McpServer {
/// Starts listening on `127.0.0.1:<random port>` with a new token, on
/// `runtime`, and writes the discovery file at `discovery` if given.
@@ -76,32 +63,10 @@ impl McpServer {
discovery: Option<PathBuf>,
runtime: &tokio::runtime::Handle,
) -> std::io::Result<Self> {
Self::start_with(registry, discovery, runtime, ServerOptions::default())
}
/// [`Self::start`] on the port and with the token of `options`.
pub fn start_with(
registry: Arc<dyn ToolRegistry>,
discovery: Option<PathBuf>,
runtime: &tokio::runtime::Handle,
options: ServerOptions,
) -> std::io::Result<Self> {
let (listener, port_unavailable) = match options.port {
Some(port) => match std::net::TcpListener::bind(("127.0.0.1", port)) {
Ok(listener) => (listener, None),
Err(e) => {
tracing::warn!("MCP server: port {port} unavailable ({e}); taking a free one");
(std::net::TcpListener::bind(("127.0.0.1", 0))?, Some(format!("port {port}: {e}")))
}
},
None => (std::net::TcpListener::bind(("127.0.0.1", 0))?, None),
};
let listener = std::net::TcpListener::bind(("127.0.0.1", 0))?;
listener.set_nonblocking(true)?;
let port = listener.local_addr()?.port();
let token = match options.token {
Some(token) => token,
None => new_token()?,
};
let token = new_token()?;
let listener = {
let _entered = runtime.enter();
tokio::net::TcpListener::from_std(listener)?
@@ -126,18 +91,13 @@ impl McpServer {
});
runtime.spawn(accept(listener, shared, stopped));
tracing::info!("MCP server on 127.0.0.1:{port}");
Ok(Self { port, port_unavailable, token, discovery, shutdown, cancel })
Ok(Self { port, token, discovery, shutdown, cancel })
}
pub fn port(&self) -> u16 {
self.port
}
/// Why the port of [`ServerOptions::port`] is not the one listened on.
pub fn port_unavailable(&self) -> Option<&str> {
self.port_unavailable.as_deref()
}
/// The bearer token of this run.
pub fn token(&self) -> &str {
&self.token
+1 -28
Переглянути файл
@@ -1,7 +1,7 @@
//! The server over real HTTP, and the stdio bridge in front of it, with a
//! registry standing in for the IDE host.
use ide_mcp::{Discovery, McpServer, ServerOptions, Tool, ToolCallError, ToolRegistry, discovery_path, stdio};
use ide_mcp::{Discovery, McpServer, Tool, ToolCallError, ToolRegistry, discovery_path, stdio};
use serde_json::{Value, json};
use std::path::{Path, PathBuf};
use std::sync::Arc;
@@ -366,30 +366,3 @@ async fn a_cancellation_that_arrives_before_the_call_is_remembered() {
let (_, body) = post(&s, "/mcp", &headers, &call).await;
assert_eq!(serde_json::from_str::<Value>(&body).unwrap()["result"]["isError"], true);
}
#[tokio::test(flavor = "multi_thread")]
async fn a_fixed_port_and_token_are_used_and_a_taken_port_falls_back_to_a_free_one() {
let mut s = setup();
s.server.take().unwrap().stop();
let free = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap().local_addr().unwrap().port();
let token = "ab".repeat(32);
let options = ServerOptions { port: Some(free), token: Some(token.clone()) };
let registry = Arc::new(Registry { project: s.project.clone() });
let runtime = tokio::runtime::Handle::current();
s.server =
Some(McpServer::start_with(registry.clone(), Some(s.discovery.clone()), &runtime, options.clone()).unwrap());
assert_eq!((s.server().port(), s.server().token()), (free, token.as_str()));
assert!(s.server().port_unavailable().is_none());
assert_eq!(Discovery::read(&s.discovery).unwrap().port, free);
let list = rpc(&s, "tools/list", json!({})).await;
assert_eq!(list["result"]["tools"][0]["name"], "echo");
// The port is taken (by the first server): a second one listens elsewhere and says why.
let second = McpServer::start_with(registry, None, &runtime, options).unwrap();
assert_ne!(second.port(), free);
assert!(
second.port_unavailable().is_some_and(|why| why.contains(&free.to_string())),
"{:?}",
second.port_unavailable()
);
}
-27
Переглянути файл
@@ -323,18 +323,6 @@ fn resolve_gradle_command(root: &Path, build_dir: &Path, s: &Settings, use_wrapp
}
let wrapper = build_dir.join(if cfg!(windows) { "gradlew.bat" } else { "gradlew" });
if use_wrapper && wrapper.is_file() {
// `gradlew` can't start without its jar, which `.gitignore`s with `*.jar` often leave
// out: run the distribution the wrapper already unpacked instead.
if build_dir.join("gradle/wrapper/gradle-wrapper.jar").is_file() {
return wrapper;
}
let home = setting_path(root, &g.user_home)
.or_else(|| std::env::var_os("GRADLE_USER_HOME").map(PathBuf::from))
.or_else(|| Some(crate::home_dir()?.join(".gradle")));
if let Some(gradle) = home.and_then(|home| unpacked_wrapper_distribution(build_dir, &home)) {
return gradle;
}
// Nothing to run instead: the wrapper's failure explains what is missing.
return wrapper;
}
pinned::pinned_install(build_dir, Tool::Gradle)
@@ -342,21 +330,6 @@ fn resolve_gradle_command(root: &Path, build_dir: &Path, s: &Settings, use_wrapp
.unwrap_or_else(|| name.into())
}
/// `bin/gradle` of the distribution `gradle/wrapper/gradle-wrapper.properties` names, once the
/// wrapper has unpacked it in `<gradle_user_home>/wrapper/dists` (and marked it complete).
fn unpacked_wrapper_distribution(build_dir: &Path, gradle_user_home: &Path) -> Option<PathBuf> {
let properties = std::fs::read_to_string(build_dir.join("gradle/wrapper/gradle-wrapper.properties")).ok()?;
let url = properties.lines().find_map(|line| line.trim().strip_prefix("distributionUrl="))?;
let zip = url.trim().replace("\\:", ":").rsplit('/').next()?.to_owned();
let name = zip.strip_suffix(".zip")?;
let gradle = if cfg!(windows) { "gradle.bat" } else { "gradle" };
// One directory per distribution URL hash, each holding the unpacked `gradle-<version>`.
let hashes = std::fs::read_dir(gradle_user_home.join("wrapper/dists").join(name)).ok()?;
hashes.flatten().map(|e| e.path()).filter(|dir| dir.join(format!("{zip}.ok")).is_file()).find_map(|dir| {
std::fs::read_dir(&dir).ok()?.flatten().map(|e| e.path().join("bin").join(gradle)).find(|p| p.is_file())
})
}
fn gradle_run_jdk<'a>(
release: Option<u32>,
configured: Option<&'a crate::java::Jdk>,
-31
Переглянути файл
@@ -1866,37 +1866,6 @@ fn max_java_picks_an_older_jdk() {
assert_eq!(free.env["JAVA_HOME"], j25.home.to_string_lossy());
}
/// #3086: `gradle-wrapper.jar` excluded by a `*.jar` rule in `.gitignore`: `gradlew` can't
/// start, so the distribution the wrapper already unpacked runs instead.
#[test]
fn gradle_wrapper_without_its_jar_runs_the_unpacked_distribution() {
use crate::apply::gradle_command;
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
let plain = if cfg!(windows) { "gradle.bat" } else { "gradle" };
let wrapper = root.join(if cfg!(windows) { "gradlew.bat" } else { "gradlew" });
std::fs::write(&wrapper, "").unwrap();
std::fs::create_dir_all(root.join("gradle/wrapper")).unwrap();
std::fs::write(
root.join("gradle/wrapper/gradle-wrapper.properties"),
"distributionUrl=https\\://services.gradle.org/distributions/gradle-4.10-bin.zip\n",
)
.unwrap();
let mut settings = Settings::default();
settings.languages.java.gradle.user_home = "user-home".into();
let hash = root.join("user-home/wrapper/dists/gradle-4.10-bin/7ddd1b3f");
let gradle = hash.join("gradle-4.10/bin").join(plain);
std::fs::create_dir_all(gradle.parent().unwrap()).unwrap();
std::fs::write(&gradle, "").unwrap();
// Not marked complete: possibly half unpacked.
assert_eq!(gradle_command(root, root, &settings), wrapper);
std::fs::write(hash.join("gradle-4.10-bin.zip.ok"), "").unwrap();
assert_eq!(gradle_command(root, root, &settings), gradle);
// With its jar the wrapper runs as usual.
std::fs::write(root.join("gradle/wrapper/gradle-wrapper.jar"), "").unwrap();
assert_eq!(gradle_command(root, root, &settings), wrapper);
}
#[test]
fn gradle_settings_precedence() {
use crate::apply::{gradle_command, gradle_env};
-3
Переглянути файл
@@ -281,9 +281,6 @@ impl Repo {
let commitish = arg(commitish, "revision")?;
let mut args: Vec<String> = vec!["worktree".into(), "add".into()];
if let Some(b) = new_branch.map(str::trim).filter(|b| !b.is_empty()) {
if crate::write::renamed_remote_start(self, b, &commitish) {
args.push("--no-track".into());
}
args.extend(["-b".into(), arg(b, "branch name")?]);
}
args.extend(["--".into(), path, commitish]);
+2 -27
Переглянути файл
@@ -800,41 +800,16 @@ pub(crate) fn create_branch(
let repo = r.gix()?;
resolve(&repo, s)?;
}
let no_track = start.is_some_and(|s| renamed_remote_start(r, name, s));
let mut args = match (checkout, overwrite) {
(true, false) => vec!["switch", "-c", name],
(true, true) => vec!["switch", "-C", name],
(false, false) => vec!["branch"],
(false, true) => vec!["branch", "--force"],
(false, false) => vec!["branch", "--", name],
(false, true) => vec!["branch", "--force", "--", name],
};
if no_track {
args.push("--no-track");
}
if !checkout {
args.extend(["--", name]);
}
args.extend(start);
run(r.root(), &args, None).map(|_| ())
}
/// Whether `start` is a remote-tracking branch with another name than the new branch
/// `name`. Git would make it the upstream, so pushing the new branch would go to the
/// start branch (`feature` from `origin/main` pushes to `main`); such a branch is left
/// without upstream and gets its own one on the first push. A remote branch under the
/// same name stays tracked.
pub(crate) fn renamed_remote_start(r: &Repo, name: &str, start: &str) -> bool {
let Ok(out) = cli::run_raw(r.root(), &["rev-parse", "--verify", "--quiet", "--symbolic-full-name", start], None)
else {
return false;
};
let full = out.stdout_str().trim().to_string();
let Some(rest) = full.strip_prefix("refs/remotes/").filter(|_| out.code == Some(0)) else { return false };
let Ok(repo) = r.gix() else { return false };
let names = repo.remote_names();
let branch = names.iter().find_map(|remote| rest.strip_prefix(&format!("{remote}/")));
branch.is_some_and(|b| b != name)
}
/// Undo Commit: moves the current branch back to the parent of `commit` (which must be
/// HEAD), keeping its changes staged. Returns the undone commit's message.
/// Edit Commit Message: writes `commit` again with `message`, and its descendants on top
+3 -29
Переглянути файл
@@ -984,41 +984,15 @@ fn branch_overwrite_preserves_the_ref_if_checkout_fails() {
}
#[test]
fn new_branch_from_remote_branch_tracks_it_only_under_the_same_name() {
let (fx, bare) = Fixture::with_origin();
fn new_branch_from_remote_branch_tracks_it() {
let (fx, _bare) = Fixture::with_origin();
fx.git(&["push", "-q", "origin", "main:release"]);
fx.git(&["fetch", "-q"]);
let repo = fx.repo();
let upstream = |name: &str| {
repo.branches().unwrap().into_iter().find(|b| b.name == name && !b.remote).and_then(|b| b.upstream)
};
repo.create_branch("release", Some("origin/release"), false).unwrap();
assert_eq!(upstream("release").as_deref(), Some("origin/release"));
// Another name: no upstream, whether switched to or not, created plainly or overwritten.
repo.create_branch("other", Some("origin/release"), false).unwrap();
assert_eq!(upstream("other"), None);
repo.create_branch_with_overwrite("other", Some("origin/main"), false, true).unwrap();
assert_eq!(upstream("other"), None);
repo.create_branch("my-release", Some("origin/release"), true).unwrap();
let info = repo.branch_info().unwrap();
assert_eq!(info.head.as_deref(), Some("my-release"));
assert_eq!(info.upstream, None);
// The first push then goes to a branch of its own name and tracks it.
fx.write("a.txt", "mine\n");
let tip = fx.commit_all("mine");
let (cancel, out) = quiet();
repo.push(false, true, &cancel, &out).unwrap();
assert_eq!(git_in(&bare, &["rev-parse", "my-release"]), tip);
assert_ne!(git_in(&bare, &["rev-parse", "release"]), tip);
assert_eq!(fx.git(&["config", "branch.my-release.merge"]), "refs/heads/my-release");
// New worktree on a new branch from a remote branch: the same rule.
let wt = fx.tmp.path().join("wt");
repo.add_worktree(&wt, "origin/release", Some("wt-branch")).unwrap();
assert_eq!(upstream("wt-branch"), None);
assert_eq!(info.upstream.as_deref(), Some("origin/release"));
}
#[test]
+1 -17
Переглянути файл
@@ -389,12 +389,6 @@ impl Documents {
self.apply_workspace_edit_inner(edit, true, &mut |_| Ok(()))
}
/// [`Self::apply_workspace_edit`] for an agent's edit (the MCP server's tools): undoable the
/// same way, announced as an agent's (`by_agent`) rather than as a refactoring.
pub fn apply_agent_workspace_edit(&self, edit: &WorkspaceEdit) -> IdeResult<()> {
self.apply_workspace_edit_as(edit, true, true, &mut |_| Ok(()))
}
/// File moves already own a combined move/reference undo record.
pub fn apply_file_move_edits(&self, edit: &WorkspaceEdit) -> IdeResult<()> {
self.apply_workspace_edit_inner(edit, false, &mut |_| Ok(()))
@@ -405,16 +399,6 @@ impl Documents {
edit: &WorkspaceEdit,
remember: bool,
before_operation: &mut dyn FnMut(usize) -> IdeResult<()>,
) -> IdeResult<()> {
self.apply_workspace_edit_as(edit, remember, false, before_operation)
}
fn apply_workspace_edit_as(
&self,
edit: &WorkspaceEdit,
remember: bool,
by_agent: bool,
before_operation: &mut dyn FnMut(usize) -> IdeResult<()>,
) -> IdeResult<()> {
let _operation = self.operations.lock();
if edit.files.is_empty() {
@@ -501,7 +485,7 @@ impl Documents {
});
}
history.prune(SystemTime::now(), MAX_HISTORY_BYTES, MAX_HISTORY_AGE);
self.sink.emit(IdeEvent::WorkspaceEditApplied { id, paths: affected, by_agent });
self.sink.emit(IdeEvent::WorkspaceEditApplied { id, paths: affected });
}
Ok(())
}
-2
Переглянути файл
@@ -122,8 +122,6 @@ Results appear in the **Services** tool window under the **Database** tab: an **
Right-click a result tab (or focus it and press `Shift+F10`) for **Close**, **Close Others**, **Close All**, **Rename Tab**, **Select Next Tab** and **Select Previous Tab**. They act on the result tabs only; **Output** stays. Renamed titles last while the result is open.
With focus on a result tab or inside a result, use `⇧⌘]` / `⇧⌘[` in the IntelliJ macOS keymap (`⌃→` / `⌃←` also work), or `Alt+→` / `Alt+←` in IntelliJ Windows/Linux. VS Code and Eclipse presets use their respective editor-tab navigation defaults. Switching focuses the destination result tab. Result navigation stays scoped to Results and is blocked while a menu or dialog is open. Customize database result shortcuts independently of editor shortcuts in **Settings › Keymap**.
Closing a selected result activates its left neighbor, or its right neighbor if there is no result on the left. When no results remain, **Output** is selected. Closing an inactive result keeps the current selection.
- **Table** or **Chart** view (bar or line, with X/Y columns and an aggregation).
+2 -5
Переглянути файл
@@ -18,17 +18,14 @@ Agent tasks started inside OpenIDEA (see [Agents](/en/guide/agents)) get the sam
</Step>
</Steps>
The server listens on `127.0.0.1` only, and every request must carry a bearer token. Requests from another origin or host are refused.
- **Port.** By default it listens on the same port, 26371, in every run (**Use a fixed port** and **Port**), so HTTP clients and port forwards (an SSH tunnel to another machine, say) keep working after a restart. When the port is in use or reserved, that run takes a free port and **Status** says why. Turn **Use a fixed port** off for a free port in every run.
- **Token.** By default the token changes each time OpenIDEA starts. Turn on **Keep the token** to keep one across runs, stored in OpenIDEA's application data for your account only; **Regenerate Token** replaces it, and clients configured with the old one stop working.
The server listens on `127.0.0.1` only, on a random port, and every request must carry a token that changes each time OpenIDEA starts. Requests from another origin or host are refused.
## Connect a client
The settings page has two buttons under **Client configuration**. Both copy an `mcpServers` entry in the JSON format most clients accept.
- **Copy Stdio Config** (recommended): the client starts OpenIDEA's executable with `--mcp-stdio`, which relays to the running IDE. It holds no token and keeps working after OpenIDEA restarts.
- **Copy HTTP Config**: the client connects to `http://127.0.0.1:<port>/mcp` with `Authorization: Bearer <token>`. It keeps working after OpenIDEA restarts only with a fixed port and a kept token; otherwise copy it again after each restart.
- **Copy HTTP Config**: the client connects to `http://127.0.0.1:<port>/mcp` with `Authorization: Bearer <token>`. It stops working when OpenIDEA restarts, because the port and token change.
The stdio configuration looks like this (the path is the one on your machine):
-2
Переглянути файл
@@ -122,8 +122,6 @@ SQL 补全基于已连接的架构:`FROM`/`JOIN` 后补全表(并根据外
右键点击结果标签页(或聚焦后按 `Shift+F10`),可使用 **关闭**、**关闭其他**、**全部关闭**、**重命名标签页**、**选择下一个标签页** 和 **选择上一个标签页**。这些操作只作用于结果标签页,**输出** 始终保留。重命名的标题在结果关闭前一直有效。
焦点位于结果标签页或结果内容中时,IntelliJ macOS 快捷键方案使用 `⇧⌘]` / `⇧⌘[`(也支持 `⌃→` / `⌃←`),IntelliJ Windows/Linux 使用 `Alt+→` / `Alt+←`。VS Code 和 Eclipse 方案分别使用各自默认的编辑器标签页导航快捷键。切换后焦点移到目标结果标签页。结果导航快捷键仅在结果区域中生效,菜单或对话框打开时不会切换结果。可在 **设置 › 快捷键** 中单独修改数据库结果快捷键,不影响编辑器快捷键。
关闭当前选中的结果标签页时,优先选中左侧相邻的结果;没有左侧结果时,选中右侧相邻结果。没有剩余结果时,选中 **输出**。关闭未选中的结果不会改变当前选择。
- **表** 或 **图表** 视图(柱状图或折线图,可选 X/Y 列和聚合方式)。
+2 -5
Переглянути файл
@@ -17,17 +17,14 @@ OpenIDEA 内置了一个 [Model Context Protocol](https://modelcontextprotocol.i
</Step>
</Steps>
服务器只监听 `127.0.0.1`,每个请求都必须带上访问令牌。来自其他 Origin 或 Host 的请求会被拒绝。
- **端口。** 默认每次运行都监听同一个端口 26371(**使用固定端口** 和 **端口**),这样 OpenIDEA 重启后 HTTP 客户端和端口转发(例如到另一台机器的 SSH 隧道)仍然有效。端口被占用或被系统保留时,本次运行改用一个空闲端口,**状态** 中会说明原因。关闭 **使用固定端口** 则每次运行使用一个空闲端口。
- **令牌。** 默认每次启动 OpenIDEA 都会换一个新令牌。打开 **保留令牌** 后会在多次运行间保留同一个令牌,保存在 OpenIDEA 的应用数据目录中,只有你的账户可读;**重新生成令牌** 会替换它,使用旧令牌配置的客户端随之失效。
服务器只监听 `127.0.0.1` 上的一个随机端口,每个请求都必须带上令牌,令牌在每次启动 OpenIDEA 时都会变化。来自其他 Origin 或 Host 的请求会被拒绝。
## 连接客户端
设置页面的 **客户端配置** 下有两个按钮,都会复制一段大多数客户端都能识别的 `mcpServers` JSON 配置。
- **复制 Stdio 配置**(推荐):客户端以 `--mcp-stdio` 参数启动 OpenIDEA 的可执行文件,由它转发给正在运行的 IDE。配置里没有令牌,OpenIDEA 重启后依然可用。
- **复制 HTTP 配置**:客户端带着 `Authorization: Bearer <token>` 连接 `http://127.0.0.1:<port>/mcp`。只有同时使用固定端口并保留令牌时,OpenIDEA 重启后这份配置才继续有效;否则每次重启后都要重新复制。
- **复制 HTTP 配置**:客户端带着 `Authorization: Bearer <token>` 连接 `http://127.0.0.1:<port>/mcp`。由于端口和令牌会变,OpenIDEA 重启后这份配置就失效了。
stdio 配置大致如下(路径以你机器上的为准):
+6 -63
Переглянути файл
@@ -1,5 +1,5 @@
import type { Page } from "@playwright/test";
import { expect, openFromTree, test } from "./fixtures";
import { expect, test } from "./fixtures";
const edgeTitle = "Result 3 — a long query result at the edge of the Services pane";
const bindings = { "alpha-console.sql": "alpha", "beta-console.sql": "beta" };
@@ -64,9 +64,7 @@ function menu(page: Page) {
async function choose(page: Page, title: string, command: string) {
await tab(page, title).click({ button: "right" });
await menu(page)
.getByRole("menuitem", { name: command.startsWith("Select ") ? new RegExp(`^${command}`) : command, exact: true })
.click();
await menu(page).getByRole("menuitem", { name: command, exact: true }).click();
await expect(menu(page)).toHaveCount(0);
}
@@ -93,8 +91,8 @@ test("result context menu fits the viewport, responds to hover and keyboard, and
"Close Others",
"Close All",
"Rename Tab",
"Select Next Tab⇧⌘]",
"Select Previous Tab⇧⌘[",
"Select Next Tab",
"Select Previous Tab",
]);
await expect(popup.getByRole("separator")).toHaveCount(2);
await selected(page, "Result 2", "beta rows");
@@ -142,7 +140,7 @@ test("result context menu fits the viewport, responds to hover and keyboard, and
await page.keyboard.press("ArrowUp");
await expect(popup.getByRole("menuitem", { name: "Close", exact: true })).toBeFocused();
await page.keyboard.press("ArrowUp");
await expect(popup.getByRole("menuitem", { name: /^Select Previous Tab/ })).toBeFocused();
await expect(popup.getByRole("menuitem", { name: "Select Previous Tab", exact: true })).toBeFocused();
await page.keyboard.press("Enter");
await expect(popup).toHaveCount(0);
await selected(page, "Result 1", "alpha rows");
@@ -209,9 +207,7 @@ for (const [theme, label] of [
await expect(surface).toHaveCSS("background-color", idle);
await expect(otherSurface).toHaveCSS("background-color", hovered);
await selected(page, "Result 2", "beta rows");
await menu(page)
.getByRole("menuitem", { name: /^Select Previous Tab/ })
.click();
await menu(page).getByRole("menuitem", { name: "Select Previous Tab", exact: true }).click();
await expect(menu(page)).toHaveCount(0);
await page.mouse.move(0, 0);
await expect(otherSurface).toHaveCSS("background-color", idle);
@@ -270,59 +266,6 @@ test("renames the clicked inactive result without changing its rows and navigate
await selected(page, "Result 3", "third rows");
});
test("default tab shortcuts stay in results across repeated tab and grid switches, and remain editor shortcuts elsewhere", async ({
workbench: page,
}) => {
await openFromTree(page, "build.gradle.kts");
await openFromTree(page, "settings.gradle.kts");
const editors = page.getByRole("tablist", { name: "Editor tabs", exact: true });
const build = editors.getByRole("tab", { name: "build.gradle.kts", exact: true });
const settings = editors.getByRole("tab", { name: "settings.gradle.kts", exact: true });
await seedResults(page);
await tab(page, "Result 1").focus();
for (const [shortcut, title, value] of [
["Meta+Shift+BracketRight", "Result 3", "third rows"],
["Meta+Shift+BracketRight", "Output"],
["Meta+Shift+BracketRight", "Result 1", "alpha rows"],
["Meta+Shift+BracketLeft", "Output"],
["Meta+Shift+BracketLeft", "Result 3", "third rows"],
]) {
await page.keyboard.press(shortcut!);
await selected(page, title!, value);
await expect(settings).toHaveAttribute("aria-selected", "true");
}
// The grid is replaced on a tab switch; the second press must still belong to results.
await page.getByRole("gridcell", { name: "third rows", exact: true }).click();
await page.keyboard.press("Meta+Shift+BracketRight");
await selected(page, "Output");
await page.keyboard.press("Meta+Shift+BracketRight");
await selected(page, "Result 1", "alpha rows");
await page.getByRole("gridcell", { name: "alpha rows", exact: true }).click();
await page.keyboard.press("Meta+Shift+BracketRight");
await selected(page, "Result 2", "beta rows");
await page.keyboard.press("Meta+Shift+BracketRight");
await selected(page, "Result 3", "third rows");
await expect(settings).toHaveAttribute("aria-selected", "true");
await settings.click();
await page.locator(".cm-content[contenteditable=true]").first().click();
await page.keyboard.press("Meta+Shift+BracketRight");
await expect(build).toHaveAttribute("aria-selected", "true");
await selected(page, "Result 3", "third rows");
await page.keyboard.press("Meta+Shift+BracketLeft");
await expect(settings).toHaveAttribute("aria-selected", "true");
await selected(page, "Result 3", "third rows");
await tab(page, "Result 1").click({ button: "right" });
await page.keyboard.press("Meta+Shift+BracketRight");
await page.keyboard.press("Meta+Shift+BracketLeft");
await selected(page, "Result 3", "third rows");
await expect(menu(page)).toBeVisible();
await page.keyboard.press("Escape");
});
test("rename owns deletion and Cmd+Enter without editing the previously focused query", async ({ workbench: page }) => {
await seedResults(page);
await page.evaluate(async () => {
+6 -73
Переглянути файл
@@ -15,92 +15,45 @@ use tauri::{State, Window};
#[derive(Default)]
pub struct McpService {
server: Mutex<Option<ide_mcp::McpServer>>,
/// The port and token settings the running server was started with.
running_with: Mutex<Option<Listen>>,
error: Mutex<Option<String>>,
}
/// What the port and token settings ask the server for.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Listen {
/// `mcpServer.port` with `mcpServer.fixedPort`; otherwise a free port.
port: Option<u16>,
fixed_token: bool,
}
/// Starts, stops or restarts the server to match the global `mcpServer` settings: `enabled`,
/// and the port and token it listens with.
/// Starts or stops the server to match the global `mcpServer.enabled`.
pub fn apply(state: &AppState) {
let settings = state.global_settings.effective().mcp_server;
let enabled = state.global_settings.effective().mcp_server.enabled;
let mut server = state.mcp.server.lock();
if !settings.enabled {
if !enabled {
if let Some(running) = server.take() {
running.stop();
}
*state.mcp.running_with.lock() = None;
ide_agent::set_mcp_executable(None);
state.host.set_mcp_executable(None);
*state.mcp.error.lock() = None;
return;
}
let wanted = Listen {
port: settings.fixed_port.then_some(settings.port).filter(|p| *p != 0),
fixed_token: settings.fixed_token,
};
if server.is_some() && *state.mcp.running_with.lock() == Some(wanted) {
if server.is_some() {
return;
}
// Another port or token: clients connect anew.
if let Some(running) = server.take() {
running.stop();
if let Some(port) = wanted.port {
wait_until_free(port);
}
}
let token = if wanted.fixed_token {
match ide_mcp::kept_token(&ide_mcp::token_path(&state.data_dir)) {
Ok(token) => Some(token),
Err(e) => {
tracing::warn!("MCP server: cannot keep the token ({e}); using a new one for this run");
None
}
}
} else {
None
};
let discovery = ide_mcp::discovery_path(&state.data_dir);
match ide_mcp::McpServer::start_with(
match ide_mcp::McpServer::start(
Arc::new(ide_host::mcp::Registry::new(state.host.clone())),
Some(discovery),
&state.host.runtime,
ide_mcp::ServerOptions { port: wanted.port, token },
) {
Ok(started) => {
let exe = std::env::current_exe().unwrap_or_default();
state.host.set_mcp_executable(Some(exe.clone()));
ide_agent::set_mcp_executable(Some(exe));
*server = Some(started);
*state.mcp.running_with.lock() = Some(wanted);
*state.mcp.error.lock() = None;
}
Err(e) => {
tracing::warn!("MCP server: {e}");
*state.mcp.running_with.lock() = None;
*state.mcp.error.lock() = Some(e.to_string());
}
}
}
/// Waits briefly for a stopped server's port to close, so the restart gets it again.
fn wait_until_free(port: u16) {
for _ in 0..100 {
if std::net::TcpListener::bind(("127.0.0.1", port)).is_ok() {
return;
}
std::thread::sleep(std::time::Duration::from_millis(20));
}
}
/// Stops the server on exit (its discovery file goes with it).
pub fn stop(state: &AppState) {
state.host.set_mcp_executable(None);
@@ -108,7 +61,6 @@ pub fn stop(state: &AppState) {
if let Some(server) = state.mcp.server.lock().take() {
server.stop();
}
*state.mcp.running_with.lock() = None;
}
/// What Settings › Agents › MCP Server shows.
@@ -119,14 +71,11 @@ pub struct McpServerStatus {
/// Why it isn't running though turned on.
pub error: Option<String>,
pub port: Option<u16>,
/// Why the fixed port (`mcpServer.port`) isn't the one listened on: it was in use or
/// reserved, so a free port was taken for this run.
pub port_unavailable: Option<String>,
/// The window's local project, which the URL and command below are for.
pub project: Option<IpcPath>,
/// `http://127.0.0.1:<port>/mcp?project=<root>`.
pub url: Option<String>,
/// Bearer token of `url` (changes with every run unless `mcpServer.fixedToken` is on).
/// Bearer token of `url` (changes with every run).
pub token: Option<String>,
/// The stdio bridge: this executable and its arguments.
pub stdio_command: Vec<String>,
@@ -142,7 +91,6 @@ pub fn mcp_server_status(window: Window, state: State<'_, AppState>) -> IdeResul
running: server.is_some(),
error: state.mcp.error.lock().clone(),
port: server.as_ref().map(|s| s.port()),
port_unavailable: server.as_ref().and_then(|s| s.port_unavailable().map(str::to_owned)),
url: server.as_ref().zip(root.as_ref()).map(|(s, r)| s.url(r)),
token: server.as_ref().map(|s| s.token().to_owned()),
stdio_command: root.as_ref().map(|r| ide_mcp::stdio_command(&exe, r)).unwrap_or_default(),
@@ -150,21 +98,6 @@ pub fn mcp_server_status(window: Window, state: State<'_, AppState>) -> IdeResul
})
}
/// Settings › Agents › MCP Server › Regenerate Token: forgets the kept token, and restarts the
/// server with a new one. Clients configured with the old token stop working.
#[tauri::command]
#[specta::specta]
pub fn mcp_regenerate_token(state: State<'_, AppState>) -> IdeResult<()> {
match std::fs::remove_file(ide_mcp::token_path(&state.data_dir)) {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(e.into()),
}
*state.mcp.running_with.lock() = None;
apply(&state);
Ok(())
}
#[tauri::command]
#[specta::specta]
pub fn mcp_set_open_editors(window: Window, state: State<'_, AppState>, paths: Vec<IpcPath>) -> IdeResult<()> {
-1
Переглянути файл
@@ -75,7 +75,6 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
mcp::mcp_ui_ready,
mcp::mcp_respond,
mcp::mcp_agent_run_closed,
mcp::mcp_regenerate_token,
mcp::mcp_server_status,
mcp::mcp_set_open_editors,
mcp::mcp_set_focused_editor,
+1 -3
Переглянути файл
@@ -63,9 +63,7 @@ impl EventSink for TauriSink {
) {
flash_taskbar_unless_focused(&self.app);
}
// A confirmation waits for the user: bring the window up. Other requests (an agent's
// run, opening a file) need nothing from the user and leave the focus where it is.
if matches!(&event, IdeEvent::McpRequest { request: ide_core::event::McpUiRequest::Confirm { .. }, .. })
if matches!(&event, IdeEvent::McpRequest { .. })
&& let Some(label) = self.window.clone()
{
let app = self.app.clone();
+2 -29
Переглянути файл
@@ -19,11 +19,6 @@ export const commands = {
mcpRespond: (id: number, allow: boolean, error: string | null) => typedError<null, IdeError>(__TAURI_INVOKE("mcp_respond", { id, allow, error })),
/** The user closed the Run tool window tab of an agent command (`run_command`). */
mcpAgentRunClosed: (name: string) => typedError<null, IdeError>(__TAURI_INVOKE("mcp_agent_run_closed", { name })),
/**
* Settings › Agents › MCP Server › Regenerate Token: forgets the kept token, and restarts the
* server with a new one. Clients configured with the old token stop working.
*/
mcpRegenerateToken: () => typedError<null, IdeError>(__TAURI_INVOKE("mcp_regenerate_token")),
mcpServerStatus: () => typedError<McpServerStatus, IdeError>(__TAURI_INVOKE("mcp_server_status")),
mcpSetOpenEditors: (paths: IpcPath[]) => typedError<null, IdeError>(__TAURI_INVOKE("mcp_set_open_editors", { paths })),
mcpSetFocusedEditor: (editor: {
@@ -5864,12 +5859,7 @@ workspaceEdit?: boolean } |
/** A document's dirty flag changed (saved / modified externally). */
{ type: "docDirty"; doc: DocId; dirty: boolean } |
/** A complete workspace edit can be undone as one operation. */
{ type: "workspaceEditApplied"; id: number; paths: IpcPath[];
/**
* Made by an agent through the MCP server's tools: undoable like a refactoring, but
* not announced as one.
*/
byAgent: boolean } |
{ type: "workspaceEditApplied"; id: number; paths: IpcPath[] } |
/**
* An open document's language changed (Settings › File Types, Override File
* Type), or its UI mode (a framework's root marker appeared or went).
@@ -7207,18 +7197,6 @@ export type McpServerSettings = {
agentTabLimit?: number,
/** Archived agent tabs kept; older ones are closed. */
agentArchiveLimit?: number,
/**
* Listen on [`Self::port`] in every run, rather than a free port each time, so HTTP clients and
* port forwards keep working after a restart.
*/
fixedPort?: boolean,
/** The port of [`Self::fixed_port`]. */
port?: number,
/**
* Keep the bearer token across runs (in the app data, readable by this user only) rather than
* make a new one each run.
*/
fixedToken?: boolean,
};
/** What Settings › Agents › MCP Server shows. */
@@ -7227,16 +7205,11 @@ export type McpServerStatus = {
/** Why it isn't running though turned on. */
error: string | null,
port: number | null,
/**
* Why the fixed port (`mcpServer.port`) isn't the one listened on: it was in use or
* reserved, so a free port was taken for this run.
*/
portUnavailable: string | null,
/** The window's local project, which the URL and command below are for. */
project: IpcPath | null,
/** `http://127.0.0.1:<port>/mcp?project=<root>`. */
url: string | null,
/** Bearer token of `url` (changes with every run unless `mcpServer.fixedToken` is on). */
/** Bearer token of `url` (changes with every run). */
token: string | null,
/** The stdio bridge: this executable and its arguments. */
stdioCommand: string[],
+2 -7
Переглянути файл
@@ -57,12 +57,7 @@ async function replace(text: string) {
}
async function rename() {
await replace("new");
emitLocalIdeEvent({
type: "workspaceEditApplied",
id: 9,
paths: ["/p/A.java", "/p/B.java", "/p/closed.java"],
byAgent: false,
});
emitLocalIdeEvent({ type: "workspaceEditApplied", id: 9, paths: ["/p/A.java", "/p/B.java", "/p/closed.java"] });
}
function historyStep(slot: EditorSlot, forward = false) {
return (forward ? redo : undo)({
@@ -188,7 +183,7 @@ it("rebuilds multiple redo markers in order when a closed file opens", async ()
const a = await open("/p/A.java");
await rename();
await replace("alt");
emitLocalIdeEvent({ type: "workspaceEditApplied", id: 10, paths: ["/p/A.java", "/p/B.java"], byAgent: true });
emitLocalIdeEvent({ type: "workspaceEditApplied", id: 10, paths: ["/p/A.java", "/p/B.java"] });
commands.undoWorkspaceEdit.mockImplementation(async (id: number) => {
await replace(id === 10 ? "new" : "old");
return { status: "ok", data: null };
+3 -8
Переглянути файл
@@ -35,7 +35,7 @@ it("waits for pending typing before undoing the entire backend transaction", asy
release = resolve;
}),
);
emitLocalIdeEvent({ type: "workspaceEditApplied", id: 17, paths: [], byAgent: false });
emitLocalIdeEvent({ type: "workspaceEditApplied", id: 17, paths: [] });
const action = notices[0]!.actions![0]!;
expect(action.label).toBe("Undo");
const pending = action.run();
@@ -47,13 +47,13 @@ it("waits for pending typing before undoing the entire backend transaction", asy
it("reports a refused undo instead of discarding newer work", async () => {
mocks.undo.mockRejectedValue(new Error("a.txt changed"));
emitLocalIdeEvent({ type: "workspaceEditApplied", id: 18, paths: [], byAgent: false });
emitLocalIdeEvent({ type: "workspaceEditApplied", id: 18, paths: [] });
await notices[0]!.actions![0]!.run();
expect(notices[1]).toMatchObject({ level: "error", title: "Cannot undo refactoring", body: "a.txt changed" });
});
it("does not apply an old notification's id to a different project", async () => {
emitLocalIdeEvent({ type: "workspaceEditApplied", id: 19, paths: [], byAgent: false });
emitLocalIdeEvent({ type: "workspaceEditApplied", id: 19, paths: [] });
const previous = useProject.getState().project;
useProject.setState({ project: { ...previous, root: "/different-project" } as NonNullable<typeof previous> });
try {
@@ -64,8 +64,3 @@ it("does not apply an old notification's id to a different project", async () =>
useProject.setState({ project: previous });
}
});
it("does not announce an agent's edit as a refactoring", () => {
emitLocalIdeEvent({ type: "workspaceEditApplied", id: 20, paths: [], byAgent: true });
expect(notices).toEqual([]);
});
+2 -6
Переглянути файл
@@ -3,10 +3,7 @@ import { onIdeEvent } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { notifications } from "@/workbench/contributions";
/**
* The notification follows the same history state as editor Undo/Redo. An agent's edits (the MCP
* server's tools) stay undoable from the editor but are not announced: an agent makes many.
*/
/** The notification follows the same history state as editor Undo/Redo. */
export function installWorkspaceEditUndo(): () => void {
let current: { id: number; project: ReturnType<typeof useProject.getState>["project"]; undone: boolean } | null =
null;
@@ -41,8 +38,7 @@ export function installWorkspaceEditUndo(): () => void {
],
});
};
const stopApplied = onIdeEvent("workspaceEditApplied", ({ id, byAgent }) => {
if (byAgent) return;
const stopApplied = onIdeEvent("workspaceEditApplied", ({ id }) => {
current = { id, project: useProject.getState().project, undone: false };
show();
});
+5 -11
Переглянути файл
@@ -665,16 +665,7 @@ export function ResultsView() {
const results = useDatabase((s) => s.results);
const active = useDatabase((s) => s.activeResult);
const hasOutput = useDatabase((s) => s.output.length > 0);
const root = useRef<HTMLDivElement>(null);
useEffect(() => {
const syncFocus = () => setContext("dbResultsFocus", !!root.current?.contains(document.activeElement));
document.addEventListener("focusin", syncFocus);
syncFocus();
return () => {
document.removeEventListener("focusin", syncFocus);
setContext("dbResultsFocus", false);
};
}, []);
useEffect(() => () => setContext("dbResultsFocus", false), []);
const tabMenu = (id: string, e: MouseEvent) => {
e.preventDefault();
const rect = e.currentTarget.getBoundingClientRect();
@@ -691,8 +682,11 @@ export function ResultsView() {
const tab = results.find((r) => r.id === active);
return (
<div
ref={root}
className={styles.view}
onFocusCapture={() => setContext("dbResultsFocus", true)}
onBlurCapture={(e) => {
if (!e.currentTarget.contains(e.relatedTarget)) setContext("dbResultsFocus", false);
}}
onKeyDown={(e) => {
if (e.key !== "ContextMenu" && !(e.shiftKey && e.key === "F10")) return;
const tab = (e.target as Element).closest<HTMLElement>('[role="tab"]');
+25 -84
Переглянути файл
@@ -1,6 +1,6 @@
import { act, cleanup, fireEvent, render, screen, within } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { installKeyboardDispatcher, normalizeBinding, PRESETS, useKeymap } from "@/platform/keymap";
import { installKeyboardDispatcher, useKeymap } from "@/platform/keymap";
import { ContextMenuHost, hideContextMenu } from "@/ui";
import { InputDialogsHost } from "@/workbench/inputDialogs";
import { ResultsView } from "./ResultsView";
@@ -113,7 +113,7 @@ function openMenu(name: string) {
async function choose(name: string) {
await act(async () => {
fireEvent.click(screen.getByRole("menuitem", { name: name.startsWith("Select ") ? new RegExp(`^${name}`) : name }));
fireEvent.click(screen.getByRole("menuitem", { name }));
});
}
@@ -139,6 +139,29 @@ function expectConsoleStateUnchanged(before: typeof initialDatabase) {
}
describe("database result tab context menu", () => {
it("offers only result actions, in order with the two group separators", async () => {
await show();
const menu = openMenu("Orders");
expect(
within(menu)
.getAllByRole("menuitem")
.map((item) => item.textContent),
).toEqual(["Close", "Close Others", "Close All", "Rename Tab", "Select Next Tab", "Select Previous Tab"]);
expect(Array.from(menu.children).map((item) => item.getAttribute("role"))).toEqual([
"menuitem",
"menuitem",
"menuitem",
"separator",
"menuitem",
"separator",
"menuitem",
"menuitem",
]);
expect(within(menu).queryByText(/pin|layout/i)).not.toBeInTheDocument();
expectSelected("Customer count");
expect(screen.getByRole("gridcell", { name: "count-row" })).toBeInTheDocument();
});
it("closes the clicked inactive result without changing the selected result", async () => {
await show();
openMenu("Orders");
@@ -363,88 +386,6 @@ describe("database result tab context menu", () => {
expectSelected("Customer count");
});
it.each(Object.entries(PRESETS))(
"navigates results using every default tab shortcut in %s",
async (preset, keymap) => {
useKeymap.setState({ preset });
await show();
const uninstall = installKeyboardDispatcher(window);
const press = async (binding: string) => {
const parts = normalizeBinding(binding).split("+");
const key = parts.at(-1)!;
const codes: Record<string, string> = {
Right: "ArrowRight",
Left: "ArrowLeft",
"[": "BracketLeft",
"]": "BracketRight",
};
await act(async () => {
fireEvent.keyDown(document.activeElement!, {
key,
code: codes[key] ?? key,
metaKey: parts.includes("Meta"),
ctrlKey: parts.includes("Ctrl"),
altKey: parts.includes("Alt"),
shiftKey: parts.includes("Shift"),
});
});
};
try {
for (const [index, next] of keymap["editor.nextTab"]!.entries()) {
const previous = keymap["editor.prevTab"]![index]!;
act(() => screen.getByRole("button", { name: "Outside results" }).focus());
await press(next);
await press(previous);
expectSelected("Customer count");
act(() => tab("Orders").focus());
await press(next);
expectOutput();
await press(next);
expectSelected("Customers");
expect(screen.getByRole("gridcell", { name: "customer-row" })).toBeInTheDocument();
await press(previous);
expectOutput();
await press(previous);
expectSelected("Customer count");
openMenu("Customers");
await press(next);
await press(previous);
expectSelected("Customer count");
fireEvent.keyDown(document.activeElement!, { key: "Escape", code: "Escape" });
}
expect(useDatabase.getState().results).toBe(seeded);
} finally {
uninstall();
}
},
);
it("releases result shortcuts after switching from a grid and moving focus outside", async () => {
await show();
const uninstall = installKeyboardDispatcher(window);
const next = async () => {
await act(async () => {
fireEvent.keyDown(document.activeElement!, {
key: "}",
code: "BracketRight",
metaKey: true,
shiftKey: true,
});
});
};
try {
act(() => screen.getByRole("grid").focus());
await next();
expectOutput();
expect(tab("Output")).toHaveFocus();
act(() => screen.getByRole("button", { name: "Outside results" }).focus());
await next();
expectOutput();
} finally {
uninstall();
}
});
it("dispatches assigned result shortcuts only while results have focus, relative to the active tab", async () => {
useKeymap.setState({
overrides: {
+3 -11
Переглянути файл
@@ -17,19 +17,11 @@ function closeOthers(id: number) {
for (const tab of useDatabase.getState().results) if (tab.id !== id) closeResult(tab.id);
}
function cycle(direction: 1 | -1, focus: boolean) {
function cycle(direction: 1 | -1) {
const { results, activeResult } = useDatabase.getState();
const ids = [OUTPUT_TAB, ...results.map((r) => r.id)];
const index = ids.indexOf(activeResult ?? OUTPUT_TAB);
if (index < 0) return;
const next = ids[(index + direction + ids.length) % ids.length]!;
if (focus) {
const button = document.getElementById(`db-results-tab-${next}`);
button?.focus();
// An inline editor can hand focus back to its grid when it blurs.
if (document.activeElement !== button) button?.focus();
}
useDatabase.setState({ activeResult: next });
if (index >= 0) useDatabase.setState({ activeResult: ids[(index + direction + ids.length) % ids.length]! });
}
export function registerResultTabActions(): () => void {
@@ -81,7 +73,7 @@ export function registerResultTabActions(): () => void {
category: "Database",
keyWhen: "dbResultsFocus && !popupOpen",
enabled: (c: ActionContext) => target(c) !== null && useDatabase.getState().results.length > 0,
run: ({ ctx }: ActionContext) => cycle(direction, !!ctx.dbResultsFocus),
run: () => cycle(direction),
})),
]);
}
-43
Переглянути файл
@@ -6,7 +6,6 @@ import { installCellActions } from "./cellActions";
import { getContext } from "@/platform/context";
import { ResultsView } from "./ResultsView";
import { executeConsole, useDatabase, type ResultTab } from "./store";
import { registerResultTabActions } from "./resultTabActions";
import { activeTableEditor, installTableEditorFocus } from "./tableEditorFocus";
const backend = vi.hoisted(() => ({
@@ -158,48 +157,6 @@ describe("editable result grid", () => {
expect(useDatabase.getState().results[0]!.id).toBe(tab.id);
});
it("keeps navigation focus after leaving an inline cell editor and releases it outside Results", async () => {
const first = show("SELECT * FROM users", [{ name: "id" }, { name: "name" }], [["1", "Ann"]]);
useDatabase.setState({ results: [first, { ...first, id: nextId++, title: "Result 2" }] });
const keymap = useKeymap.getState();
useKeymap.setState({ preset: "intellij-macos", overrides: {}, extensions: {} });
const dispose = registerResultTabActions();
const uninstall = installKeyboardDispatcher(window);
try {
await act(async () =>
render(
<>
<ResultsView />
<button>Outside results</button>
</>,
),
);
fireEvent.doubleClick(await screen.findByRole("gridcell", { name: "Ann" }));
const input = screen.getByRole("textbox", { name: "Edit name" });
fireEvent.change(input, { target: { value: "Bob" } });
await act(async () => {
fireEvent.keyDown(input, { key: "}", code: "BracketRight", metaKey: true, shiftKey: true });
});
expect(screen.getByRole("tab", { name: "Result 2" })).toHaveAttribute("aria-selected", "true");
expect(screen.getByRole("tab", { name: "Result 2" })).toHaveFocus();
await act(async () => {
fireEvent.keyDown(document.activeElement!, { key: "{", code: "BracketLeft", metaKey: true, shiftKey: true });
});
expect(screen.getByRole("tab", { name: "Result 1" })).toHaveAttribute("aria-selected", "true");
expect(screen.getByRole("tab", { name: "Result 1" })).toHaveFocus();
act(() => screen.getByRole("button", { name: "Outside results" }).focus());
await act(async () => {
fireEvent.keyDown(document.activeElement!, { key: "}", code: "BracketRight", metaKey: true, shiftKey: true });
});
expect(screen.getByRole("tab", { name: "Result 1" })).toHaveAttribute("aria-selected", "true");
expect(backend.applyEdits).not.toHaveBeenCalled();
} finally {
uninstall();
dispose();
useKeymap.setState(keymap, true);
}
});
it.each(["s2", ""])("records the selected schema or connection default: %s", async (schema) => {
show("SELECT * FROM users", [{ name: "id" }, { name: "name" }], [["1", "Ann"]]);
useDatabase.setState({ consoles: { "console.sql": "pg" }, consoleSchemas: { "console.sql": schema } });
-8
Переглянути файл
@@ -7,7 +7,6 @@ const status: McpServerStatus = {
running: true,
error: null,
port: 1234,
portUnavailable: null,
project: "/p",
url: "http://127.0.0.1:1234/mcp?project=/p",
token: "secret",
@@ -21,13 +20,6 @@ describe("MCP server settings", () => {
expect(validateSettings({ mcpServer: { enabled: true } }).mcpServer.enabled).toBe(true);
expect(MCP_SERVER_PAGE.projectScope).not.toBe(true);
});
it("keeps a fixed port by default and a new token in every run", () => {
expect(DEFAULT_SETTINGS.mcpServer).toMatchObject({ fixedPort: true, port: 26371, fixedToken: false });
const custom = validateSettings({ mcpServer: { fixedPort: false, port: 7000, fixedToken: true } }).mcpServer;
expect(custom).toMatchObject({ fixedPort: false, port: 7000, fixedToken: true });
expect(validateSettings({ mcpServer: { port: 70000 } }).mcpServer.port).toBe(65535);
expect(validateSettings({ mcpServer: { port: "x" } }).mcpServer.port).toBe(26371);
});
it("copies a reusable stdio configuration without the token", () => {
const config = stdioConfig(status)!;
expect(JSON.parse(config).mcpServers.openidea).toEqual({
+1 -21
Переглянути файл
@@ -40,10 +40,6 @@ import {
} from "./behaviorSchema";
import { isThemeChoiceId, type ThemeChoiceId } from "@/platform/themes";
/** Agents › IDE MCP Server › Port: its default (`ide-core::settings::DEFAULT_MCP_PORT`) and range. */
export const DEFAULT_MCP_PORT = 26371;
export const MCP_PORT_LIMITS = { min: 1, max: 65535 };
/** A built-in theme, a plugin's (`plugin:<id>/<theme>`) or the legacy `"system"`. */
export type ThemeId = ThemeChoiceId | "system";
@@ -116,17 +112,7 @@ export interface ValidSettings extends WorkflowSettings {
/** Tools › Agents › Chat: the meters in an agent task's header. */
agents: Required<AgentSettings>;
/** Agents › IDE MCP Server (global). */
mcpServer: {
enabled: boolean;
runWithoutConfirmation: boolean;
agentTabLimit: number;
agentArchiveLimit: number;
/** Listen on `port` in every run rather than a free port each time. */
fixedPort: boolean;
port: number;
/** Keep the bearer token across runs rather than make a new one each run. */
fixedToken: boolean;
};
mcpServer: { enabled: boolean; runWithoutConfirmation: boolean; agentTabLimit: number; agentArchiveLimit: number };
}
/** One `languageServers.<name>` entry; every field optional, like in settings.toml. */
@@ -222,9 +208,6 @@ export const DEFAULT_SETTINGS: ValidSettings = {
runWithoutConfirmation: false,
agentTabLimit: DEFAULT_AGENT_RUNS.tabLimit,
agentArchiveLimit: DEFAULT_AGENT_RUNS.archiveLimit,
fixedPort: true,
port: DEFAULT_MCP_PORT,
fixedToken: false,
},
...DEFAULT_WORKFLOW,
};
@@ -400,9 +383,6 @@ export function validateSettings(raw: Settings | unknown): ValidSettings {
runWithoutConfirmation: bool(obj(root.mcpServer).runWithoutConfirmation, d.mcpServer.runWithoutConfirmation),
agentTabLimit: validateAgentRuns(root.mcpServer).tabLimit,
agentArchiveLimit: validateAgentRuns(root.mcpServer).archiveLimit,
fixedPort: bool(obj(root.mcpServer).fixedPort, d.mcpServer.fixedPort),
port: num(obj(root.mcpServer).port, d.mcpServer.port, MCP_PORT_LIMITS, true),
fixedToken: bool(obj(root.mcpServer).fixedToken, d.mcpServer.fixedToken),
},
...validateWorkflow(root),
};
+8 -43
Переглянути файл
@@ -6,8 +6,6 @@ import { WORKFLOW_LIMITS } from "@/platform/workflowSettings";
import { useTx } from "@/platform/i18n";
import { Button, Input, T, copyText } from "@/ui";
import { Row } from "../components/Form";
import { useSetting } from "../components/context";
import { MCP_PORT_LIMITS } from "../model/schema";
import type { PageSpec } from "./spec";
import styles from "./McpServer.module.css";
@@ -25,10 +23,9 @@ export function stdioConfig(status: McpServerStatus): string | null {
return JSON.stringify({ mcpServers: { openidea: { type: "stdio", command, args } } }, null, 2);
}
function useStatus(): [McpServerStatus | null, () => void] {
function useStatus(): McpServerStatus | null {
const root = useProject((s) => s.project?.root);
const [status, setStatus] = useState<McpServerStatus | null>(null);
const [loads, setLoads] = useState(0);
useEffect(() => {
if (!isTauri()) return;
let live = true;
@@ -46,14 +43,13 @@ function useStatus(): [McpServerStatus | null, () => void] {
live = false;
off();
};
}, [root, loads]);
return [status, () => setLoads((n) => n + 1)];
}, [root]);
return status;
}
function McpServerEndpoint() {
const tx = useTx();
const [status, reload] = useStatus();
const [fixedToken] = useSetting<boolean>("mcpServer.fixedToken");
const status = useStatus();
const [copied, setCopied] = useState<string | null>(null);
useEffect(() => {
if (!copied) return;
@@ -65,13 +61,9 @@ function McpServerEndpoint() {
if (!text) return;
void copyText(text).then(() => setCopied(which));
};
const regenerate = () => void call(commands.mcpRegenerateToken()).then(reload, reload);
const { port, error } = status;
const busy = status.portUnavailable;
const state = status.running
? busy
? tx`Running on port ${port}: the fixed port is unavailable (${busy})`
: tx`Running on port ${port}`
? tx`Running on port ${port}`
: error
? tx`Failed to start: ${error}`
: tx("Not running");
@@ -80,7 +72,7 @@ function McpServerEndpoint() {
return (
<>
<Row label="Status">
<span className={error || busy ? styles.error : styles.status}>{state}</span>
<span className={error ? styles.error : styles.status}>{state}</span>
</Row>
<Row
label="Endpoint"
@@ -102,7 +94,7 @@ function McpServerEndpoint() {
<Row
label="Client configuration"
stacked
hint="The HTTP configuration holds the token: it keeps working after OpenIDEA restarts only with a fixed port and a kept token. The stdio one starts OpenIDEA's executable, which relays to the running IDE."
hint="The HTTP configuration holds this run's token and stops working when OpenIDEA restarts. The stdio one starts OpenIDEA's executable, which relays to the running IDE."
>
<div className={styles.buttons}>
<Button size="small" disabled={!http} onClick={() => copy("http", http)}>
@@ -118,13 +110,6 @@ function McpServerEndpoint() {
)}
</div>
</Row>
{fixedToken && (
<Row label="Token" hint="Clients configured with the current token stop working.">
<Button size="small" disabled={!status.running} onClick={regenerate}>
<T>Regenerate Token</T>
</Button>
</Row>
)}
</>
);
}
@@ -134,7 +119,7 @@ export const MCP_SERVER_PAGE: PageSpec = {
title: "IDE MCP Server",
group: "Agents",
order: 470,
keywords: ["mcp", "model context protocol", "ai", "agent", "claude", "codex", "tools", "stdio", "port", "token"],
keywords: ["mcp", "model context protocol", "ai", "agent", "claude", "codex", "tools", "stdio"],
sections: [
{
options: [
@@ -150,26 +135,6 @@ export const MCP_SERVER_PAGE: PageSpec = {
label: "Run tools without confirmation (brave mode)",
hint: "Run configurations, terminal commands and other tools that change a project start without asking, for unattended agents. Only the IDE's own settings can turn this on, not a project's.",
},
{
kind: "toggle",
key: "mcpServer.fixedPort",
label: "Use a fixed port",
hint: "Listen on the same port in every run, so HTTP clients and port forwards keep working after OpenIDEA restarts. When the port is in use, this run takes a free one and Status says so. Off: a free port in every run.",
},
{
kind: "number",
key: "mcpServer.port",
label: "Port",
...MCP_PORT_LIMITS,
integer: true,
hint: "The fixed port on 127.0.0.1, used while Use a fixed port is on.",
},
{
kind: "toggle",
key: "mcpServer.fixedToken",
label: "Keep the token",
hint: "Keep the same bearer token in every run, stored for your account only. Off: a new token in every run. Anyone with the token can use the tools while OpenIDEA runs, so regenerate it if it leaks.",
},
{
kind: "number",
key: "mcpServer.agentTabLimit",
-84
Переглянути файл
@@ -23,7 +23,6 @@ vi.mock("../CommitChooser", () => ({ chooseLogCommit: (commits: Commit[]) => api
import { commitKey } from "../multiRoot";
import { useVcs } from "../store";
import { DEFAULT_LOG_OPTIONS, useLogOptions } from "../logOptions";
import * as logPresentation from "../logPresentation";
import {
displayedLogGraph,
emptyFilters,
@@ -71,7 +70,6 @@ beforeEach(() => {
commits: [],
selection: [],
selected: null,
seek: null,
done: false,
fragments: { expanded: new Set(), collapsed: new Set(), merges: new Set() },
generation: useGitLog.getState().generation + 1,
@@ -79,7 +77,6 @@ beforeEach(() => {
});
afterEach(async () => {
vi.restoreAllMocks();
api.log.mockResolvedValue(ok([]));
await reloadLog();
});
@@ -298,85 +295,4 @@ describe("commit navigation", () => {
expect(api.log).toHaveBeenCalledTimes(1);
expect(api.log.mock.calls[0]?.[1]).toMatchObject({ seek: target.id, branches: ["HEAD"] });
});
it.each([10, 300])("does not rebuild the displayed graph for each of %i loaded commits", async (count) => {
const commits = Array.from({ length: count }, (_, i) => c(`commit${i}`, i + 1 < count ? [`commit${i + 1}`] : []));
useGitLog.setState({ commits, done: true });
const present = vi.spyOn(logPresentation, "presentLogGraph");
await goToParent(commits[0]!);
expect(useGitLog.getState().selected).toBe("commit1");
expect(api.log).not.toHaveBeenCalled();
expect(present.mock.calls.length).toBeLessThanOrEqual(3);
});
it("reveals a commit beyond thirty fallback pages when seek does not find it", async () => {
const history = Array.from({ length: PAGE * 32 + 7 }, (_, i) => c(`commit${i}`));
const target = history.at(-1)!;
api.log.mockImplementation(async (_repo: string, q: LogQuery) => ok(history.slice(q.skip, q.skip + q.limit)));
await revealCommit(target.id, "/repo");
expect(api.log.mock.calls[0]?.[1].seek).toBe(target.id);
expect(api.log.mock.calls.length).toBeGreaterThan(31);
expect(useGitLog.getState().selected).toBe(commitKey({ ...target, repo: "/repo" }));
});
it("finds an old parent beyond thirty pages with one graph snapshot per check", async () => {
const tip = { ...c("tip", ["parent"]), repo: "/repo" };
const history = [
tip,
...Array.from({ length: PAGE * 31 }, (_, i) =>
c(`commit${i}`, i + 1 < PAGE * 31 ? [`commit${i + 1}`] : ["parent"]),
),
c("parent"),
];
useGitLog.setState({ commits: [tip] });
api.log.mockImplementation(async (_repo: string, q: LogQuery) => ok(history.slice(q.skip, q.skip + q.limit)));
const present = vi.spyOn(logPresentation, "presentLogGraph");
await goToParent(tip);
expect(api.log.mock.calls.length).toBeGreaterThan(30);
expect(useGitLog.getState().selected).toBe(commitKey({ ...c("parent"), repo: "/repo" }));
expect(present.mock.calls.length).toBeLessThanOrEqual(api.log.mock.calls.length + 3);
});
it("recomputes collapsed parent adjacency after loading another page", async () => {
const tip = { ...c("tip", ["middle"]), repo: "/repo" };
useGitLog.setState({ commits: [tip] });
useLogOptions.setState({ collapseLinear: true });
api.log.mockResolvedValue(ok([c("middle", ["base"]), c("base")]));
await goToParent(tip);
expect(api.log).toHaveBeenCalledTimes(1);
expect(useGitLog.getState().selected).toBe(commitKey({ ...c("base"), repo: "/repo" }));
});
it("navigates the displayed parent of a linearized merge", async () => {
const commits = [c("merge", ["main", "side"]), c("side", ["base"]), c("main", ["base"]), c("base")];
useGitLog.setState({ commits, done: true });
useLogOptions.setState({ linearizeMerges: true });
await goToParent(commits[0]!);
expect(useGitLog.getState().selected).toBe("side");
expect(api.choose).not.toHaveBeenCalled();
});
it("does not confuse parent hashes shared by different repositories", async () => {
const tip = { ...c("tip", ["parent"]), repo: "/a" };
useVcs.setState({ roots: ["/a", "/b"] });
useGitLog.setState({
commits: [tip, { ...c("parent"), repo: "/b" }, { ...c("parent"), repo: "/a" }],
done: true,
});
await goToParent(tip);
expect(useGitLog.getState().selected).toBe(commitKey({ ...c("parent"), repo: "/a" }));
expect(api.choose).not.toHaveBeenCalled();
});
});
+5 -11
Переглянути файл
@@ -1196,18 +1196,12 @@ export function displayedLogGraph() {
export async function goToParent(c: Commit) {
const generation = useGitLog.getState().generation;
const find = () => {
const { graph, commits } = displayedLogGraph();
const parents = graph.find((x) => x.id === commitKey(c))?.parents ?? [];
return { parents, candidates: commits.filter((x) => parents.includes(commitKey(x))) };
};
if (!find().parents.length) return;
await pageUntil(() => {
const { parents, candidates } = find();
return candidates.length === parents.length;
});
const parents = () => displayedLogGraph().graph.find((x) => x.id === commitKey(c))?.parents ?? [];
if (!parents().length) return;
const find = () => displayedLogGraph().commits.filter((x) => parents().includes(commitKey(x)));
await pageUntil(() => find().length === parents().length);
if (useGitLog.getState().generation !== generation) return;
const { candidates } = find();
const candidates = find();
const chosen = candidates.length > 1 ? await chooseLogCommit(candidates, "Select Parent Commit") : candidates[0];
if (chosen && useGitLog.getState().generation === generation) selectCommit(commitKey(chosen), true);
}
-2
Переглянути файл
@@ -95,7 +95,6 @@ export const eclipseMacos: Record<string, string[]> = {
"diff.nextFile": [],
"navigate.nextOccurrence": [],
"editor.nextTab": ["Meta+F6", "Meta+Alt+Right"],
"db.nextResultTab": ["Meta+F6", "Meta+Alt+Right"],
"code.optimizeImports": ["Shift+Meta+O"],
"project.optimizeImports": ["Shift+Meta+O"],
"code.overrideMethods": [],
@@ -103,7 +102,6 @@ export const eclipseMacos: Record<string, string[]> = {
"code.expressionTypeInfo": [],
"navigate.prevOccurrence": [],
"editor.prevTab": ["Shift+Meta+F6", "Meta+Alt+Left"],
"db.previousResultTab": ["Shift+Meta+F6", "Meta+Alt+Left"],
"code.quickDocumentation": ["F2"],
"db.quickDoc": ["F2"],
"localHistory.recentChanges": [],
-2
Переглянути файл
@@ -99,7 +99,6 @@ export const eclipseWindows: Record<string, string[]> = {
"diff.applyRightSide": [],
"navigate.nextOccurrence": [],
"editor.nextTab": ["Ctrl+F6", "Ctrl+Alt+Left", "Ctrl+PageDown"],
"db.nextResultTab": ["Ctrl+F6", "Ctrl+Alt+Left", "Ctrl+PageDown"],
"code.optimizeImports": ["Ctrl+Alt+O", "Shift+Ctrl+O"],
"project.optimizeImports": ["Ctrl+Alt+O", "Shift+Ctrl+O"],
"code.overrideMethods": [],
@@ -107,7 +106,6 @@ export const eclipseWindows: Record<string, string[]> = {
"code.expressionTypeInfo": [],
"navigate.prevOccurrence": [],
"editor.prevTab": ["Shift+Ctrl+F6", "Ctrl+Alt+Right", "Ctrl+PageUp"],
"db.previousResultTab": ["Shift+Ctrl+F6", "Ctrl+Alt+Right", "Ctrl+PageUp"],
"code.quickDocumentation": ["Shift+Ctrl+Space", "F2"],
"db.quickDoc": ["Shift+Ctrl+Space", "F2"],
"localHistory.recentChanges": [],
-2
Переглянути файл
@@ -57,8 +57,6 @@ const shared = [
["refactor.changeSignature", "db.modifyTable"],
["refactor.move", "project.move"],
["editor.closeTab", "toolwindow.closeContent"],
["editor.nextTab", "db.nextResultTab"],
["editor.prevTab", "db.previousResultTab"],
["run.rerun", "debug.rerun", "find.rerun", "usages.rerun"],
[
"debug.smartStepInto",
-2
Переглянути файл
@@ -363,8 +363,6 @@ export const intellijMacos: Record<string, string[]> = {
"db.openValueWindow": [],
"db.findInValue": ["Meta+F"],
"db.execute": ["Meta+Enter"],
"db.nextResultTab": ["Meta+Shift+]", "Ctrl+Right"],
"db.previousResultTab": ["Meta+Shift+[", "Ctrl+Left"],
// Table editor with pending changes (after `vcs.rollback`, so ⌥⌘Z reverts the table's edits there).
"db.goToColumn": ["Meta+F12"],
"db.submitChanges": ["Meta+Enter"],
-2
Переглянути файл
@@ -361,8 +361,6 @@ export const intellijWindows: Record<string, string[]> = {
"db.openValueWindow": [],
"db.findInValue": ["Ctrl+F"],
"db.execute": ["Ctrl+Enter"],
"db.nextResultTab": ["Alt+Right"],
"db.previousResultTab": ["Alt+Left"],
// Table editor with pending changes (after `vcs.rollback`, so Ctrl+Alt+Z reverts the table's edits there).
"db.goToColumn": ["Ctrl+F12"],
"db.submitChanges": ["Ctrl+Enter"],
-2
Переглянути файл
@@ -359,8 +359,6 @@ export const vscodeMacos: Record<string, string[]> = {
"db.openValueWindow": [],
"db.findInValue": ["Meta+F"],
"db.execute": ["Meta+Enter"],
"db.nextResultTab": ["Meta+Alt+Right", "Meta+Shift+]"],
"db.previousResultTab": ["Meta+Alt+Left", "Meta+Shift+["],
"db.showToolWindow": [],
// Database tool window (when the tree has focus).
"db.openConsole": [],
-2
Переглянути файл
@@ -37,8 +37,6 @@ export const vscodeWindows: Record<string, string[]> = {
"toolwindow.closeContent": ["Ctrl+W", "Ctrl+F4"],
"editor.nextTab": ["Ctrl+PageDown"],
"editor.prevTab": ["Ctrl+PageUp"],
"db.nextResultTab": ["Ctrl+PageDown"],
"db.previousResultTab": ["Ctrl+PageUp"],
"window.toggleFullScreen": ["F11"],
"project.rename": ["F2"],
"project.delete": ["Delete"],
+2 -12
Переглянути файл
@@ -760,7 +760,7 @@
"Open a project to get its endpoint.": "Open a project to get its endpoint.",
"No project open": "No project open",
"Client configuration": "Client configuration",
"The HTTP configuration holds the token: it keeps working after OpenIDEA restarts only with a fixed port and a kept token. The stdio one starts OpenIDEA's executable, which relays to the running IDE.": "The HTTP configuration holds the token: it keeps working after OpenIDEA restarts only with a fixed port and a kept token. The stdio one starts OpenIDEA's executable, which relays to the running IDE.",
"The HTTP configuration holds this run's token and stops working when OpenIDEA restarts. The stdio one starts OpenIDEA's executable, which relays to the running IDE.": "The HTTP configuration holds this run's token and stops working when OpenIDEA restarts. The stdio one starts OpenIDEA's executable, which relays to the running IDE.",
"Copy HTTP Config": "Copy HTTP Config",
"Copy Stdio Config": "Copy Stdio Config",
"Copied to the clipboard": "Copied to the clipboard",
@@ -1472,15 +1472,5 @@
"Archived ({count})": "Archived ({count})",
"no usages": "no usages",
"1 usage": "1 usage",
"{n} usages": "{n} usages",
"Running on port {port}: the fixed port is unavailable ({busy})": "Running on port {port}: the fixed port is unavailable ({busy})",
"Token": "Token",
"Clients configured with the current token stop working.": "Clients configured with the current token stop working.",
"Regenerate Token": "Regenerate Token",
"Use a fixed port": "Use a fixed port",
"Listen on the same port in every run, so HTTP clients and port forwards keep working after OpenIDEA restarts. When the port is in use, this run takes a free one and Status says so. Off: a free port in every run.": "Listen on the same port in every run, so HTTP clients and port forwards keep working after OpenIDEA restarts. When the port is in use, this run takes a free one and Status says so. Off: a free port in every run.",
"Port": "Port",
"The fixed port on 127.0.0.1, used while Use a fixed port is on.": "The fixed port on 127.0.0.1, used while Use a fixed port is on.",
"Keep the token": "Keep the token",
"Keep the same bearer token in every run, stored for your account only. Off: a new token in every run. Anyone with the token can use the tools while OpenIDEA runs, so regenerate it if it leaks.": "Keep the same bearer token in every run, stored for your account only. Off: a new token in every run. Anyone with the token can use the tools while OpenIDEA runs, so regenerate it if it leaks."
"{n} usages": "{n} usages"
}
+2 -11
Переглянути файл
@@ -7149,7 +7149,7 @@
"Open a project to get its endpoint.": "打开一个项目以获取其端点。",
"No project open": "未打开项目",
"Client configuration": "客户端配置",
"The HTTP configuration holds the token: it keeps working after OpenIDEA restarts only with a fixed port and a kept token. The stdio one starts OpenIDEA's executable, which relays to the running IDE.": "HTTP 配置包含令牌:只有同时使用固定端口并保留令牌时,它在 OpenIDEA 重启后才继续有效。stdio 配置会启动 OpenIDEA 的可执行文件,由它转发到正在运行的 IDE。",
"The HTTP configuration holds this run's token and stops working when OpenIDEA restarts. The stdio one starts OpenIDEA's executable, which relays to the running IDE.": "HTTP 配置包含本次运行的令牌,OpenIDEA 重启后即失效。stdio 配置会启动 OpenIDEA 的可执行文件,由它转发到正在运行的 IDE。",
"Copy HTTP Config": "复制 HTTP 配置",
"Copy Stdio Config": "复制 Stdio 配置",
"Copied to the clipboard": "已复制到剪贴板",
@@ -7870,14 +7870,5 @@
"Archived ({count})": "归档({count})",
"no usages": "无用法",
"1 usage": "1 个用法",
"{n} usages": "{n} 个用法",
"Running on port {port}: the fixed port is unavailable ({busy})": "正在端口 {port} 上运行:固定端口不可用({busy})",
"Token": "令牌",
"Clients configured with the current token stop working.": "使用当前令牌配置的客户端将失效。",
"Regenerate Token": "重新生成令牌",
"Use a fixed port": "使用固定端口",
"Listen on the same port in every run, so HTTP clients and port forwards keep working after OpenIDEA restarts. When the port is in use, this run takes a free one and Status says so. Off: a free port in every run.": "每次运行都监听同一个端口,这样 OpenIDEA 重启后 HTTP 客户端和端口转发仍然有效。端口被占用时,本次运行改用一个空闲端口,并在状态中说明。关闭时:每次运行使用一个空闲端口。",
"The fixed port on 127.0.0.1, used while Use a fixed port is on.": "127.0.0.1 上的固定端口,在开启“使用固定端口”时使用。",
"Keep the token": "保留令牌",
"Keep the same bearer token in every run, stored for your account only. Off: a new token in every run. Anyone with the token can use the tools while OpenIDEA runs, so regenerate it if it leaks.": "每次运行都使用同一个访问令牌,只为你的账户保存。关闭时:每次运行生成新令牌。任何拿到令牌的人都能在 OpenIDEA 运行时使用这些工具,令牌泄露时请重新生成。"
"{n} usages": "{n} 个用法"
}