дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-06 18:17:15 +02:00
Порівняти коміти
7
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
d757a1704b | ||
|
|
620fa247ef | ||
|
|
52e5a0c4af | ||
|
|
4acb265b90 | ||
|
|
b284c37588 | ||
|
|
771575057e | ||
|
|
563d2a75d4 |
No files matched your search
@@ -270,6 +270,13 @@ 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| {
|
||||
@@ -909,6 +916,8 @@ 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]
|
||||
|
||||
@@ -77,6 +77,9 @@ 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).
|
||||
|
||||
@@ -300,11 +300,30 @@ 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 }
|
||||
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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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_workspace_edit(&call.host, call.window(), edit).await
|
||||
crate::ops::lsp::apply_agent_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_workspace_edit(&host, call.window(), edit).await
|
||||
crate::ops::lsp::apply_agent_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_workspace_edit(&host, call.window(), edit).await?;
|
||||
crate::ops::lsp::apply_agent_workspace_edit(&host, call.window(), edit).await?;
|
||||
if dirty {
|
||||
notes.push(format!("{shown}: patched the unsaved editor buffer"));
|
||||
}
|
||||
|
||||
@@ -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_workspace_edit(&h, &w, edit).await;
|
||||
let written = crate::ops::lsp::apply_agent_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));
|
||||
|
||||
@@ -1483,23 +1483,38 @@ 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 || {
|
||||
// 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");
|
||||
}
|
||||
record_before_multi_file_edit(&project, &edit);
|
||||
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 || {
|
||||
|
||||
@@ -231,7 +231,11 @@ async fn mutations_preserve_unsaved_text_and_reject_metadata_and_escapes() {
|
||||
.iter()
|
||||
.rev()
|
||||
.find_map(|event| match event {
|
||||
IdeEvent::WorkspaceEditApplied { id, .. } => Some(*id),
|
||||
// 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)
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
@@ -223,6 +223,8 @@ 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) => {
|
||||
@@ -322,11 +324,13 @@ 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(|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(
|
||||
|mut e| {
|
||||
crate::virtual_doc::normalize_uris(&mut 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() {
|
||||
|
||||
@@ -1440,13 +1440,9 @@ impl LspManager {
|
||||
let params = serde_json::to_value(params).map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
let stamp = self.injected_request_stamp(¶ms);
|
||||
let fut = async {
|
||||
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 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}")))
|
||||
};
|
||||
let result = match tokio::time::timeout(timeout, fut).await {
|
||||
Ok(r) => r.map_err(|e| rpc_err(&t.server.name, method, e)),
|
||||
|
||||
@@ -18,23 +18,36 @@ const URI_ESCAPES: &AsciiSet = &CONTROLS
|
||||
.add(b'|')
|
||||
.add(b'}');
|
||||
|
||||
/// 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) {
|
||||
/// 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) {
|
||||
match value {
|
||||
serde_json::Value::Array(values) => values.iter_mut().for_each(normalize_csharp_uris),
|
||||
serde_json::Value::Array(values) => values.iter_mut().for_each(normalize_uris),
|
||||
serde_json::Value::Object(fields) => {
|
||||
for (key, value) in fields {
|
||||
for (key, value) in fields.iter_mut() {
|
||||
// Opaque payloads must survive resolve/execute round trips unchanged.
|
||||
if matches!(key.as_str(), "data" | "arguments") {
|
||||
continue;
|
||||
}
|
||||
if matches!(key.as_str(), "uri" | "targetUri")
|
||||
&& let Some(uri) = value.as_str().filter(|s| s.starts_with("csharp:"))
|
||||
if matches!(key.as_str(), "uri" | "targetUri" | "oldUri" | "newUri")
|
||||
&& let Some(uri) = value.as_str().and_then(escaped_uri)
|
||||
{
|
||||
*value = utf8_percent_encode(uri, URI_ESCAPES).to_string().into();
|
||||
*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();
|
||||
} else {
|
||||
normalize_csharp_uris(value);
|
||||
normalize_uris(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -42,6 +55,16 @@ pub(crate) fn normalize_csharp_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 {
|
||||
@@ -202,7 +225,7 @@ mod tests {
|
||||
{ "data": { "uri": uri }, "command": { "arguments": [{ "targetUri": uri }] } }
|
||||
]);
|
||||
let original = response.clone();
|
||||
normalize_csharp_uris(&mut response);
|
||||
normalize_uris(&mut response);
|
||||
assert_eq!(response[0]["uri"], encoded);
|
||||
assert_eq!(response[0]["source"], uri);
|
||||
assert_eq!(response[1]["location"]["targetUri"], encoded);
|
||||
@@ -210,6 +233,31 @@ 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");
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! `<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.
|
||||
//! the server stops. `<app-data>/mcp/token` keeps the token across runs when
|
||||
//! the user chose a fixed token.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::io;
|
||||
@@ -14,6 +15,28 @@ 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,
|
||||
@@ -32,15 +55,8 @@ 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)?;
|
||||
let written = write_private(&tmp, &bytes).and_then(|()| std::fs::rename(&tmp, path));
|
||||
if written.is_err() {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
}
|
||||
written
|
||||
write_atomic(path, &bytes)
|
||||
}
|
||||
|
||||
/// Removes the file at `path` if it still describes this process's server.
|
||||
@@ -51,6 +67,18 @@ 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;
|
||||
@@ -91,4 +119,23 @@ 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");
|
||||
}
|
||||
}
|
||||
@@ -22,8 +22,8 @@ mod protocol;
|
||||
mod server;
|
||||
pub mod stdio;
|
||||
|
||||
pub use discovery::{DISCOVERY_FILE, Discovery, discovery_path};
|
||||
pub use server::McpServer;
|
||||
pub use discovery::{DISCOVERY_FILE, Discovery, TOKEN_FILE, discovery_path, kept_token, token_path};
|
||||
pub use server::{McpServer, ServerOptions};
|
||||
pub use tokio_util::sync::CancellationToken;
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
@@ -49,12 +49,25 @@ 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.
|
||||
@@ -63,10 +76,32 @@ impl McpServer {
|
||||
discovery: Option<PathBuf>,
|
||||
runtime: &tokio::runtime::Handle,
|
||||
) -> std::io::Result<Self> {
|
||||
let listener = std::net::TcpListener::bind(("127.0.0.1", 0))?;
|
||||
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),
|
||||
};
|
||||
listener.set_nonblocking(true)?;
|
||||
let port = listener.local_addr()?.port();
|
||||
let token = new_token()?;
|
||||
let token = match options.token {
|
||||
Some(token) => token,
|
||||
None => new_token()?,
|
||||
};
|
||||
let listener = {
|
||||
let _entered = runtime.enter();
|
||||
tokio::net::TcpListener::from_std(listener)?
|
||||
@@ -91,13 +126,18 @@ impl McpServer {
|
||||
});
|
||||
runtime.spawn(accept(listener, shared, stopped));
|
||||
tracing::info!("MCP server on 127.0.0.1:{port}");
|
||||
Ok(Self { port, token, discovery, shutdown, cancel })
|
||||
Ok(Self { port, port_unavailable, 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,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, Tool, ToolCallError, ToolRegistry, discovery_path, stdio};
|
||||
use ide_mcp::{Discovery, McpServer, ServerOptions, Tool, ToolCallError, ToolRegistry, discovery_path, stdio};
|
||||
use serde_json::{Value, json};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
@@ -366,3 +366,30 @@ 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()
|
||||
);
|
||||
}
|
||||
@@ -323,6 +323,18 @@ 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)
|
||||
@@ -330,6 +342,21 @@ 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>,
|
||||
|
||||
@@ -1866,6 +1866,37 @@ 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};
|
||||
|
||||
@@ -281,6 +281,9 @@ 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]);
|
||||
|
||||
@@ -800,16 +800,41 @@ 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", "--", name],
|
||||
(false, true) => vec!["branch", "--force", "--", name],
|
||||
(false, false) => vec!["branch"],
|
||||
(false, true) => vec!["branch", "--force"],
|
||||
};
|
||||
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
|
||||
|
||||
@@ -984,15 +984,41 @@ fn branch_overwrite_preserves_the_ref_if_checkout_fails() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_branch_from_remote_branch_tracks_it() {
|
||||
let (fx, _bare) = Fixture::with_origin();
|
||||
fn new_branch_from_remote_branch_tracks_it_only_under_the_same_name() {
|
||||
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.as_deref(), Some("origin/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);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -389,6 +389,12 @@ 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(()))
|
||||
@@ -399,6 +405,16 @@ 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() {
|
||||
@@ -485,7 +501,7 @@ impl Documents {
|
||||
});
|
||||
}
|
||||
history.prune(SystemTime::now(), MAX_HISTORY_BYTES, MAX_HISTORY_AGE);
|
||||
self.sink.emit(IdeEvent::WorkspaceEditApplied { id, paths: affected });
|
||||
self.sink.emit(IdeEvent::WorkspaceEditApplied { id, paths: affected, by_agent });
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -122,6 +122,8 @@ 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).
|
||||
|
||||
@@ -18,14 +18,17 @@ Agent tasks started inside OpenIDEA (see [Agents](/en/guide/agents)) get the sam
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
## 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 stops working when OpenIDEA restarts, because the port and token change.
|
||||
- **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.
|
||||
|
||||
The stdio configuration looks like this (the path is the one on your machine):
|
||||
|
||||
|
||||
@@ -122,6 +122,8 @@ SQL 补全基于已连接的架构:`FROM`/`JOIN` 后补全表(并根据外
|
||||
|
||||
右键点击结果标签页(或聚焦后按 `Shift+F10`),可使用 **关闭**、**关闭其他**、**全部关闭**、**重命名标签页**、**选择下一个标签页** 和 **选择上一个标签页**。这些操作只作用于结果标签页,**输出** 始终保留。重命名的标题在结果关闭前一直有效。
|
||||
|
||||
焦点位于结果标签页或结果内容中时,IntelliJ macOS 快捷键方案使用 `⇧⌘]` / `⇧⌘[`(也支持 `⌃→` / `⌃←`),IntelliJ Windows/Linux 使用 `Alt+→` / `Alt+←`。VS Code 和 Eclipse 方案分别使用各自默认的编辑器标签页导航快捷键。切换后焦点移到目标结果标签页。结果导航快捷键仅在结果区域中生效,菜单或对话框打开时不会切换结果。可在 **设置 › 快捷键** 中单独修改数据库结果快捷键,不影响编辑器快捷键。
|
||||
|
||||
关闭当前选中的结果标签页时,优先选中左侧相邻的结果;没有左侧结果时,选中右侧相邻结果。没有剩余结果时,选中 **输出**。关闭未选中的结果不会改变当前选择。
|
||||
|
||||
- **表** 或 **图表** 视图(柱状图或折线图,可选 X/Y 列和聚合方式)。
|
||||
|
||||
@@ -17,14 +17,17 @@ OpenIDEA 内置了一个 [Model Context Protocol](https://modelcontextprotocol.i
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
服务器只监听 `127.0.0.1` 上的一个随机端口,每个请求都必须带上令牌,令牌在每次启动 OpenIDEA 时都会变化。来自其他 Origin 或 Host 的请求会被拒绝。
|
||||
服务器只监听 `127.0.0.1`,每个请求都必须带上访问令牌。来自其他 Origin 或 Host 的请求会被拒绝。
|
||||
|
||||
- **端口。** 默认每次运行都监听同一个端口 26371(**使用固定端口** 和 **端口**),这样 OpenIDEA 重启后 HTTP 客户端和端口转发(例如到另一台机器的 SSH 隧道)仍然有效。端口被占用或被系统保留时,本次运行改用一个空闲端口,**状态** 中会说明原因。关闭 **使用固定端口** 则每次运行使用一个空闲端口。
|
||||
- **令牌。** 默认每次启动 OpenIDEA 都会换一个新令牌。打开 **保留令牌** 后会在多次运行间保留同一个令牌,保存在 OpenIDEA 的应用数据目录中,只有你的账户可读;**重新生成令牌** 会替换它,使用旧令牌配置的客户端随之失效。
|
||||
|
||||
## 连接客户端
|
||||
|
||||
设置页面的 **客户端配置** 下有两个按钮,都会复制一段大多数客户端都能识别的 `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 配置大致如下(路径以你机器上的为准):
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import { expect, test } from "./fixtures";
|
||||
import { expect, openFromTree, 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,7 +64,9 @@ 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, exact: true }).click();
|
||||
await menu(page)
|
||||
.getByRole("menuitem", { name: command.startsWith("Select ") ? new RegExp(`^${command}`) : command, exact: true })
|
||||
.click();
|
||||
await expect(menu(page)).toHaveCount(0);
|
||||
}
|
||||
|
||||
@@ -91,8 +93,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");
|
||||
@@ -140,7 +142,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", exact: true })).toBeFocused();
|
||||
await expect(popup.getByRole("menuitem", { name: /^Select Previous Tab/ })).toBeFocused();
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(popup).toHaveCount(0);
|
||||
await selected(page, "Result 1", "alpha rows");
|
||||
@@ -207,7 +209,9 @@ 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", exact: true }).click();
|
||||
await menu(page)
|
||||
.getByRole("menuitem", { name: /^Select Previous Tab/ })
|
||||
.click();
|
||||
await expect(menu(page)).toHaveCount(0);
|
||||
await page.mouse.move(0, 0);
|
||||
await expect(otherSurface).toHaveCSS("background-color", idle);
|
||||
@@ -266,6 +270,59 @@ 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 () => {
|
||||
|
||||
@@ -15,45 +15,92 @@ 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>>,
|
||||
}
|
||||
|
||||
/// Starts or stops the server to match the global `mcpServer.enabled`.
|
||||
/// 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.
|
||||
pub fn apply(state: &AppState) {
|
||||
let enabled = state.global_settings.effective().mcp_server.enabled;
|
||||
let settings = state.global_settings.effective().mcp_server;
|
||||
let mut server = state.mcp.server.lock();
|
||||
if !enabled {
|
||||
if !settings.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;
|
||||
}
|
||||
if server.is_some() {
|
||||
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) {
|
||||
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(
|
||||
match ide_mcp::McpServer::start_with(
|
||||
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);
|
||||
@@ -61,6 +108,7 @@ 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.
|
||||
@@ -71,11 +119,14 @@ 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).
|
||||
/// Bearer token of `url` (changes with every run unless `mcpServer.fixedToken` is on).
|
||||
pub token: Option<String>,
|
||||
/// The stdio bridge: this executable and its arguments.
|
||||
pub stdio_command: Vec<String>,
|
||||
@@ -91,6 +142,7 @@ 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(),
|
||||
@@ -98,6 +150,21 @@ 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<()> {
|
||||
|
||||
@@ -75,6 +75,7 @@ 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,
|
||||
|
||||
@@ -63,7 +63,9 @@ impl EventSink for TauriSink {
|
||||
) {
|
||||
flash_taskbar_unless_focused(&self.app);
|
||||
}
|
||||
if matches!(&event, IdeEvent::McpRequest { .. })
|
||||
// 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 { .. }, .. })
|
||||
&& let Some(label) = self.window.clone()
|
||||
{
|
||||
let app = self.app.clone();
|
||||
|
||||
+29
-2
@@ -19,6 +19,11 @@ 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: {
|
||||
@@ -5859,7 +5864,12 @@ 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[] } |
|
||||
{ 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 } |
|
||||
/**
|
||||
* An open document's language changed (Settings › File Types, Override File
|
||||
* Type), or its UI mode (a framework's root marker appeared or went).
|
||||
@@ -7197,6 +7207,18 @@ 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. */
|
||||
@@ -7205,11 +7227,16 @@ 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). */
|
||||
/** Bearer token of `url` (changes with every run unless `mcpServer.fixedToken` is on). */
|
||||
token: string | null,
|
||||
/** The stdio bridge: this executable and its arguments. */
|
||||
stdioCommand: string[],
|
||||
|
||||
@@ -57,7 +57,12 @@ 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"] });
|
||||
emitLocalIdeEvent({
|
||||
type: "workspaceEditApplied",
|
||||
id: 9,
|
||||
paths: ["/p/A.java", "/p/B.java", "/p/closed.java"],
|
||||
byAgent: false,
|
||||
});
|
||||
}
|
||||
function historyStep(slot: EditorSlot, forward = false) {
|
||||
return (forward ? redo : undo)({
|
||||
@@ -183,7 +188,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"] });
|
||||
emitLocalIdeEvent({ type: "workspaceEditApplied", id: 10, paths: ["/p/A.java", "/p/B.java"], byAgent: true });
|
||||
commands.undoWorkspaceEdit.mockImplementation(async (id: number) => {
|
||||
await replace(id === 10 ? "new" : "old");
|
||||
return { status: "ok", data: null };
|
||||
|
||||
@@ -35,7 +35,7 @@ it("waits for pending typing before undoing the entire backend transaction", asy
|
||||
release = resolve;
|
||||
}),
|
||||
);
|
||||
emitLocalIdeEvent({ type: "workspaceEditApplied", id: 17, paths: [] });
|
||||
emitLocalIdeEvent({ type: "workspaceEditApplied", id: 17, paths: [], byAgent: false });
|
||||
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: [] });
|
||||
emitLocalIdeEvent({ type: "workspaceEditApplied", id: 18, paths: [], byAgent: false });
|
||||
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: [] });
|
||||
emitLocalIdeEvent({ type: "workspaceEditApplied", id: 19, paths: [], byAgent: false });
|
||||
const previous = useProject.getState().project;
|
||||
useProject.setState({ project: { ...previous, root: "/different-project" } as NonNullable<typeof previous> });
|
||||
try {
|
||||
@@ -64,3 +64,8 @@ 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([]);
|
||||
});
|
||||
@@ -3,7 +3,10 @@ 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. */
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
export function installWorkspaceEditUndo(): () => void {
|
||||
let current: { id: number; project: ReturnType<typeof useProject.getState>["project"]; undone: boolean } | null =
|
||||
null;
|
||||
@@ -38,7 +41,8 @@ export function installWorkspaceEditUndo(): () => void {
|
||||
],
|
||||
});
|
||||
};
|
||||
const stopApplied = onIdeEvent("workspaceEditApplied", ({ id }) => {
|
||||
const stopApplied = onIdeEvent("workspaceEditApplied", ({ id, byAgent }) => {
|
||||
if (byAgent) return;
|
||||
current = { id, project: useProject.getState().project, undone: false };
|
||||
show();
|
||||
});
|
||||
|
||||
@@ -665,7 +665,16 @@ export function ResultsView() {
|
||||
const results = useDatabase((s) => s.results);
|
||||
const active = useDatabase((s) => s.activeResult);
|
||||
const hasOutput = useDatabase((s) => s.output.length > 0);
|
||||
useEffect(() => () => setContext("dbResultsFocus", false), []);
|
||||
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);
|
||||
};
|
||||
}, []);
|
||||
const tabMenu = (id: string, e: MouseEvent) => {
|
||||
e.preventDefault();
|
||||
const rect = e.currentTarget.getBoundingClientRect();
|
||||
@@ -682,11 +691,8 @@ 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"]');
|
||||
|
||||
@@ -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, useKeymap } from "@/platform/keymap";
|
||||
import { installKeyboardDispatcher, normalizeBinding, PRESETS, 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 }));
|
||||
fireEvent.click(screen.getByRole("menuitem", { name: name.startsWith("Select ") ? new RegExp(`^${name}`) : name }));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -139,29 +139,6 @@ 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");
|
||||
@@ -386,6 +363,88 @@ 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: {
|
||||
|
||||
@@ -17,11 +17,19 @@ function closeOthers(id: number) {
|
||||
for (const tab of useDatabase.getState().results) if (tab.id !== id) closeResult(tab.id);
|
||||
}
|
||||
|
||||
function cycle(direction: 1 | -1) {
|
||||
function cycle(direction: 1 | -1, focus: boolean) {
|
||||
const { results, activeResult } = useDatabase.getState();
|
||||
const ids = [OUTPUT_TAB, ...results.map((r) => r.id)];
|
||||
const index = ids.indexOf(activeResult ?? OUTPUT_TAB);
|
||||
if (index >= 0) useDatabase.setState({ activeResult: ids[(index + direction + ids.length) % ids.length]! });
|
||||
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 });
|
||||
}
|
||||
|
||||
export function registerResultTabActions(): () => void {
|
||||
@@ -73,7 +81,7 @@ export function registerResultTabActions(): () => void {
|
||||
category: "Database",
|
||||
keyWhen: "dbResultsFocus && !popupOpen",
|
||||
enabled: (c: ActionContext) => target(c) !== null && useDatabase.getState().results.length > 0,
|
||||
run: () => cycle(direction),
|
||||
run: ({ ctx }: ActionContext) => cycle(direction, !!ctx.dbResultsFocus),
|
||||
})),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ 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(() => ({
|
||||
@@ -157,6 +158,48 @@ 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 } });
|
||||
|
||||
@@ -7,6 +7,7 @@ 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",
|
||||
@@ -20,6 +21,13 @@ 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({
|
||||
|
||||
@@ -40,6 +40,10 @@ 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";
|
||||
|
||||
@@ -112,7 +116,17 @@ 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 };
|
||||
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;
|
||||
};
|
||||
}
|
||||
|
||||
/** One `languageServers.<name>` entry; every field optional, like in settings.toml. */
|
||||
@@ -208,6 +222,9 @@ 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,
|
||||
};
|
||||
@@ -383,6 +400,9 @@ 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),
|
||||
};
|
||||
|
||||
@@ -6,6 +6,8 @@ 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";
|
||||
|
||||
@@ -23,9 +25,10 @@ export function stdioConfig(status: McpServerStatus): string | null {
|
||||
return JSON.stringify({ mcpServers: { openidea: { type: "stdio", command, args } } }, null, 2);
|
||||
}
|
||||
|
||||
function useStatus(): McpServerStatus | null {
|
||||
function useStatus(): [McpServerStatus | null, () => void] {
|
||||
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;
|
||||
@@ -43,13 +46,14 @@ function useStatus(): McpServerStatus | null {
|
||||
live = false;
|
||||
off();
|
||||
};
|
||||
}, [root]);
|
||||
return status;
|
||||
}, [root, loads]);
|
||||
return [status, () => setLoads((n) => n + 1)];
|
||||
}
|
||||
|
||||
function McpServerEndpoint() {
|
||||
const tx = useTx();
|
||||
const status = useStatus();
|
||||
const [status, reload] = useStatus();
|
||||
const [fixedToken] = useSetting<boolean>("mcpServer.fixedToken");
|
||||
const [copied, setCopied] = useState<string | null>(null);
|
||||
useEffect(() => {
|
||||
if (!copied) return;
|
||||
@@ -61,9 +65,13 @@ 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
|
||||
? tx`Running on port ${port}`
|
||||
? busy
|
||||
? tx`Running on port ${port}: the fixed port is unavailable (${busy})`
|
||||
: tx`Running on port ${port}`
|
||||
: error
|
||||
? tx`Failed to start: ${error}`
|
||||
: tx("Not running");
|
||||
@@ -72,7 +80,7 @@ function McpServerEndpoint() {
|
||||
return (
|
||||
<>
|
||||
<Row label="Status">
|
||||
<span className={error ? styles.error : styles.status}>{state}</span>
|
||||
<span className={error || busy ? styles.error : styles.status}>{state}</span>
|
||||
</Row>
|
||||
<Row
|
||||
label="Endpoint"
|
||||
@@ -94,7 +102,7 @@ function McpServerEndpoint() {
|
||||
<Row
|
||||
label="Client configuration"
|
||||
stacked
|
||||
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."
|
||||
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."
|
||||
>
|
||||
<div className={styles.buttons}>
|
||||
<Button size="small" disabled={!http} onClick={() => copy("http", http)}>
|
||||
@@ -110,6 +118,13 @@ 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>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -119,7 +134,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"],
|
||||
keywords: ["mcp", "model context protocol", "ai", "agent", "claude", "codex", "tools", "stdio", "port", "token"],
|
||||
sections: [
|
||||
{
|
||||
options: [
|
||||
@@ -135,6 +150,26 @@ 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",
|
||||
|
||||
@@ -23,6 +23,7 @@ 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,
|
||||
@@ -70,6 +71,7 @@ beforeEach(() => {
|
||||
commits: [],
|
||||
selection: [],
|
||||
selected: null,
|
||||
seek: null,
|
||||
done: false,
|
||||
fragments: { expanded: new Set(), collapsed: new Set(), merges: new Set() },
|
||||
generation: useGitLog.getState().generation + 1,
|
||||
@@ -77,6 +79,7 @@ beforeEach(() => {
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
vi.restoreAllMocks();
|
||||
api.log.mockResolvedValue(ok([]));
|
||||
await reloadLog();
|
||||
});
|
||||
@@ -295,4 +298,85 @@ 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();
|
||||
});
|
||||
});
|
||||
@@ -1196,12 +1196,18 @@ export function displayedLogGraph() {
|
||||
|
||||
export async function goToParent(c: Commit) {
|
||||
const generation = useGitLog.getState().generation;
|
||||
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);
|
||||
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;
|
||||
});
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -95,6 +95,7 @@ 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": [],
|
||||
@@ -102,6 +103,7 @@ 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": [],
|
||||
|
||||
@@ -99,6 +99,7 @@ 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": [],
|
||||
@@ -106,6 +107,7 @@ 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": [],
|
||||
|
||||
@@ -57,6 +57,8 @@ 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",
|
||||
|
||||
@@ -363,6 +363,8 @@ 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"],
|
||||
|
||||
@@ -361,6 +361,8 @@ 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"],
|
||||
|
||||
@@ -359,6 +359,8 @@ 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": [],
|
||||
|
||||
@@ -37,6 +37,8 @@ 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"],
|
||||
|
||||
@@ -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 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.",
|
||||
"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.",
|
||||
"Copy HTTP Config": "Copy HTTP Config",
|
||||
"Copy Stdio Config": "Copy Stdio Config",
|
||||
"Copied to the clipboard": "Copied to the clipboard",
|
||||
@@ -1472,5 +1472,15 @@
|
||||
"Archived ({count})": "Archived ({count})",
|
||||
"no usages": "no usages",
|
||||
"1 usage": "1 usage",
|
||||
"{n} usages": "{n} usages"
|
||||
"{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."
|
||||
}
|
||||
@@ -7149,7 +7149,7 @@
|
||||
"Open a project to get its endpoint.": "打开一个项目以获取其端点。",
|
||||
"No project open": "未打开项目",
|
||||
"Client configuration": "客户端配置",
|
||||
"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。",
|
||||
"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。",
|
||||
"Copy HTTP Config": "复制 HTTP 配置",
|
||||
"Copy Stdio Config": "复制 Stdio 配置",
|
||||
"Copied to the clipboard": "已复制到剪贴板",
|
||||
@@ -7870,5 +7870,14 @@
|
||||
"Archived ({count})": "归档({count})",
|
||||
"no usages": "无用法",
|
||||
"1 usage": "1 个用法",
|
||||
"{n} usages": "{n} 个用法"
|
||||
"{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 运行时使用这些工具,令牌泄露时请重新生成。"
|
||||
}
|
||||
Reference in new issue
Заблокувати користувача