дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-16 14:45:40 +02:00
Порівняти коміти
38
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
cd574a3e28 | ||
|
|
8aed4156f4 | ||
|
|
0221034936 | ||
|
|
0d432bf1a6 | ||
|
|
cbac930a6f | ||
|
|
33f082e32f | ||
|
|
0bbf5568cd | ||
|
|
2277c1cdfd | ||
|
|
a537223233 | ||
|
|
19c7947fc4 | ||
|
|
98f9fc0063 | ||
|
|
0d5ef48a94 | ||
|
|
444b620985 | ||
|
|
0c45a96d84 | ||
|
|
fd8f8d6dd0 | ||
|
|
c1bec5182c | ||
|
|
dcb4835a87 | ||
|
|
f74bc7abac | ||
|
|
c871c164c1 | ||
|
|
db65b12afe | ||
|
|
0cc873565a | ||
|
|
7cc100367d | ||
|
|
39c0f6676e | ||
|
|
f19d5dc3f9 | ||
|
|
0a8df16941 | ||
|
|
6dcece3081 | ||
|
|
5c59566897 | ||
|
|
6b3edb6cf5 | ||
|
|
e598936529 | ||
|
|
8b7318e59a | ||
|
|
faa9a91953 | ||
|
|
c805173467 | ||
|
|
94b72c271a | ||
|
|
610d68ee41 | ||
|
|
c6bd809d08 | ||
|
|
401d66d850 | ||
|
|
4561ae05b2 | ||
|
|
34c81a61e4 |
No files matched your search
@@ -2,8 +2,8 @@
|
||||
//! the agent reports them over ACP.
|
||||
|
||||
use crate::model::{
|
||||
AgentCommand, AgentCommandSource, AgentConfigOption, AgentConfigValue, AgentConfigVia, AgentCost, AgentLimit,
|
||||
AgentModelPricing, AgentUsage,
|
||||
AgentCommand, AgentCommandSource, AgentConfigChoice, AgentConfigOption, AgentConfigValue, AgentConfigVia,
|
||||
AgentCost, AgentLimit, AgentModelPricing, AgentUsage,
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
@@ -54,6 +54,45 @@ pub(crate) fn bypass_approvals(config: &[AgentConfigOption]) -> bool {
|
||||
.any(|category| selected(category).zip(bypass_value(category)).is_some_and(|(value, bypass)| bypass(value)))
|
||||
}
|
||||
|
||||
/// Mode values that ask before anything changes the project, most careful first: Codex's
|
||||
/// Read Only (its Ask still edits the workspace), Claude Code's default (its Accept Edits
|
||||
/// doesn't ask), then plan modes.
|
||||
const ASKING_MODES: [&str; 4] = ["read-only", "default", "plan", "ask"];
|
||||
|
||||
/// Moves `config` to settings that ask before anything changes the project (a side
|
||||
/// conversation): approvals that approve everything ask, and the mode is the most careful one.
|
||||
pub(crate) fn keep_asking(config: &mut [AgentConfigOption]) {
|
||||
ask_for_approvals(config);
|
||||
for option in config.iter_mut().filter(|o| o.category.as_deref() == Some("mode")) {
|
||||
if let Some(mode) = ASKING_MODES.iter().find(|m| option.values.iter().any(|v| v.value == **m)) {
|
||||
option.current = Some((*mode).to_owned());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The choices that keep a session asking before it changes anything: `wanted` without its
|
||||
/// mode and approval choices, and the [`keep_asking`] value of each such option of `options`.
|
||||
pub(crate) fn asking_choices(options: &[AgentConfigOption], wanted: &[AgentConfigChoice]) -> Vec<AgentConfigChoice> {
|
||||
let guarded = |o: &AgentConfigOption| o.category.as_deref().and_then(bypass_value).is_some();
|
||||
let mut out: Vec<AgentConfigChoice> =
|
||||
wanted.iter().filter(|c| !options.iter().any(|o| o.id == c.id && guarded(o))).cloned().collect();
|
||||
let mut asking = options.to_vec();
|
||||
keep_asking(&mut asking);
|
||||
for option in asking.iter().filter(|o| guarded(o)) {
|
||||
if let Some(value) = &option.current {
|
||||
out.push(AgentConfigChoice { id: option.id.clone(), value: value.clone() });
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether `config` is what [`keep_asking`] makes of it.
|
||||
pub(crate) fn keeps_asking(config: &[AgentConfigOption]) -> bool {
|
||||
let mut asking = config.to_vec();
|
||||
keep_asking(&mut asking);
|
||||
asking.iter().zip(config).all(|(a, b)| a.current == b.current)
|
||||
}
|
||||
|
||||
/// For an option of `category` that can approve everything, what tells its approving values.
|
||||
fn bypass_value(category: &str) -> Option<fn(&str) -> bool> {
|
||||
match category {
|
||||
@@ -464,6 +503,26 @@ mod tests {
|
||||
assert_eq!(ids(&c), [("allow_all", Some("off")), ("approval", Some("ask"))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn asking_choices_keep_a_side_conversation_from_changing_anything() {
|
||||
let codex = options_of(&json!({"modes": {"currentModeId": "full-access",
|
||||
"availableModes": [{"id": "read-only"}, {"id": "ask"}, {"id": "auto"}, {"id": "full-access"}]}}));
|
||||
let mode = codex[0].id.clone();
|
||||
let choice = |id: &str, value: &str| AgentConfigChoice { id: id.into(), value: value.into() };
|
||||
// Codex goes to Read Only (its Ask edits the workspace), whatever the source task chose.
|
||||
let wanted = asking_choices(&codex, &[choice(&mode, "full-access"), choice("model", "gpt")]);
|
||||
assert_eq!(wanted, [choice("model", "gpt"), choice(&mode, "read-only")]);
|
||||
assert_eq!(asking_choices(&codex, &[choice(&mode, "ask")]), [choice(&mode, "read-only")]);
|
||||
// Claude Code's Accept Edits doesn't ask: default does.
|
||||
let claude = options_of(&json!({"modes": {"currentModeId": "acceptEdits",
|
||||
"availableModes": [{"id": "default"}, {"id": "acceptEdits"}, {"id": "plan"}, {"id": "bypassPermissions"}]}}));
|
||||
assert_eq!(asking_choices(&claude, &[]), [choice(&claude[0].id, "default")]);
|
||||
assert!(!keeps_asking(&claude));
|
||||
let mut safe = claude.clone();
|
||||
keep_asking(&mut safe);
|
||||
assert!(keeps_asking(&safe));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn effort_and_fast_categories_are_inferred_from_ids() {
|
||||
let mut c = options_of(&json!({
|
||||
|
||||
@@ -70,6 +70,8 @@ pub(crate) const LIMITS_UPDATE: &str = "openidea_limits";
|
||||
/// A native agent's own update: the background tasks its session runs
|
||||
/// (see [`TaskState::background_tasks`]).
|
||||
pub(crate) const BACKGROUND_TASKS_UPDATE: &str = "openidea_background_tasks";
|
||||
/// A native agent's diagnostic, including warnings emitted before a session exists.
|
||||
pub(crate) const WARNING_NOTIFICATION: &str = "_openidea/warning";
|
||||
/// Referenced files up to this size are embedded in the prompt (when the agent takes it).
|
||||
const MAX_EMBED: u64 = 256 * 1024;
|
||||
/// How long a probe waits for the agent to answer `initialize`.
|
||||
@@ -208,20 +210,23 @@ 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>,
|
||||
) -> 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)
|
||||
};
|
||||
) -> 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) };
|
||||
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));
|
||||
servers
|
||||
let mut off = mcp::servers_off(&configured, overrides);
|
||||
if builtin_off {
|
||||
off.push(BUILTIN_SERVER.to_owned());
|
||||
}
|
||||
McpForSession { servers, off }
|
||||
}
|
||||
|
||||
fn known_config(&self, provider: &str) -> Vec<AgentConfigOption> {
|
||||
@@ -637,14 +642,9 @@ impl AgentManager {
|
||||
}
|
||||
offered = self.shared.known_commands(&provider);
|
||||
}
|
||||
for &(name, description) in builtin_commands(&provider) {
|
||||
if !offered.iter().any(|c| c.name == name) {
|
||||
offered.push(AgentCommand {
|
||||
name: name.to_owned(),
|
||||
description: description.to_owned(),
|
||||
hint: None,
|
||||
source: AgentCommandSource::Command,
|
||||
});
|
||||
for command in builtin_commands(&provider) {
|
||||
if !offered.iter().any(|c| c.name == command.name) {
|
||||
offered.push(command);
|
||||
}
|
||||
}
|
||||
if provider != "claude" && provider != "claude-acp" {
|
||||
@@ -894,7 +894,9 @@ impl AgentManager {
|
||||
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);
|
||||
// The source task's choices may change the project without asking; the side conversation asks.
|
||||
let wanted = config::asking_choices(&config, &req.config);
|
||||
config::keep_asking(&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",
|
||||
@@ -936,7 +938,7 @@ impl AgentManager {
|
||||
task: task.clone(),
|
||||
session_id: None,
|
||||
entries: Vec::new(),
|
||||
wanted: req.config,
|
||||
wanted,
|
||||
before,
|
||||
saved: None,
|
||||
touched: None,
|
||||
@@ -1053,6 +1055,15 @@ impl AgentManager {
|
||||
if !o.values.iter().any(|v| v.value == value) {
|
||||
return Err(IdeError::invalid(format!("{} has no value {value}", o.name)));
|
||||
}
|
||||
if s.ephemeral {
|
||||
let mut next = s.task.config.clone();
|
||||
if let Some(n) = next.iter_mut().find(|n| n.id == option) {
|
||||
n.current = Some(value.clone());
|
||||
}
|
||||
if !config::keeps_asking(&next) {
|
||||
return Err(IdeError::invalid("a side conversation asks before changing anything"));
|
||||
}
|
||||
}
|
||||
o.clone()
|
||||
};
|
||||
let previous = target.current.clone();
|
||||
@@ -1141,7 +1152,11 @@ impl AgentManager {
|
||||
.peer
|
||||
.request(
|
||||
"session/fork",
|
||||
json!({ "sessionId": live.session, "cwd": cwd_s, "mcpServers": mcp_servers }),
|
||||
{
|
||||
let mut params = session_params(&cwd_s, &mcp_servers);
|
||||
params["sessionId"] = json!(live.session);
|
||||
params
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
@@ -2314,7 +2329,8 @@ impl Task {
|
||||
let mut session = None;
|
||||
if let (Some(id), true) = (saved, can_load) {
|
||||
self.replaying.store(true, Ordering::Release);
|
||||
let params = json!({ "sessionId": &id, "cwd": &cwd_s, "mcpServers": &mcp_servers });
|
||||
let mut params = session_params(&cwd_s, &mcp_servers);
|
||||
params["sessionId"] = json!(&id);
|
||||
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);
|
||||
@@ -2327,7 +2343,7 @@ impl Task {
|
||||
let (session_id, result) = match session {
|
||||
Some(s) => s,
|
||||
None => {
|
||||
let params = json!({ "cwd": &cwd_s, "mcpServers": &mcp_servers });
|
||||
let params = session_params(&cwd_s, &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 },
|
||||
@@ -2368,7 +2384,10 @@ impl Task {
|
||||
}
|
||||
let (mut options, mut wanted) = {
|
||||
let s = self.state.lock();
|
||||
(if known { reported } else { s.task.config.clone() }, s.wanted.clone())
|
||||
let options = if known { reported } else { s.task.config.clone() };
|
||||
// A side conversation asks before anything, whatever mode the agent starts in.
|
||||
let wanted = if s.ephemeral { config::asking_choices(&options, &s.wanted) } else { s.wanted.clone() };
|
||||
(options, wanted)
|
||||
};
|
||||
config::add_client_options(provider_id, &mut options);
|
||||
// Changing model can replace the effort / context-tier choices; validate those only afterwards.
|
||||
@@ -2415,6 +2434,14 @@ impl Task {
|
||||
Err(e) => tracing::warn!("agent task {}: setting {} to {} failed: {e}", self.id, o.id, choice.value),
|
||||
}
|
||||
}
|
||||
// A side conversation never runs in a mode that changes things without asking: when the
|
||||
// agent refused the switch, it doesn't start.
|
||||
if self.state.lock().ephemeral && !config::keeps_asking(&options) {
|
||||
return Err(SessionOpenError {
|
||||
message: "The agent didn't switch to a mode that asks before changing anything, so the side conversation can't start".into(),
|
||||
allow_acp_fallback: false,
|
||||
});
|
||||
}
|
||||
let model = model_of(&options).filter(|_| model_options);
|
||||
self.shared.remember(provider_id, Some(&options), None, model.as_deref());
|
||||
{
|
||||
@@ -2558,11 +2585,20 @@ impl Task {
|
||||
if let Some(title) = title {
|
||||
// Check and write under one lock: a rename landing between them would be lost.
|
||||
let mut s = self.state.lock();
|
||||
if !s.title_renamed && s.task.title != title {
|
||||
let user_named = update.get("userNamed").and_then(Value::as_bool) == Some(true);
|
||||
let flag_changed = user_named && !s.title_renamed;
|
||||
if user_named {
|
||||
s.title_renamed = true;
|
||||
}
|
||||
if (user_named || !s.title_renamed) && s.task.title != title {
|
||||
s.task.title = title.to_owned();
|
||||
drop(s);
|
||||
self.persist();
|
||||
self.emit_task();
|
||||
} else if flag_changed {
|
||||
drop(s);
|
||||
self.persist();
|
||||
self.emit_task();
|
||||
}
|
||||
}
|
||||
return;
|
||||
@@ -2912,6 +2948,15 @@ struct Client {
|
||||
|
||||
impl Handler for Client {
|
||||
fn on_notification(&self, method: &str, params: Value) {
|
||||
if method == WARNING_NOTIFICATION {
|
||||
if let Some(task) = self.task.upgrade()
|
||||
&& let Some(message) = params.get("message").and_then(Value::as_str).filter(|s| !s.trim().is_empty())
|
||||
{
|
||||
task.push_entry(AgentEntry::Error { message: message.to_owned() });
|
||||
task.persist();
|
||||
}
|
||||
return;
|
||||
}
|
||||
if method == "session/update"
|
||||
&& let (Some(task), Some(update)) = (self.task.upgrade(), params.get("update"))
|
||||
{
|
||||
@@ -3242,6 +3287,23 @@ 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
|
||||
}
|
||||
@@ -3275,13 +3337,20 @@ fn model_of(config: &[AgentConfigOption]) -> Option<String> {
|
||||
config.iter().find(|o| o.category.as_deref() == Some("model")).and_then(|o| o.current.clone())
|
||||
}
|
||||
|
||||
/// Commands the agent implements on its own and never lists in `availableCommands` —
|
||||
/// its CLI builtins, passed through as prompt text (e.g. `/compact`). `(name, description)`.
|
||||
fn builtin_commands(provider: &str) -> &'static [(&'static str, &'static str)] {
|
||||
/// Commands the agent implements on its own and never lists in `availableCommands`.
|
||||
fn builtin_commands(provider: &str) -> Vec<AgentCommand> {
|
||||
match provider {
|
||||
// Codex app-server has no command-list API, so the native adapter supplies its
|
||||
// stable builtins and merges the session's dynamic skills separately.
|
||||
"codex" => native::codex::builtin_commands(),
|
||||
// OpenCode ACP handles `/compact` via session.summarize but omits it from its command list.
|
||||
"opencode" => &[("compact", "compact the conversation")],
|
||||
_ => &[],
|
||||
"opencode" => vec![AgentCommand {
|
||||
name: "compact".into(),
|
||||
description: "compact the conversation".into(),
|
||||
hint: None,
|
||||
source: AgentCommandSource::Command,
|
||||
}],
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3343,6 +3412,9 @@ 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);
|
||||
|
||||
@@ -3357,7 +3429,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": "OpenIDEA", "command": command[0], "args": command[1..], "env": [] })]
|
||||
vec![json!({ "name": BUILTIN_SERVER, "command": command[0], "args": command[1..], "env": [] })]
|
||||
}
|
||||
|
||||
/// What was sent of a streaming message: its first `bytes` (`utf16` UTF-16 units), which
|
||||
|
||||
@@ -86,6 +86,29 @@ 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
|
||||
@@ -1016,6 +1039,44 @@ 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();
|
||||
|
||||
@@ -170,6 +170,8 @@ 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.
|
||||
@@ -344,9 +346,10 @@ impl Shim {
|
||||
cwd: PathBuf,
|
||||
start: Start,
|
||||
pending: bool,
|
||||
mcp_config: Option<String>,
|
||||
params: &Value,
|
||||
) -> Arc<Session> {
|
||||
let mcp_config = mcp_config.and_then(|json| match write_mcp_config(&json) {
|
||||
let mcp_off = mcp_off(params);
|
||||
let mcp_config = mcp_config(params).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}");
|
||||
@@ -356,6 +359,7 @@ 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,
|
||||
@@ -411,13 +415,8 @@ 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,
|
||||
mcp_config(¶ms),
|
||||
);
|
||||
let session =
|
||||
self.add_session(&id, self.cwd_of(¶ms), Start::New { id: id.clone() }, false, ¶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() }))
|
||||
@@ -433,7 +432,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, mcp_config(¶ms));
|
||||
let session = self.add_session(id, cwd, start, pending, ¶ms);
|
||||
rt.block_on(session.ensure()).map_err(|e| self.start_error(&session, e))?;
|
||||
if method == "session/load" {
|
||||
session.replay(&chain);
|
||||
@@ -459,7 +458,7 @@ impl Shim {
|
||||
(start, st.settings.clone())
|
||||
};
|
||||
self.save_pending(&id, Some(&start));
|
||||
let session = self.add_session(&id, source.cwd.clone(), start, true, mcp_config(¶ms));
|
||||
let session = self.add_session(&id, source.cwd.clone(), start, true, ¶ms);
|
||||
session.st.lock().settings = settings;
|
||||
let options = session.st.lock().settings.options();
|
||||
Ok(json!({ "sessionId": id, "configOptions": options }))
|
||||
@@ -666,6 +665,9 @@ 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() };
|
||||
@@ -1497,6 +1499,24 @@ 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,10 +48,17 @@ impl Settings {
|
||||
.filter_map(|m| {
|
||||
let s = |k: &str| m.get(k).and_then(Value::as_str).map(str::to_owned);
|
||||
let value = s("value")?;
|
||||
let resolved = s("resolvedModel");
|
||||
// The default entry follows the account's default model, so "Default
|
||||
// (recommended)" hides what actually runs: name the model it resolves to.
|
||||
let name = match (value.as_str(), resolved.as_deref()) {
|
||||
("default", Some(r)) if !r.is_empty() => format!("Default ({r})"),
|
||||
_ => s("displayName").unwrap_or_else(|| value.clone()),
|
||||
};
|
||||
Some(Model {
|
||||
name: s("displayName").unwrap_or_else(|| value.clone()),
|
||||
name,
|
||||
description: s("description"),
|
||||
resolved: s("resolvedModel"),
|
||||
resolved,
|
||||
efforts: if m.get("supportsEffort").and_then(Value::as_bool) == Some(true) {
|
||||
m.get("supportedEffortLevels")
|
||||
.and_then(Value::as_array)
|
||||
@@ -230,6 +237,19 @@ mod tests {
|
||||
assert_eq!(s.model, "claude-x-1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_default_entry_is_named_by_the_model_it_runs() {
|
||||
let s = Settings::from_cli(&init(), &json!({"applied": {"model": "claude-sonnet-5-5"}}));
|
||||
let names: Vec<_> = s.models.iter().map(|m| m.name.as_str()).collect();
|
||||
assert_eq!(names, ["Default (claude-sonnet-5-5)", "Opus", "Haiku 4.5"]);
|
||||
// Without a resolved model, the agent's own name stands.
|
||||
let s = Settings::from_cli(
|
||||
&json!({"models": [{"value": "default", "displayName": "Default (recommended)"}]}),
|
||||
&json!({}),
|
||||
);
|
||||
assert_eq!(s.models[0].name, "Default (recommended)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn options_follow_the_model() {
|
||||
let mut s = Settings::from_cli(&init(), &json!({"applied": {"model": "claude-sonnet-5-5", "effort": "high"}}));
|
||||
|
||||
@@ -1243,6 +1243,13 @@ 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);
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
//! Codex's built-in slash commands. `codex app-server` has no command-list API, so the
|
||||
//! native adapter owns this stable compatibility table; skills stay dynamic via `skills/list`.
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
/// Menu metadata shared by agent_commands and the prompt dispatcher.
|
||||
pub(crate) struct BuiltinCommandSpec {
|
||||
pub name: &'static str,
|
||||
pub description: &'static str,
|
||||
pub hint: Option<&'static str>,
|
||||
}
|
||||
|
||||
pub(crate) const BUILTIN_COMMANDS: &[BuiltinCommandSpec] = &[
|
||||
BuiltinCommandSpec { name: "plan", description: "Turn plan mode on or off.", hint: None },
|
||||
BuiltinCommandSpec {
|
||||
name: "mcp",
|
||||
description: "Show the status of the MCP servers, or reconnect them.",
|
||||
hint: Some("[reconnect]"),
|
||||
},
|
||||
BuiltinCommandSpec { name: "skills", description: "List available skills.", hint: None },
|
||||
BuiltinCommandSpec { name: "status", description: "Display session configuration and token usage.", hint: None },
|
||||
BuiltinCommandSpec {
|
||||
name: "review",
|
||||
description: "Review uncommitted changes, or review with custom instructions.",
|
||||
hint: Some("optional review instructions"),
|
||||
},
|
||||
BuiltinCommandSpec {
|
||||
name: "review-branch",
|
||||
description: "Review changes relative to a base branch.",
|
||||
hint: Some("branch name"),
|
||||
},
|
||||
BuiltinCommandSpec { name: "review-commit", description: "Review a specific commit.", hint: Some("commit sha") },
|
||||
BuiltinCommandSpec {
|
||||
name: "compact",
|
||||
description: "Summarize conversation to avoid hitting the context limit.",
|
||||
hint: None,
|
||||
},
|
||||
BuiltinCommandSpec {
|
||||
name: "goal",
|
||||
description: "Set a goal to keep pursuing.",
|
||||
hint: Some("[<objective>|clear|pause|resume]"),
|
||||
},
|
||||
BuiltinCommandSpec { name: "rename", description: "Rename the current session.", hint: Some("new name") },
|
||||
BuiltinCommandSpec {
|
||||
name: "logout",
|
||||
description: "Sign out of Codex. This option is available when you are logged in via ChatGPT.",
|
||||
hint: None,
|
||||
},
|
||||
];
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) enum BuiltinCommand {
|
||||
Plan,
|
||||
Mcp,
|
||||
Skills,
|
||||
Status,
|
||||
Review,
|
||||
ReviewBranch,
|
||||
ReviewCommit,
|
||||
Compact,
|
||||
Goal,
|
||||
Rename,
|
||||
Logout,
|
||||
}
|
||||
|
||||
impl BuiltinCommand {
|
||||
fn from_name(name: &str) -> Option<Self> {
|
||||
Some(match name {
|
||||
"plan" => Self::Plan,
|
||||
"mcp" => Self::Mcp,
|
||||
"skills" => Self::Skills,
|
||||
"status" => Self::Status,
|
||||
"review" => Self::Review,
|
||||
"review-branch" => Self::ReviewBranch,
|
||||
"review-commit" => Self::ReviewCommit,
|
||||
"compact" => Self::Compact,
|
||||
"goal" => Self::Goal,
|
||||
"rename" => Self::Rename,
|
||||
"logout" => Self::Logout,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(super) struct ParsedCommand {
|
||||
pub command: BuiltinCommand,
|
||||
/// Everything after the command name, trimmed but otherwise unchanged.
|
||||
pub rest: String,
|
||||
}
|
||||
|
||||
impl ParsedCommand {
|
||||
/// Commands that Codex completes as a turn. Missing review arguments stay local so the
|
||||
/// adapter can print the command's usage without starting an unnecessary model request.
|
||||
pub fn starts_turn(&self) -> bool {
|
||||
matches!(self.command, BuiltinCommand::Compact | BuiltinCommand::Review)
|
||||
|| (matches!(self.command, BuiltinCommand::ReviewBranch | BuiltinCommand::ReviewCommit)
|
||||
&& !self.rest.is_empty())
|
||||
}
|
||||
}
|
||||
|
||||
/// A recognized Codex builtin at the start of the prompt. Unknown slash commands and
|
||||
/// `$skill` invocations return `None`, so they continue through Codex as ordinary prompts.
|
||||
pub(super) fn parse(prompt: &Value) -> Option<ParsedCommand> {
|
||||
let text = prompt.as_array()?.first()?.get("text")?.as_str()?.trim();
|
||||
let command_text = text.strip_prefix('/')?.trim();
|
||||
let (name, rest) = command_text.split_once(char::is_whitespace).unwrap_or((command_text, ""));
|
||||
let command = BuiltinCommand::from_name(&name.to_ascii_lowercase())?;
|
||||
Some(ParsedCommand { command, rest: rest.trim().to_owned() })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn text(value: &str) -> Value {
|
||||
json!([{ "type": "text", "text": value }])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_builtin_is_registered_and_parsed() {
|
||||
let expected = [
|
||||
"plan",
|
||||
"mcp",
|
||||
"skills",
|
||||
"status",
|
||||
"review",
|
||||
"review-branch",
|
||||
"review-commit",
|
||||
"compact",
|
||||
"goal",
|
||||
"rename",
|
||||
"logout",
|
||||
];
|
||||
assert_eq!(BUILTIN_COMMANDS.iter().map(|c| c.name).collect::<Vec<_>>(), expected);
|
||||
for name in expected {
|
||||
assert!(parse(&text(&format!("/{name}"))).is_some(), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parsing_keeps_arguments_and_leaves_non_builtins_alone() {
|
||||
let parsed = parse(&text(" /review-branch origin/main ")).unwrap();
|
||||
assert_eq!(parsed.command, BuiltinCommand::ReviewBranch);
|
||||
assert_eq!(parsed.rest, "origin/main");
|
||||
assert!(parsed.starts_turn());
|
||||
assert!(!parse(&text("/review-branch")).unwrap().starts_turn());
|
||||
assert!(parse(&text("/$review check this")).is_none());
|
||||
assert!(parse(&text("review")).is_none());
|
||||
|
||||
let prompt = json!([{ "type": "text", "text": "/compact" }, { "type": "image", "data": "AA==" }]);
|
||||
assert_eq!(parse(&prompt).unwrap().command, BuiltinCommand::Compact);
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,11 @@
|
||||
//! translated to and from ACP. A codex thread is an ACP session; a subagent's thread is
|
||||
//! a subagent session of the thread that spawned it.
|
||||
|
||||
mod commands;
|
||||
mod translate;
|
||||
mod trust;
|
||||
|
||||
pub(crate) use commands::BUILTIN_COMMANDS;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -10,6 +14,8 @@ mod tests;
|
||||
use super::Shim;
|
||||
use crate::acp::AUTH_REQUIRED;
|
||||
use crate::provider::ProviderSpec;
|
||||
use crate::{AgentCommand, AgentCommandSource};
|
||||
use commands::{BuiltinCommand, ParsedCommand};
|
||||
use ide_jsonrpc::{Framing, Handler, Peer, RpcError, codes};
|
||||
use parking_lot::Mutex;
|
||||
use serde_json::{Value, json};
|
||||
@@ -32,6 +38,19 @@ const EXIT_GRACE: Duration = Duration::from_millis(100);
|
||||
const NAME_PROMPT: &str = "Name this conversation for a list of tasks: a short title of at most six words, in the \
|
||||
language the user writes in. Reply with the title only, without quotes or a closing period.";
|
||||
|
||||
/// Slash-command metadata for provider discovery and sessions without an advertised list.
|
||||
pub(crate) fn builtin_commands() -> Vec<AgentCommand> {
|
||||
BUILTIN_COMMANDS
|
||||
.iter()
|
||||
.map(|command| AgentCommand {
|
||||
name: command.name.to_owned(),
|
||||
description: command.description.to_owned(),
|
||||
hint: command.hint.map(str::to_owned),
|
||||
source: AgentCommandSource::Command,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(crate) fn connect(
|
||||
spec: &ProviderSpec,
|
||||
cwd: &Path,
|
||||
@@ -183,6 +202,8 @@ struct State {
|
||||
threads: HashMap<String, Thread>,
|
||||
/// The last `account/rateLimits/updated` snapshot.
|
||||
rate_limits: Option<Value>,
|
||||
/// Project trust has been checked (and, when needed, asked about) on this connection.
|
||||
trust_checked: HashSet<String>,
|
||||
/// Codex exited.
|
||||
gone: bool,
|
||||
}
|
||||
@@ -215,6 +236,8 @@ struct Thread {
|
||||
early_cancel: Option<Instant>,
|
||||
/// The latest agent message (a subagent's answer).
|
||||
answer: String,
|
||||
/// The latest `thread/tokenUsage/updated` payload, for the `/status` command.
|
||||
token_usage: Option<Value>,
|
||||
/// The thread has a name.
|
||||
named: bool,
|
||||
/// A name is being asked for.
|
||||
@@ -320,6 +343,12 @@ impl CodexShim {
|
||||
self.codex().request(method, params, None).await.map_err(from_codex)
|
||||
}
|
||||
|
||||
fn warning(&self, message: impl Into<String>) {
|
||||
if let Some(client) = self.client.get() {
|
||||
let _ = client.notify(crate::WARNING_NOTIFICATION, json!({ "message": message.into() }));
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle(&self, method: &str, params: Value) -> Result<Value, ResponseError> {
|
||||
match method {
|
||||
"initialize" => self.initialize().await,
|
||||
@@ -403,6 +432,7 @@ impl CodexShim {
|
||||
|
||||
async fn new_session(&self, params: &Value) -> Result<Value, ResponseError> {
|
||||
let models = self.models().await?;
|
||||
self.prepare_project_trust(params).await;
|
||||
let mut request = json!({ "cwd": params.get("cwd") });
|
||||
if let Some(config) = translate::mcp_config(params) {
|
||||
request["config"] = config;
|
||||
@@ -420,6 +450,7 @@ impl CodexShim {
|
||||
async fn load_session(&self, params: &Value) -> Result<Value, ResponseError> {
|
||||
let id = str_param(params, "sessionId")?;
|
||||
let models = self.models().await?;
|
||||
self.prepare_project_trust(params).await;
|
||||
let mut request = json!({ "threadId": id, "cwd": params.get("cwd") });
|
||||
if let Some(config) = translate::mcp_config(params) {
|
||||
request["config"] = config;
|
||||
@@ -438,6 +469,7 @@ impl CodexShim {
|
||||
async fn fork_session(&self, params: &Value) -> Result<Value, ResponseError> {
|
||||
let source = str_param(params, "sessionId")?;
|
||||
let models = self.models().await?;
|
||||
self.prepare_project_trust(params).await;
|
||||
let settings = self.state.lock().threads.get(source).and_then(|t| t.settings.clone());
|
||||
let mut request = json!({ "threadId": source, "cwd": params.get("cwd") });
|
||||
if let Some(config) = translate::mcp_config(params) {
|
||||
@@ -471,11 +503,18 @@ impl CodexShim {
|
||||
|
||||
async fn prompt(&self, params: &Value) -> Result<Value, ResponseError> {
|
||||
let session = str_param(params, "sessionId")?.to_owned();
|
||||
let input = translate::user_input(params.get("prompt").unwrap_or(&Value::Null));
|
||||
let prompt = params.get("prompt").unwrap_or(&Value::Null);
|
||||
let command = commands::parse(prompt);
|
||||
if let Some(command) = command.as_ref()
|
||||
&& !command.starts_turn()
|
||||
{
|
||||
return self.local_command(&session, command).await;
|
||||
}
|
||||
let input = translate::user_input(prompt);
|
||||
if input.is_empty() {
|
||||
return Err(invalid("empty prompt"));
|
||||
}
|
||||
let models = self.models().await?;
|
||||
let models = if command.is_none() { Some(self.models().await?) } else { None };
|
||||
let (done, ended) = oneshot::channel();
|
||||
let settings = {
|
||||
let mut state = self.state.lock();
|
||||
@@ -491,33 +530,213 @@ impl CodexShim {
|
||||
t.error = None;
|
||||
t.settings.clone()
|
||||
};
|
||||
let mut request = json!({ "threadId": session, "input": input, "summary": "auto" });
|
||||
if let Some(s) = settings {
|
||||
request["model"] = json!(s.model_slug(&models));
|
||||
request["approvalPolicy"] = json!(s.mode.approval_policy());
|
||||
request["sandboxPolicy"] = s.mode.sandbox_policy();
|
||||
if let Some(effort) = &s.effort {
|
||||
request["effort"] = json!(effort);
|
||||
let started = match command.as_ref() {
|
||||
Some(command) => match command.command {
|
||||
BuiltinCommand::Compact => {
|
||||
// Codex reports compaction as its own turn, using the same started/completed
|
||||
// notifications that finish the pending session/prompt above.
|
||||
self.call("thread/compact/start", json!({ "threadId": session })).await
|
||||
}
|
||||
BuiltinCommand::Review | BuiltinCommand::ReviewBranch | BuiltinCommand::ReviewCommit => {
|
||||
self.call("review/start", json!({ "threadId": session, "target": review_target(command) })).await
|
||||
}
|
||||
_ => unreachable!("local commands return before a pending turn is created"),
|
||||
},
|
||||
None => {
|
||||
let models = models.expect("ordinary prompts load the model catalog");
|
||||
let mut request = json!({ "threadId": session, "input": input, "summary": "auto" });
|
||||
if let Some(s) = &settings {
|
||||
request["model"] = json!(s.model_slug(&models));
|
||||
request["approvalPolicy"] = json!(s.mode.approval_policy());
|
||||
request["sandboxPolicy"] = s.mode.sandbox_policy();
|
||||
// Omit the default so older app-server versions keep accepting normal
|
||||
// turns; selecting Plan opts into this newer request field.
|
||||
if s.collaboration_mode == translate::PLAN_COLLABORATION_MODE
|
||||
|| s.collaboration_mode_override.is_some()
|
||||
{
|
||||
request["collaborationMode"] = translate::collaboration_mode(s, &models);
|
||||
}
|
||||
if let Some(effort) = &s.effort {
|
||||
request["effort"] = json!(effort);
|
||||
}
|
||||
}
|
||||
self.call("turn/start", request).await
|
||||
}
|
||||
};
|
||||
if let Ok(started) = &started
|
||||
&& let Some(turn) = started.pointer("/turn/id").and_then(Value::as_str)
|
||||
{
|
||||
self.turn_known(&session, turn, false);
|
||||
}
|
||||
match self.call("turn/start", request).await {
|
||||
Ok(started) => {
|
||||
if let Some(turn) = started.pointer("/turn/id").and_then(Value::as_str) {
|
||||
self.turn_known(&session, turn, false);
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
if let Some(t) = self.state.lock().threads.get_mut(&session) {
|
||||
t.prompt = None;
|
||||
}
|
||||
return Err(e);
|
||||
if started.is_ok()
|
||||
&& command.is_none()
|
||||
&& let Some(thread) = self.state.lock().threads.get_mut(&session)
|
||||
&& let Some(settings) = thread.settings.as_mut()
|
||||
{
|
||||
// A Default override is needed only for the first turn that resets a resumed
|
||||
// Plan thread; omitting it afterwards preserves compatibility with older Codex.
|
||||
settings.collaboration_mode_override = None;
|
||||
}
|
||||
if let Err(e) = started {
|
||||
if let Some(t) = self.state.lock().threads.get_mut(&session) {
|
||||
t.prompt = None;
|
||||
}
|
||||
return Err(e);
|
||||
}
|
||||
let (turn, last_error) = ended.await.map_err(|_| error(codes::INTERNAL_ERROR, "Codex exited"))?;
|
||||
let rate_limits = self.state.lock().rate_limits.clone();
|
||||
stop_reason(&turn, last_error, rate_limits.as_ref())
|
||||
}
|
||||
|
||||
/// Runs commands that codex-acp historically handled locally: configuration, status,
|
||||
/// inventory, naming and account actions. They complete without starting a model turn.
|
||||
async fn local_command(&self, session: &str, command: &ParsedCommand) -> Result<Value, ResponseError> {
|
||||
let (settings, cwd, token_usage, rate_limits) = {
|
||||
let state = self.state.lock();
|
||||
if state.gone {
|
||||
return Err(error(codes::INTERNAL_ERROR, "Codex exited"));
|
||||
}
|
||||
let thread = state.threads.get(session).ok_or_else(|| invalid(format!("no session {session}")))?;
|
||||
if thread.prompt.is_some() || thread.turn.is_some() {
|
||||
return Err(invalid("a turn is already running"));
|
||||
}
|
||||
(thread.settings.clone(), thread.cwd.clone(), thread.token_usage.clone(), state.rate_limits.clone())
|
||||
};
|
||||
|
||||
match command.command {
|
||||
BuiltinCommand::Plan => {
|
||||
if !command.rest.is_empty() {
|
||||
self.say(session, command_usage(BuiltinCommand::Plan));
|
||||
return Ok(json!({ "stopReason": "end_turn" }));
|
||||
}
|
||||
let models = self.models().await?;
|
||||
let options = {
|
||||
let mut state = self.state.lock();
|
||||
let thread =
|
||||
state.threads.get_mut(session).ok_or_else(|| invalid(format!("no session {session}")))?;
|
||||
let settings = thread.settings.as_mut().ok_or_else(|| invalid(format!("no session {session}")))?;
|
||||
settings.collaboration_mode = if settings.collaboration_mode == translate::PLAN_COLLABORATION_MODE {
|
||||
translate::DEFAULT_COLLABORATION_MODE.to_owned()
|
||||
} else {
|
||||
translate::PLAN_COLLABORATION_MODE.to_owned()
|
||||
};
|
||||
settings.collaboration_mode_override = Some(settings.collaboration_mode.clone());
|
||||
translate::config_options(&models, settings)
|
||||
};
|
||||
self.emit(session, json!({ "sessionUpdate": "config_option_update", "configOptions": options }));
|
||||
}
|
||||
BuiltinCommand::Status => {
|
||||
let text =
|
||||
status_text(session, settings.as_ref(), cwd.as_deref(), token_usage.as_ref(), rate_limits.as_ref());
|
||||
self.say(session, text);
|
||||
}
|
||||
BuiltinCommand::Skills => {
|
||||
let cwd = cwd.ok_or_else(|| invalid(format!("no session {session}")))?;
|
||||
let found = self.call("skills/list", json!({ "cwds": [cwd] })).await?;
|
||||
self.say(session, skills_text(&found));
|
||||
}
|
||||
BuiltinCommand::Mcp => match command.rest.as_str() {
|
||||
"" => self.say(session, self.mcp_text(session).await?),
|
||||
rest if rest.eq_ignore_ascii_case("reconnect") => {
|
||||
self.call("config/mcpServer/reload", json!({})).await?;
|
||||
self.say(session, self.mcp_text(session).await?);
|
||||
}
|
||||
_ => self.say(session, command_usage(BuiltinCommand::Mcp)),
|
||||
},
|
||||
BuiltinCommand::Rename => {
|
||||
if command.rest.is_empty() {
|
||||
self.say(session, command_usage(BuiltinCommand::Rename));
|
||||
} else {
|
||||
self.call("thread/name/set", json!({ "threadId": session, "name": command.rest })).await?;
|
||||
// User commands are authoritative over the automatic title, so the manager
|
||||
// must retain this title through later generated-name updates.
|
||||
self.emit(
|
||||
session,
|
||||
json!({ "sessionUpdate": "session_info_update", "title": command.rest, "userNamed": true }),
|
||||
);
|
||||
}
|
||||
}
|
||||
BuiltinCommand::Logout => {
|
||||
self.call("account/logout", Value::Null).await?;
|
||||
self.say(session, "Logged out from Codex account.");
|
||||
}
|
||||
BuiltinCommand::Goal => self.goal_command(session, &command.rest).await?,
|
||||
BuiltinCommand::ReviewBranch | BuiltinCommand::ReviewCommit if command.rest.is_empty() => {
|
||||
self.say(session, command_usage(command.command));
|
||||
}
|
||||
BuiltinCommand::ReviewBranch | BuiltinCommand::ReviewCommit => {
|
||||
return Err(invalid("review command did not start a turn"));
|
||||
}
|
||||
BuiltinCommand::Review | BuiltinCommand::Compact => {
|
||||
return Err(invalid("turn command reached the local command path"));
|
||||
}
|
||||
}
|
||||
Ok(json!({ "stopReason": "end_turn" }))
|
||||
}
|
||||
|
||||
async fn goal_command(&self, session: &str, rest: &str) -> Result<(), ResponseError> {
|
||||
let argument = rest.trim();
|
||||
if argument.is_empty() {
|
||||
self.say(session, command_usage(BuiltinCommand::Goal));
|
||||
return Ok(());
|
||||
}
|
||||
match argument.to_ascii_lowercase().as_str() {
|
||||
"clear" => {
|
||||
self.call("thread/goal/clear", json!({ "threadId": session })).await?;
|
||||
self.say(session, "Goal cleared.");
|
||||
}
|
||||
"pause" => {
|
||||
let response = self
|
||||
.call("thread/goal/set", json!({ "threadId": session, "status": "paused", "origin": "user" }))
|
||||
.await?;
|
||||
self.say(
|
||||
session,
|
||||
format!(
|
||||
"Goal is now {}.",
|
||||
response.pointer("/goal/status").and_then(Value::as_str).unwrap_or("paused")
|
||||
),
|
||||
);
|
||||
}
|
||||
"resume" => {
|
||||
let response = self
|
||||
.call("thread/goal/set", json!({ "threadId": session, "status": "active", "origin": "user" }))
|
||||
.await?;
|
||||
self.say(
|
||||
session,
|
||||
format!(
|
||||
"Goal is now {}.",
|
||||
response.pointer("/goal/status").and_then(Value::as_str).unwrap_or("active")
|
||||
),
|
||||
);
|
||||
}
|
||||
_ if argument.chars().count() > 4000 => {
|
||||
self.say(session, "Command \"/goal\" requires goal text of at most 4000 characters.");
|
||||
}
|
||||
_ => {
|
||||
let response = self
|
||||
.call(
|
||||
"thread/goal/set",
|
||||
json!({ "threadId": session, "objective": argument, "status": "active", "origin": "user" }),
|
||||
)
|
||||
.await?;
|
||||
let status = response.pointer("/goal/status").and_then(Value::as_str).unwrap_or("active");
|
||||
self.say(session, format!("Goal set and {status}."));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn mcp_text(&self, session: &str) -> Result<String, ResponseError> {
|
||||
let response = self
|
||||
.call("mcpServerStatus/list", json!({ "threadId": session, "detail": "toolsAndAuthOnly", "limit": 100 }))
|
||||
.await?;
|
||||
Ok(mcp_text(&response))
|
||||
}
|
||||
|
||||
fn say(&self, session: &str, text: impl AsRef<str>) {
|
||||
self.emit(session, translate::chunk("agent_message_chunk", text.as_ref()));
|
||||
}
|
||||
|
||||
async fn steer(&self, params: &Value) -> Result<Value, ResponseError> {
|
||||
let session = str_param(params, "sessionId")?;
|
||||
let turn = self.state.lock().threads.get(session).and_then(|t| t.turn.clone());
|
||||
@@ -643,6 +862,25 @@ impl CodexShim {
|
||||
fn on_codex_notification(self: &Arc<Self>, method: &str, params: &Value) {
|
||||
let thread = params.get("threadId").and_then(Value::as_str).unwrap_or_default();
|
||||
match method {
|
||||
"configWarning" => {
|
||||
let Some(summary) = params.get("summary").and_then(Value::as_str).filter(|s| !s.trim().is_empty())
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let mut message = summary.trim().to_owned();
|
||||
for key in ["details", "path"] {
|
||||
if let Some(value) = params.get(key).and_then(Value::as_str).filter(|s| !s.trim().is_empty()) {
|
||||
message.push_str("\n\n");
|
||||
message.push_str(value.trim());
|
||||
}
|
||||
}
|
||||
self.warning(message);
|
||||
}
|
||||
"warning" => {
|
||||
if let Some(message) = params.get("message").and_then(Value::as_str).filter(|s| !s.trim().is_empty()) {
|
||||
self.warning(message);
|
||||
}
|
||||
}
|
||||
"skills/changed" => {
|
||||
let shim = self.clone();
|
||||
let sessions: Vec<String> = self
|
||||
@@ -693,7 +931,12 @@ impl CodexShim {
|
||||
t.last_chunk = None;
|
||||
Some(translate::plan(params))
|
||||
}),
|
||||
"thread/tokenUsage/updated" => self.with_thread(thread, |_, _| translate::usage(params)),
|
||||
"thread/tokenUsage/updated" => self.with_thread(thread, |t, _| {
|
||||
if let Some(usage) = params.get("tokenUsage") {
|
||||
t.token_usage = Some(usage.clone());
|
||||
}
|
||||
translate::usage(params)
|
||||
}),
|
||||
"thread/name/updated" => self.with_thread(thread, |t, _| {
|
||||
let title = params.get("threadName").and_then(Value::as_str)?;
|
||||
t.named = true;
|
||||
@@ -1182,3 +1425,114 @@ fn stop_reason(turn: &Value, last_error: Option<Value>, rate_limits: Option<&Val
|
||||
};
|
||||
Ok(json!({ "stopReason": stop }))
|
||||
}
|
||||
|
||||
/// The `review/start` target of a parsed review command.
|
||||
fn review_target(command: &ParsedCommand) -> Value {
|
||||
match command.command {
|
||||
BuiltinCommand::Review if command.rest.is_empty() => json!({ "type": "uncommittedChanges" }),
|
||||
BuiltinCommand::Review => json!({ "type": "custom", "instructions": command.rest }),
|
||||
BuiltinCommand::ReviewBranch => json!({ "type": "baseBranch", "branch": command.rest }),
|
||||
BuiltinCommand::ReviewCommit => json!({ "type": "commit", "sha": command.rest, "title": null }),
|
||||
_ => unreachable!("only review commands have review targets"),
|
||||
}
|
||||
}
|
||||
|
||||
fn command_usage(command: BuiltinCommand) -> String {
|
||||
match command {
|
||||
BuiltinCommand::Plan => "Command \"/plan\" accepts no arguments.".to_owned(),
|
||||
BuiltinCommand::Mcp => "Command \"/mcp\" accepts no arguments, or `reconnect`.".to_owned(),
|
||||
BuiltinCommand::ReviewBranch => "Command \"/review-branch\" requires branch name.".to_owned(),
|
||||
BuiltinCommand::ReviewCommit => "Command \"/review-commit\" requires commit sha.".to_owned(),
|
||||
BuiltinCommand::Goal => "Command \"/goal\" requires [<objective>|clear|pause|resume].".to_owned(),
|
||||
BuiltinCommand::Rename => "Command \"/rename\" requires new name.".to_owned(),
|
||||
_ => "This command does not accept arguments.".to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
fn status_text(
|
||||
session: &str,
|
||||
settings: Option<&Settings>,
|
||||
cwd: Option<&str>,
|
||||
token_usage: Option<&Value>,
|
||||
rate_limits: Option<&Value>,
|
||||
) -> String {
|
||||
let mut lines = Vec::new();
|
||||
if let Some(settings) = settings {
|
||||
lines.push(format!("**Model:** {}", settings.model));
|
||||
lines.push(format!("**Collaboration:** {}", settings.collaboration_mode));
|
||||
lines.push(format!("**Approval:** {}", settings.mode.approval_policy()));
|
||||
lines.push(format!("**Sandbox:** {}", settings.mode.sandbox_mode()));
|
||||
}
|
||||
if let Some(cwd) = cwd {
|
||||
lines.push(format!("**Directory:** {cwd}"));
|
||||
}
|
||||
lines.push(format!("**Session:** `{session}`"));
|
||||
if let Some(usage) = token_usage {
|
||||
let total = usage.pointer("/total/totalTokens").and_then(Value::as_u64);
|
||||
let used = usage.pointer("/last/totalTokens").and_then(Value::as_u64);
|
||||
let window = usage.get("modelContextWindow").and_then(Value::as_u64).filter(|window| *window > 0);
|
||||
if let (Some(total), Some(used), Some(window)) = (total, used, window) {
|
||||
let percent = (used.saturating_mul(100) + window / 2) / window;
|
||||
lines.push(format!("**Token usage:** {total} total"));
|
||||
lines.push(format!("**Context window:** {used} / {window} ({percent}%)"));
|
||||
}
|
||||
}
|
||||
if let Some(primary) = rate_limits.and_then(|r| r.get("primary"))
|
||||
&& let Some(used) = primary.get("usedPercent").and_then(Value::as_f64)
|
||||
{
|
||||
lines.push(format!("**Rate limit:** {used:.0}% used"));
|
||||
}
|
||||
lines.join(" \n")
|
||||
}
|
||||
|
||||
fn skills_text(response: &Value) -> String {
|
||||
let mut seen = HashSet::new();
|
||||
let names: Vec<String> = response
|
||||
.get("data")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|entry| entry.get("skills").and_then(Value::as_array))
|
||||
.flatten()
|
||||
.filter(|skill| skill.get("enabled") != Some(&Value::Bool(false)))
|
||||
.filter_map(|skill| {
|
||||
let name = skill.get("name").and_then(Value::as_str)?.trim();
|
||||
if name.is_empty() || !seen.insert(name.to_owned()) {
|
||||
return None;
|
||||
}
|
||||
let description = skill
|
||||
.pointer("/interface/shortDescription")
|
||||
.or_else(|| skill.get("shortDescription"))
|
||||
.or_else(|| skill.get("description"))
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default();
|
||||
Some(if description.is_empty() { name.to_owned() } else { format!("{name}: {description}") })
|
||||
})
|
||||
.collect();
|
||||
if names.is_empty() {
|
||||
"No skills configured.".to_owned()
|
||||
} else {
|
||||
format!("Available skills:\n{}", names.iter().map(|name| format!("- {name}")).collect::<Vec<_>>().join("\n"))
|
||||
}
|
||||
}
|
||||
|
||||
fn mcp_text(response: &Value) -> String {
|
||||
let servers = response.get("data").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default();
|
||||
if servers.is_empty() {
|
||||
return "No MCP servers configured.".to_owned();
|
||||
}
|
||||
let lines = servers
|
||||
.iter()
|
||||
.filter_map(|server| {
|
||||
let name = server.get("name").and_then(Value::as_str)?;
|
||||
let status = server
|
||||
.get("runtimeStatus")
|
||||
.and_then(Value::as_str)
|
||||
.or_else(|| server.get("authStatus").and_then(Value::as_str))
|
||||
.unwrap_or("unknown");
|
||||
let tools = server.get("tools").and_then(Value::as_object).map_or(0, serde_json::Map::len);
|
||||
Some(format!("- {name}: {status}, {tools} tools"))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
format!("MCP servers:\n{}", lines.join("\n"))
|
||||
}
|
||||
@@ -180,24 +180,38 @@ fn settings_follow_the_thread_and_the_models() {
|
||||
let result = json!({"model": "big", "reasoningEffort": null, "approvalPolicy": "untrusted",
|
||||
"sandbox": {"type": "workspaceWrite"}});
|
||||
let mut s = Settings::of(&result, &models);
|
||||
assert_eq!(s, Settings { model: "big".into(), effort: Some("low".into()), mode: Mode::Ask });
|
||||
assert_eq!(
|
||||
s,
|
||||
Settings {
|
||||
model: "big".into(),
|
||||
effort: Some("low".into()),
|
||||
mode: Mode::Ask,
|
||||
collaboration_mode: DEFAULT_COLLABORATION_MODE.into(),
|
||||
collaboration_mode_override: None,
|
||||
}
|
||||
);
|
||||
|
||||
let options = config_options(&models, &s);
|
||||
let ids: Vec<&str> = options.as_array().unwrap().iter().map(|o| o["id"].as_str().unwrap()).collect();
|
||||
assert_eq!(ids, [MODEL, EFFORT, MODE]);
|
||||
assert_eq!(ids, [MODEL, EFFORT, MODE, COLLABORATION_MODE]);
|
||||
assert_eq!(options[0]["options"].as_array().unwrap().len(), 2, "hidden models are left out");
|
||||
assert_eq!(options[1]["category"], "thought_level");
|
||||
assert_eq!(options[1]["options"][1]["name"], "Extra high");
|
||||
assert_eq!(options[2]["currentValue"], "ask");
|
||||
assert_eq!(options[3]["currentValue"], "default");
|
||||
|
||||
// A model without efforts drops the option; its slug is what codex gets.
|
||||
s.set(&models, MODEL, "plain").unwrap();
|
||||
assert_eq!((s.effort.as_deref(), s.model_slug(&models).as_str()), (None, "plain-slug"));
|
||||
assert_eq!(config_options(&models, &s).as_array().unwrap().len(), 2);
|
||||
assert_eq!(config_options(&models, &s).as_array().unwrap().len(), 3);
|
||||
assert!(s.set(&models, EFFORT, "low").is_err());
|
||||
assert!(s.set(&models, MODEL, "nope").is_err());
|
||||
s.set(&models, MODE, "full-access").unwrap();
|
||||
assert_eq!((s.mode.approval_policy(), s.mode.sandbox_policy()), ("never", json!({"type": "dangerFullAccess"})));
|
||||
s.set(&models, COLLABORATION_MODE, PLAN_COLLABORATION_MODE).unwrap();
|
||||
assert_eq!(collaboration_mode(&s, &models)["mode"], PLAN_COLLABORATION_MODE);
|
||||
s.set(&models, COLLABORATION_MODE, DEFAULT_COLLABORATION_MODE).unwrap();
|
||||
assert_eq!(collaboration_mode(&s, &models)["mode"], DEFAULT_COLLABORATION_MODE);
|
||||
|
||||
// A model codex runs that it doesn't list is still offered.
|
||||
let s = Settings::of(&json!({"model": "custom", "sandbox": {"type": "readOnly"}}), &models);
|
||||
@@ -226,6 +240,18 @@ fn prompts_become_user_input() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compact_is_recognized_with_completion_whitespace_and_attachments() {
|
||||
// Completion leaves trailing whitespace and images can remain in the prompt. The first
|
||||
// text block still names the command; unknown slash-shaped text continues normally.
|
||||
assert_eq!(commands::parse(&text("/compact")).unwrap().command, BuiltinCommand::Compact);
|
||||
assert_eq!(commands::parse(&text(" /compact \n")).unwrap().command, BuiltinCommand::Compact);
|
||||
assert_eq!(commands::parse(&text("/compact now")).unwrap().rest, "now");
|
||||
let prompt = json!([{"type": "text", "text": "/compact"}, {"type": "image", "data": "AA=="}]);
|
||||
assert_eq!(commands::parse(&prompt).unwrap().command, BuiltinCommand::Compact);
|
||||
assert!(commands::parse(&text("x/compact")).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn commands_are_titled_by_what_they_do() {
|
||||
let cmd = |actions: Value| {
|
||||
@@ -453,6 +479,7 @@ fn history_replays_turns() {
|
||||
#[derive(Default)]
|
||||
struct Client {
|
||||
updates: Mutex<Vec<Value>>,
|
||||
warnings: Mutex<Vec<Value>>,
|
||||
asked: Mutex<Vec<Value>>,
|
||||
/// Option ids to choose; `None` (or none left) cancels.
|
||||
answers: Mutex<VecDeque<Option<&'static str>>>,
|
||||
@@ -462,6 +489,8 @@ impl Handler for Client {
|
||||
fn on_notification(&self, method: &str, params: Value) {
|
||||
if method == "session/update" {
|
||||
self.updates.lock().push(params);
|
||||
} else if method == "_openidea/warning" {
|
||||
self.warnings.lock().push(params);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -527,6 +556,10 @@ async fn questions_share_one_card_and_keep_their_ids() {
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum Scenario {
|
||||
AuthFailure,
|
||||
Command(&'static str),
|
||||
Compact,
|
||||
PlanThenPrompt,
|
||||
PlanToggleThenPrompt,
|
||||
Interrupt,
|
||||
Resume,
|
||||
Steer,
|
||||
@@ -541,6 +574,10 @@ impl Scenario {
|
||||
fn file(self) -> &'static str {
|
||||
match self {
|
||||
Scenario::AuthFailure => "auth_failure",
|
||||
Scenario::Command(_) => "simple",
|
||||
Scenario::Compact => "simple",
|
||||
Scenario::PlanThenPrompt => "simple",
|
||||
Scenario::PlanToggleThenPrompt => "simple",
|
||||
Scenario::Interrupt => "interrupt",
|
||||
Scenario::Resume => "resume",
|
||||
Scenario::Steer => "steer",
|
||||
@@ -598,6 +635,21 @@ async fn drive(scenario: Scenario, acp: &Peer, client: &Client, cwd: &str, threa
|
||||
Scenario::AuthFailure | Scenario::Simple | Scenario::UsageLimit | Scenario::Subagent => {
|
||||
out.push(("prompt", request(acp, "session/prompt", prompt("Reply with the single word: hi")).await));
|
||||
}
|
||||
Scenario::Compact => {
|
||||
out.push(("prompt", request(acp, "session/prompt", prompt("/compact")).await));
|
||||
}
|
||||
Scenario::Command(command) => {
|
||||
out.push(("prompt", request(acp, "session/prompt", prompt(command)).await));
|
||||
}
|
||||
Scenario::PlanThenPrompt => {
|
||||
out.push(("plan", request(acp, "session/prompt", prompt("/plan")).await));
|
||||
out.push(("prompt", request(acp, "session/prompt", prompt("Reply with the single word: hi")).await));
|
||||
}
|
||||
Scenario::PlanToggleThenPrompt => {
|
||||
out.push(("plan", request(acp, "session/prompt", prompt("/plan")).await));
|
||||
out.push(("default", request(acp, "session/prompt", prompt("/plan")).await));
|
||||
out.push(("prompt", request(acp, "session/prompt", prompt("Reply with the single word: hi")).await));
|
||||
}
|
||||
Scenario::Interrupt => {
|
||||
out.push(("mode", request(acp, "session/set_config_option", set(MODE, "read-only")).await));
|
||||
let running = {
|
||||
@@ -665,6 +717,37 @@ fn load(name: &str) -> Transcript {
|
||||
Transcript { meta, frames }
|
||||
}
|
||||
|
||||
/// The simple fixture through session setup. Local commands add only the app-server calls
|
||||
/// they need after it; turn commands keep the fixture's turn notifications.
|
||||
fn command_transcript(calls: &[(&'static str, Value)]) -> Transcript {
|
||||
let mut transcript = load(Scenario::Simple.file());
|
||||
let prompt = transcript
|
||||
.frames
|
||||
.iter()
|
||||
.position(|(out, frame)| *out && frame["method"] == "turn/start")
|
||||
.expect("the scenario starts a turn");
|
||||
transcript.frames.truncate(prompt);
|
||||
transcript.frames.push((true, json!({ "id": 4, "method": "skills/list" })));
|
||||
transcript.frames.push((false, json!({ "id": 4, "result": { "data": [] } })));
|
||||
for (index, (method, result)) in calls.iter().enumerate() {
|
||||
let id = 10 + index;
|
||||
transcript.frames.push((true, json!({ "id": id, "method": method })));
|
||||
transcript.frames.push((false, json!({ "id": id, "result": result })));
|
||||
}
|
||||
transcript
|
||||
}
|
||||
|
||||
fn turn_command_transcript(method: &str) -> Transcript {
|
||||
let mut transcript = load(Scenario::Simple.file());
|
||||
let start = transcript
|
||||
.frames
|
||||
.iter_mut()
|
||||
.find(|(out, frame)| *out && frame["method"] == "turn/start")
|
||||
.expect("the scenario starts a turn");
|
||||
start.1["method"] = json!(method);
|
||||
transcript
|
||||
}
|
||||
|
||||
/// Plays codex: waits for each frame the shim should send, sends what codex sent.
|
||||
/// Returns the frames the shim sent.
|
||||
async fn play<R: AsyncRead + Unpin, W: AsyncWrite + Unpin>(
|
||||
@@ -684,10 +767,10 @@ async fn play<R: AsyncRead + Unpin, W: AsyncWrite + Unpin>(
|
||||
.unwrap()
|
||||
.unwrap_or_else(|| panic!("the shim closed before {frame}"));
|
||||
let actual: Value = serde_json::from_str(&line).unwrap();
|
||||
// Older recordings predate skill discovery and thread naming; play an
|
||||
// Older recordings predate config inspection, skill discovery and thread naming; play an
|
||||
// unsupported server.
|
||||
let method = actual["method"].as_str().unwrap_or_default();
|
||||
if matches!(method, "skills/list" | "thread/sample") && frame["method"] != method {
|
||||
if matches!(method, "config/read" | "skills/list" | "thread/sample") && frame["method"] != method {
|
||||
let reply = json!({ "id": actual["id"], "error": { "code": -32601, "message": "unsupported" } });
|
||||
write.write_all(format!("{reply}\n").as_bytes()).await.unwrap();
|
||||
continue;
|
||||
@@ -760,6 +843,149 @@ fn session_of(results: &Results, label: &str) -> String {
|
||||
result(results, label).as_ref().unwrap()["sessionId"].as_str().unwrap().to_owned()
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn configuration_warnings_before_a_session_and_runtime_warnings_reach_the_client() {
|
||||
let mut transcript = load(Scenario::Simple.file());
|
||||
transcript.frames.insert(
|
||||
0,
|
||||
(
|
||||
false,
|
||||
json!({"method": "configWarning", "params": {
|
||||
"summary": "Project-local config is disabled until the project is trusted.",
|
||||
"details": "Update the project's trust setting.", "path": "/work/.codex/config.toml"
|
||||
}}),
|
||||
),
|
||||
);
|
||||
let at = transcript.frames.iter().position(|(out, f)| *out && f["method"] == "turn/start").unwrap();
|
||||
transcript
|
||||
.frames
|
||||
.insert(at, (false, json!({"method": "warning", "params": {"message": "MCP server unavailable"}})));
|
||||
let (results, client, frames, _, _codex) = replay_transcript(Scenario::Simple, transcript).await;
|
||||
assert!(result(&results, "new").is_ok());
|
||||
assert_eq!(
|
||||
*client.warnings.lock(),
|
||||
[
|
||||
json!({"message": "Project-local config is disabled until the project is trusted.\n\nUpdate the project's trust setting.\n\n/work/.codex/config.toml"}),
|
||||
json!({"message": "MCP server unavailable"}),
|
||||
]
|
||||
);
|
||||
assert!(sent(&frames, "config/value/write").is_empty());
|
||||
assert!(sent(&frames, "config/batchWrite").is_empty());
|
||||
}
|
||||
|
||||
struct TrustServer {
|
||||
cwd: String,
|
||||
disabled: bool,
|
||||
other_project: bool,
|
||||
write_error: bool,
|
||||
overridden: bool,
|
||||
calls: Mutex<Vec<(String, Value)>>,
|
||||
}
|
||||
|
||||
impl Handler for TrustServer {
|
||||
fn on_notification(&self, _: &str, _: Value) {}
|
||||
|
||||
fn on_request(&self, method: &str, params: Value) -> Result<Value, (i64, String)> {
|
||||
self.calls.lock().push((method.to_owned(), params));
|
||||
match method {
|
||||
"initialize" => Ok(json!({})),
|
||||
"model/list" => Ok(json!({"data": []})),
|
||||
"config/read" => {
|
||||
let cwd =
|
||||
if self.other_project { Path::new(&self.cwd).join("other") } else { PathBuf::from(&self.cwd) };
|
||||
Ok(json!({"layers": [
|
||||
{"name": {"type": "user", "profile": null}, "version": "original"},
|
||||
{"name": {"type": "project", "dotCodexFolder": cwd.join(".codex")},
|
||||
"disabledReason": self.disabled.then_some("Project config is disabled until trusted.")}
|
||||
]}))
|
||||
}
|
||||
"config/value/write" if self.write_error => Err((-32001, "Config changed concurrently".into())),
|
||||
"config/value/write" => Ok(json!({"status": if self.overridden {"okOverridden"} else {"ok"}})),
|
||||
"thread/start" | "thread/resume" | "thread/fork" => {
|
||||
Ok(json!({"thread": {"id": "s", "turns": []}, "cwd": self.cwd}))
|
||||
}
|
||||
"skills/list" => Ok(json!({"data": []})),
|
||||
_ => Err((codes::METHOD_NOT_FOUND, method.to_owned())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn project_trust_is_confirmed_before_new_resumed_and_forked_sessions() {
|
||||
for method in ["session/new", "session/load", "session/fork"] {
|
||||
for (answer, disabled, other_project, write_error, overridden) in [
|
||||
(Some("codex-trust-project"), true, false, false, false),
|
||||
(Some("codex-keep-untrusted"), true, false, false, false),
|
||||
(None, true, false, false, false),
|
||||
(Some("codex-trust-project"), false, false, false, false),
|
||||
(Some("codex-trust-project"), true, true, false, false),
|
||||
(Some("codex-trust-project"), true, false, true, false),
|
||||
(Some("codex-trust-project"), true, false, false, true),
|
||||
] {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let cwd = tmp.path().join("project.with.dots-项目").to_string_lossy().into_owned();
|
||||
let server = Arc::new(TrustServer {
|
||||
cwd: cwd.clone(),
|
||||
disabled,
|
||||
other_project,
|
||||
write_error,
|
||||
overridden,
|
||||
calls: Mutex::default(),
|
||||
});
|
||||
let client = Arc::new(Client::default());
|
||||
client.answers.lock().push_back(answer);
|
||||
let (ours, theirs) = tokio::io::duplex(1 << 16);
|
||||
let (read, write) = tokio::io::split(theirs);
|
||||
let native = Peer::connect_framed(read, write, server.clone(), Framing::Lines);
|
||||
let acp = attach(client.clone(), |events| {
|
||||
let (read, write) = tokio::io::split(ours);
|
||||
Ok(Peer::connect_framed(read, write, events, Framing::Lines))
|
||||
})
|
||||
.unwrap();
|
||||
request(&acp, "initialize", json!({})).await.unwrap();
|
||||
let params = json!({"cwd": cwd, "sessionId": "source", "mcpServers": []});
|
||||
request(&acp, method, params.clone()).await.unwrap();
|
||||
// The same connection must not ask repeatedly after a decline.
|
||||
request(&acp, method, params).await.unwrap();
|
||||
let approved = answer == Some("codex-trust-project") && disabled && !other_project;
|
||||
{
|
||||
let asked = client.asked.lock();
|
||||
assert_eq!(asked.len(), usize::from(disabled && !other_project));
|
||||
if let Some(permission) = asked.first() {
|
||||
assert!(permission["toolCall"]["title"].as_str().unwrap().contains(&cwd));
|
||||
assert_eq!(
|
||||
permission["toolCall"]["kind"], "edit",
|
||||
"side conversations must deny persistent trust changes"
|
||||
);
|
||||
assert_eq!(
|
||||
permission["options"][0]["kind"], "allow_always",
|
||||
"task bypass must not grant permanent trust"
|
||||
);
|
||||
}
|
||||
let calls = server.calls.lock();
|
||||
let writes: Vec<_> = calls.iter().filter(|(m, _)| m == "config/value/write").collect();
|
||||
assert_eq!(writes.len(), usize::from(approved));
|
||||
if let Some((_, write)) = writes.first() {
|
||||
assert_eq!(
|
||||
*write,
|
||||
json!({"keyPath": format!("projects.{}.trust_level", json!(cwd)), "value": "trusted", "mergeStrategy": "replace", "expectedVersion": "original"})
|
||||
);
|
||||
let written = calls.iter().position(|(m, _)| m == "config/value/write").unwrap();
|
||||
let started = calls.iter().position(|(m, _)| m.starts_with("thread/")).unwrap();
|
||||
assert!(written < started, "the session must load config after the write");
|
||||
}
|
||||
}
|
||||
// Drain notifications sent before the last response.
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
if approved && (write_error || overridden) {
|
||||
assert!(!client.warnings.lock().is_empty());
|
||||
}
|
||||
acp.kill();
|
||||
native.kill();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn auth_failure_names_auth() {
|
||||
let (results, _client, frames, _) = replay(Scenario::AuthFailure).await;
|
||||
@@ -771,7 +997,7 @@ async fn auth_failure_names_auth() {
|
||||
let categories: Vec<&str> =
|
||||
new["configOptions"].as_array().unwrap().iter().map(|o| o["category"].as_str().unwrap()).collect();
|
||||
// The model the user's codex config names; codex doesn't list it, so its efforts are unknown.
|
||||
assert_eq!(categories, ["model", "mode"]);
|
||||
assert_eq!(categories, ["model", "mode", "collaboration_mode"]);
|
||||
let model = new["configOptions"][0]["currentValue"].as_str().unwrap();
|
||||
assert_eq!(model, "gpt-6-luna");
|
||||
assert!(new["configOptions"][0]["options"].as_array().unwrap().iter().any(|o| o["value"] == model));
|
||||
@@ -1011,6 +1237,7 @@ async fn settings_apply_to_the_next_turn() {
|
||||
(starts[0]["params"]["model"].as_str(), starts[0]["params"]["effort"].as_str()),
|
||||
(Some("gpt-5.6-luna"), Some("medium"))
|
||||
);
|
||||
assert!(starts[0]["params"].get("collaborationMode").is_none());
|
||||
assert_eq!(
|
||||
(starts[1]["params"]["model"].as_str(), starts[1]["params"]["effort"].as_str()),
|
||||
(Some("gpt-5.5"), Some("high"))
|
||||
@@ -1019,6 +1246,192 @@ async fn settings_apply_to_the_next_turn() {
|
||||
assert_eq!(client.text(&session, "agent_message_chunk"), "oneOn it.\n\ntwo");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn compact_is_started_through_its_app_server_method() {
|
||||
// Play the ordinary-turn fixture with the request swapped: the notifications are the
|
||||
// same, while this pins the user-visible command to `thread/compact/start`, not a prompt.
|
||||
let mut transcript = load(Scenario::Simple.file());
|
||||
let start = transcript
|
||||
.frames
|
||||
.iter_mut()
|
||||
.find(|(out, frame)| *out && frame["method"] == "turn/start")
|
||||
.expect("the scenario starts a turn");
|
||||
start.1["method"] = json!("thread/compact/start");
|
||||
let (results, _client, frames, _meta, _codex) = replay_transcript(Scenario::Compact, transcript).await;
|
||||
|
||||
assert_eq!(result(&results, "prompt").as_ref().unwrap(), &json!({"stopReason": "end_turn"}));
|
||||
assert!(sent(&frames, "turn/start").is_empty());
|
||||
assert_eq!(sent(&frames, "thread/compact/start").len(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn review_commands_start_the_matching_review_target() {
|
||||
for (prompt, target) in [
|
||||
("/review", json!({ "type": "uncommittedChanges" })),
|
||||
("/review focus on errors", json!({ "type": "custom", "instructions": "focus on errors" })),
|
||||
("/review-branch origin/main", json!({ "type": "baseBranch", "branch": "origin/main" })),
|
||||
("/review-commit abc123", json!({ "type": "commit", "sha": "abc123", "title": null })),
|
||||
] {
|
||||
let (results, _client, frames, _meta, _codex) =
|
||||
replay_transcript(Scenario::Command(prompt), turn_command_transcript("review/start")).await;
|
||||
assert_eq!(result(&results, "prompt").as_ref().unwrap(), &json!({ "stopReason": "end_turn" }), "{prompt}");
|
||||
assert!(sent(&frames, "turn/start").is_empty(), "{prompt}");
|
||||
assert_eq!(sent(&frames, "review/start")[0]["params"]["target"], target, "{prompt}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn plan_toggles_collaboration_mode_and_updates_the_composer() {
|
||||
let (results, client, _frames, _meta, _codex) =
|
||||
replay_transcript(Scenario::Command("/plan"), command_transcript(&[])).await;
|
||||
let session = session_of(&results, "new");
|
||||
assert_eq!(result(&results, "prompt").as_ref().unwrap(), &json!({ "stopReason": "end_turn" }));
|
||||
let update = client.of(&session).into_iter().find(|u| u["sessionUpdate"] == "config_option_update").unwrap();
|
||||
let plan =
|
||||
update["configOptions"].as_array().unwrap().iter().find(|o| o["category"] == "collaboration_mode").unwrap();
|
||||
assert_eq!(plan["currentValue"], "plan");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn plan_applies_to_the_next_normal_turn() {
|
||||
let (results, _client, frames, _meta, _codex) =
|
||||
replay_transcript(Scenario::PlanThenPrompt, load(Scenario::Simple.file())).await;
|
||||
assert_eq!(result(&results, "plan").as_ref().unwrap(), &json!({ "stopReason": "end_turn" }));
|
||||
assert_eq!(result(&results, "prompt").as_ref().unwrap(), &json!({ "stopReason": "end_turn" }));
|
||||
let start = sent(&frames, "turn/start")[0];
|
||||
assert_eq!(start["params"]["collaborationMode"]["mode"], "plan");
|
||||
assert_eq!(start["params"]["collaborationMode"]["settings"]["model"], "gpt-5.6-luna");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn toggling_plan_off_sends_an_explicit_default_once() {
|
||||
let (results, _client, frames, _meta, _codex) =
|
||||
replay_transcript(Scenario::PlanToggleThenPrompt, load(Scenario::Simple.file())).await;
|
||||
assert_eq!(result(&results, "default").as_ref().unwrap(), &json!({ "stopReason": "end_turn" }));
|
||||
let start = sent(&frames, "turn/start")[0];
|
||||
assert_eq!(start["params"]["collaborationMode"]["mode"], "default");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn informational_commands_report_skills_mcp_and_status() {
|
||||
let skills = json!({ "data": [{ "skills": [
|
||||
{ "name": "review", "enabled": true, "description": "Review changes" },
|
||||
{ "name": "hidden", "enabled": false, "description": "Hidden" }
|
||||
] }] });
|
||||
let servers = json!({ "data": [
|
||||
{ "name": "github", "runtimeStatus": "connected", "authStatus": "oAuth", "tools": { "search": {} } },
|
||||
{ "name": "docs", "runtimeStatus": "failed", "authStatus": "unknown", "tools": {} }
|
||||
] });
|
||||
for (prompt, method, response, expected) in [
|
||||
("/skills", "skills/list", skills, "Available skills:\n- review: Review changes"),
|
||||
(
|
||||
"/mcp",
|
||||
"mcpServerStatus/list",
|
||||
servers,
|
||||
"MCP servers:\n- github: connected, 1 tools\n- docs: failed, 0 tools",
|
||||
),
|
||||
("/status", "", Value::Null, "**Session:**"),
|
||||
] {
|
||||
let calls: &[(&str, Value)] = if method.is_empty() { &[] } else { &[(method, response)] };
|
||||
let calls: Vec<(&'static str, Value)> = calls
|
||||
.iter()
|
||||
.map(|(method, response)| {
|
||||
let method = match *method {
|
||||
"skills/list" => "skills/list",
|
||||
"mcpServerStatus/list" => "mcpServerStatus/list",
|
||||
other => panic!("unexpected method {other}"),
|
||||
};
|
||||
(method, response.clone())
|
||||
})
|
||||
.collect();
|
||||
let (results, client, _frames, _meta, _codex) =
|
||||
replay_transcript(Scenario::Command(prompt), command_transcript(&calls)).await;
|
||||
let session = session_of(&results, "new");
|
||||
assert_eq!(result(&results, "prompt").as_ref().unwrap(), &json!({ "stopReason": "end_turn" }));
|
||||
assert!(client.text(&session, "agent_message_chunk").contains(expected), "{prompt}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn rename_and_logout_use_their_app_server_actions() {
|
||||
let (results, client, frames, _meta, _codex) = replay_transcript(
|
||||
Scenario::Command("/rename Better name"),
|
||||
command_transcript(&[("thread/name/set", json!({}))]),
|
||||
)
|
||||
.await;
|
||||
let session = session_of(&results, "new");
|
||||
assert_eq!(sent(&frames, "thread/name/set")[0]["params"], json!({ "threadId": session, "name": "Better name" }));
|
||||
let info = client.of(&session).into_iter().find(|u| u["sessionUpdate"] == "session_info_update").unwrap();
|
||||
assert_eq!((info["title"].as_str(), info["userNamed"].as_bool()), (Some("Better name"), Some(true)));
|
||||
|
||||
let (results, client, frames, _meta, _codex) =
|
||||
replay_transcript(Scenario::Command("/logout"), command_transcript(&[("account/logout", json!({}))])).await;
|
||||
let session = session_of(&results, "new");
|
||||
assert_eq!(sent(&frames, "account/logout").len(), 1);
|
||||
assert_eq!(client.text(&session, "agent_message_chunk"), "Logged out from Codex account.");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn goal_commands_set_pause_resume_and_clear_through_app_server() {
|
||||
for (prompt, method, params, result) in [
|
||||
(
|
||||
"/goal fix the failing tests",
|
||||
"thread/goal/set",
|
||||
json!({ "threadId": "s", "objective": "fix the failing tests", "status": "active", "origin": "user" }),
|
||||
json!({ "goal": { "status": "active" } }),
|
||||
),
|
||||
(
|
||||
"/goal pause",
|
||||
"thread/goal/set",
|
||||
json!({ "threadId": "s", "status": "paused", "origin": "user" }),
|
||||
json!({ "goal": { "status": "paused" } }),
|
||||
),
|
||||
(
|
||||
"/goal resume",
|
||||
"thread/goal/set",
|
||||
json!({ "threadId": "s", "status": "active", "origin": "user" }),
|
||||
json!({ "goal": { "status": "active" } }),
|
||||
),
|
||||
("/goal clear", "thread/goal/clear", json!({ "threadId": "s" }), json!({ "cleared": true })),
|
||||
] {
|
||||
let (results, _client, frames, _meta, _codex) =
|
||||
replay_transcript(Scenario::Command(prompt), command_transcript(&[(method, result)])).await;
|
||||
let session = session_of(&results, "new");
|
||||
let sent = sent(&frames, method);
|
||||
assert_eq!(sent.len(), 1, "{prompt}");
|
||||
let mut expected = params;
|
||||
expected["threadId"] = json!(session);
|
||||
assert_eq!(sent[0]["params"], expected, "{prompt}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn missing_review_arguments_print_usage_without_starting_a_turn() {
|
||||
for prompt in ["/review-branch", "/review-commit", "/rename", "/goal"] {
|
||||
let (results, client, frames, _meta, _codex) =
|
||||
replay_transcript(Scenario::Command(prompt), command_transcript(&[])).await;
|
||||
let session = session_of(&results, "new");
|
||||
assert_eq!(result(&results, "prompt").as_ref().unwrap(), &json!({ "stopReason": "end_turn" }));
|
||||
assert!(sent(&frames, "turn/start").is_empty());
|
||||
assert!(client.text(&session, "agent_message_chunk").starts_with("Command \""), "{prompt}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn mcp_reconnect_reloads_before_reporting_status() {
|
||||
let servers =
|
||||
json!({ "data": [{ "name": "github", "runtimeStatus": "connected", "authStatus": "oAuth", "tools": {} }] });
|
||||
let (results, client, frames, _meta, _codex) = replay_transcript(
|
||||
Scenario::Command("/mcp reconnect"),
|
||||
command_transcript(&[("config/mcpServer/reload", json!({})), ("mcpServerStatus/list", servers)]),
|
||||
)
|
||||
.await;
|
||||
let session = session_of(&results, "new");
|
||||
assert_eq!(sent(&frames, "config/mcpServer/reload").len(), 1);
|
||||
assert_eq!(sent(&frames, "mcpServerStatus/list").len(), 1);
|
||||
assert!(client.text(&session, "agent_message_chunk").contains("github: connected"));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn approvals_are_asked_and_answered() {
|
||||
let (results, client, frames, _) = replay(Scenario::Approvals).await;
|
||||
|
||||
@@ -138,6 +138,12 @@ pub(super) struct Settings {
|
||||
pub model: String,
|
||||
pub effort: Option<String>,
|
||||
pub mode: Mode,
|
||||
/// Codex's Default/Plan collaboration mode. It is sent with each turn because it is
|
||||
/// part of the turn contract rather than the sandbox permission mode above.
|
||||
pub collaboration_mode: String,
|
||||
/// A mode just chosen by the user, sent once even when it is Default so a resumed Plan
|
||||
/// thread is explicitly reset. Subsequent default turns can omit the field again.
|
||||
pub collaboration_mode_override: Option<String>,
|
||||
}
|
||||
|
||||
impl Settings {
|
||||
@@ -156,6 +162,12 @@ impl Settings {
|
||||
result.get("approvalPolicy").unwrap_or(&Value::Null),
|
||||
result.get("sandbox").unwrap_or(&Value::Null),
|
||||
),
|
||||
collaboration_mode: result
|
||||
.pointer("/collaborationMode/mode")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or(DEFAULT_COLLABORATION_MODE)
|
||||
.to_owned(),
|
||||
collaboration_mode_override: None,
|
||||
};
|
||||
s.fit_effort(models);
|
||||
s
|
||||
@@ -194,6 +206,13 @@ impl Settings {
|
||||
self.effort = Some(value.to_owned());
|
||||
}
|
||||
MODE => self.mode = Mode::parse(value).ok_or_else(|| format!("unknown mode {value}"))?,
|
||||
COLLABORATION_MODE => {
|
||||
if !matches!(value, DEFAULT_COLLABORATION_MODE | PLAN_COLLABORATION_MODE) {
|
||||
return Err(format!("unknown collaboration mode {value}"));
|
||||
}
|
||||
self.collaboration_mode = value.to_owned();
|
||||
self.collaboration_mode_override = Some(value.to_owned());
|
||||
}
|
||||
_ => return Err(format!("unknown setting {option}")),
|
||||
}
|
||||
Ok(())
|
||||
@@ -203,6 +222,9 @@ impl Settings {
|
||||
pub(super) const MODEL: &str = "model";
|
||||
pub(super) const EFFORT: &str = "reasoning_effort";
|
||||
pub(super) const MODE: &str = "mode";
|
||||
pub(super) const COLLABORATION_MODE: &str = "collaboration_mode";
|
||||
pub(super) const DEFAULT_COLLABORATION_MODE: &str = "default";
|
||||
pub(super) const PLAN_COLLABORATION_MODE: &str = "plan";
|
||||
|
||||
/// ACP `configOptions`: model, reasoning effort (for models that have it) and mode.
|
||||
pub(super) fn config_options(models: &[ModelInfo], s: &Settings) -> Value {
|
||||
@@ -235,9 +257,32 @@ pub(super) fn config_options(models: &[ModelInfo], s: &Settings) -> Value {
|
||||
"id": MODE, "name": "Mode", "category": "mode", "type": "select", "currentValue": s.mode.id(),
|
||||
"options": Mode::ALL.iter().map(|m| select_value(m.id(), m.name(), Some(m.description()))).collect::<Vec<_>>(),
|
||||
}));
|
||||
out.push(json!({
|
||||
"id": COLLABORATION_MODE,
|
||||
"name": "Collaboration mode",
|
||||
"category": "collaboration_mode",
|
||||
"type": "select",
|
||||
"currentValue": s.collaboration_mode,
|
||||
"options": [
|
||||
select_value(DEFAULT_COLLABORATION_MODE, "Default", Some("Execute changes directly")),
|
||||
select_value(PLAN_COLLABORATION_MODE, "Plan", Some("Plan before making changes")),
|
||||
],
|
||||
}));
|
||||
Value::Array(out)
|
||||
}
|
||||
|
||||
/// `turn/start.collaborationMode`: the preset plus the selected model settings.
|
||||
pub(super) fn collaboration_mode(settings: &Settings, models: &[ModelInfo]) -> Value {
|
||||
json!({
|
||||
"mode": settings.collaboration_mode_override.as_deref().unwrap_or(&settings.collaboration_mode),
|
||||
"settings": {
|
||||
"model": settings.model_slug(models),
|
||||
"reasoning_effort": settings.effort,
|
||||
"developer_instructions": null,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
fn select_value(value: &str, name: &str, description: Option<&str>) -> Value {
|
||||
let mut v = json!({ "value": value, "name": name });
|
||||
if let Some(d) = description {
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
//! A project trusted by the IDE may still be untrusted by Codex. Ask before changing
|
||||
//! Codex's own decision; only its config API writes the current project's trust entry.
|
||||
|
||||
use super::*;
|
||||
|
||||
fn disabled_project<'a>(config: &'a Value, cwd: &str) -> Option<&'a Value> {
|
||||
let folder = Path::new(cwd).join(".codex");
|
||||
config.get("layers")?.as_array()?.iter().find(|layer| {
|
||||
layer.pointer("/name/type").and_then(Value::as_str) == Some("project")
|
||||
&& layer
|
||||
.pointer("/name/dotCodexFolder")
|
||||
.and_then(Value::as_str)
|
||||
.is_some_and(|path| Path::new(path) == folder)
|
||||
&& layer.get("disabledReason").and_then(Value::as_str).is_some_and(|reason| !reason.trim().is_empty())
|
||||
})
|
||||
}
|
||||
|
||||
impl CodexShim {
|
||||
pub(super) async fn prepare_project_trust(&self, params: &Value) {
|
||||
let Some(cwd) = params.get("cwd").and_then(Value::as_str) else { return };
|
||||
if !self.state.lock().trust_checked.insert(cwd.to_owned()) {
|
||||
return;
|
||||
}
|
||||
// Old app-servers may not expose config layers. Their warnings still reach the UI.
|
||||
let Ok(Ok(config)) = tokio::time::timeout(
|
||||
Duration::from_secs(5),
|
||||
self.call("config/read", json!({ "cwd": cwd, "includeLayers": true })),
|
||||
)
|
||||
.await
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let Some(layer) = disabled_project(&config, cwd) else { return };
|
||||
let Some(client) = self.client.get() else { return };
|
||||
let title = format!(
|
||||
"Trust project in Codex: {cwd}? This saves trust in your Codex user configuration and allows \
|
||||
this project's MCP servers, hooks and exec policies to load."
|
||||
);
|
||||
let permission = json!({
|
||||
"sessionId": params.get("sessionId").and_then(Value::as_str).unwrap_or_default(),
|
||||
"toolCall": {
|
||||
"toolCallId": format!("codex-project-trust:{cwd}"),
|
||||
"title": title, "kind": "edit",
|
||||
"rawInput": { "project": cwd },
|
||||
},
|
||||
"options": [
|
||||
// Permanent trust must never be auto-approved by the task's allow-once bypass.
|
||||
{ "optionId": "codex-trust-project", "name": "Trust Project in Codex", "kind": "allow_always" },
|
||||
{ "optionId": "codex-keep-untrusted", "name": "Keep Untrusted", "kind": "reject_once" },
|
||||
],
|
||||
});
|
||||
let answer: Result<Value, RpcError> = client.request("session/request_permission", permission, None).await;
|
||||
let approved = answer.as_ref().is_ok_and(|answer| {
|
||||
answer.pointer("/outcome/outcome").and_then(Value::as_str) == Some("selected")
|
||||
&& answer.pointer("/outcome/optionId").and_then(Value::as_str) == Some("codex-trust-project")
|
||||
});
|
||||
if !approved {
|
||||
if let Some(reason) = layer.get("disabledReason").and_then(Value::as_str) {
|
||||
self.warning(reason);
|
||||
}
|
||||
return;
|
||||
}
|
||||
// Quote the path as one key segment: dots and Windows backslashes are literal.
|
||||
let mut write = json!({
|
||||
"keyPath": format!("projects.{}.trust_level", json!(cwd)),
|
||||
"value": "trusted", "mergeStrategy": "replace",
|
||||
});
|
||||
if let Some(version) = config["layers"]
|
||||
.as_array()
|
||||
.and_then(|layers| {
|
||||
layers.iter().find(|layer| {
|
||||
layer.pointer("/name/type").and_then(Value::as_str) == Some("user")
|
||||
&& layer.pointer("/name/profile").is_none_or(Value::is_null)
|
||||
})
|
||||
})
|
||||
.and_then(|layer| layer.get("version"))
|
||||
.filter(|version| version.is_string())
|
||||
{
|
||||
write["expectedVersion"] = version.clone();
|
||||
}
|
||||
match self.call("config/value/write", write).await {
|
||||
Err(error) => self.warning(format!("Codex could not save trust for {cwd}: {}", error.message)),
|
||||
Ok(reply) if reply["status"] == "okOverridden" => {
|
||||
self.warning(format!(
|
||||
"Codex saved trust for {cwd}, but a higher-priority configuration overrides it. \
|
||||
Project configuration may remain disabled; check the Codex configuration or contact your administrator."
|
||||
));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
// start/resume/fork now load the updated config before creating the thread.
|
||||
}
|
||||
}
|
||||
@@ -909,8 +909,23 @@ 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.
|
||||
assert!(mgr_a.commands("codex", None).await.unwrap().is_empty());
|
||||
// Other agents get only what they offered, plus verified native builtins.
|
||||
assert_eq!(
|
||||
names(mgr_a.commands("codex", None).await.unwrap()),
|
||||
[
|
||||
"plan",
|
||||
"mcp",
|
||||
"skills",
|
||||
"status",
|
||||
"review",
|
||||
"review-branch",
|
||||
"review-commit",
|
||||
"compact",
|
||||
"goal",
|
||||
"rename",
|
||||
"logout",
|
||||
]
|
||||
);
|
||||
mgr_a.cancel(&task.id, None).unwrap();
|
||||
wait_for(&mgr_a, &task.id, AgentStatus::Ready).await;
|
||||
mgr_a.shutdown();
|
||||
@@ -930,9 +945,27 @@ async fn builtin_commands_only_fill_verified_gaps_and_preserve_advertised_metada
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager_at(tmp.path(), &tmp.path().join("models.json"), agent);
|
||||
for provider in ["claude", "claude-acp", "opencode2", "codex", "custom"] {
|
||||
for provider in ["claude", "claude-acp", "opencode2", "custom"] {
|
||||
assert!(mgr.commands(provider, None).await.unwrap().is_empty(), "{provider}");
|
||||
}
|
||||
let commands = mgr.commands("codex", None).await.unwrap();
|
||||
assert_eq!(
|
||||
commands.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(),
|
||||
[
|
||||
"plan",
|
||||
"mcp",
|
||||
"skills",
|
||||
"status",
|
||||
"review",
|
||||
"review-branch",
|
||||
"review-commit",
|
||||
"compact",
|
||||
"goal",
|
||||
"rename",
|
||||
"logout",
|
||||
]
|
||||
);
|
||||
assert_eq!(commands[1].hint.as_deref(), Some("[reconnect]"));
|
||||
let commands = mgr.commands("opencode", None).await.unwrap();
|
||||
assert_eq!(commands.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["compact"]);
|
||||
let task = mgr
|
||||
@@ -1603,6 +1636,12 @@ 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)] {
|
||||
@@ -1623,6 +1662,67 @@ async fn renamed_titles_survive_updates_forks_and_restart() {
|
||||
restored.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn startup_warnings_survive_replay_and_restart_without_failing_the_task() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask { provider: "claude".into(), prompt: text("again"), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
let handle = mgr.task(&task.id).unwrap();
|
||||
handle.replaying.store(true, Ordering::Release);
|
||||
handle.turn_started.store(false, Ordering::Release);
|
||||
let client = Client { task: Arc::downgrade(&handle) };
|
||||
client.on_notification(WARNING_NOTIFICATION, json!({"message": "Project MCP config is disabled until trusted."}));
|
||||
client.on_notification(WARNING_NOTIFICATION, json!({"message": " "}));
|
||||
client.on_notification(WARNING_NOTIFICATION, json!({}));
|
||||
assert_eq!(handle.state.lock().task.status, AgentStatus::Ready);
|
||||
assert!(!handle.turn_started.load(Ordering::Acquire));
|
||||
mgr.shutdown();
|
||||
let restored = manager(tmp.path(), agent);
|
||||
let handle = restored.task(&task.id).unwrap();
|
||||
assert_eq!(handle.state.lock().conversation.main.entries.iter().filter(|entry| matches!(entry, AgentEntry::Error {message} if message == "Project MCP config is disabled until trusted.")).count(), 1);
|
||||
restored.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn persistent_project_trust_needs_confirmation_even_with_bypass_and_is_denied_in_side_chats() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let task = mgr
|
||||
.create(NewAgentTask { provider: "claude".into(), prompt: text("again"), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
let handle = mgr.task(&task.id).unwrap();
|
||||
handle.state.lock().task.config = config::options_of(&json!({"configOptions": [{
|
||||
"id": "mode", "category": "mode", "type": "select", "currentValue": "full-access",
|
||||
"options": [{"value": "full-access", "name": "Full Access"}]
|
||||
}]}));
|
||||
assert!(config::bypass_approvals(&handle.state.lock().task.config));
|
||||
let params = json!({"toolCall": {"toolCallId": "trust", "kind": "edit", "title": "Trust Project in Codex"},
|
||||
"options": [
|
||||
{"optionId": "codex-trust-project", "name": "Trust Project in Codex", "kind": "allow_always"},
|
||||
{"optionId": "codex-keep-untrusted", "name": "Keep Untrusted", "kind": "reject_once"}
|
||||
]});
|
||||
let asking = {
|
||||
let handle = handle.clone();
|
||||
let params = params.clone();
|
||||
tokio::task::spawn_blocking(move || handle.ask_permission(¶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");
|
||||
handle.state.lock().ephemeral = true;
|
||||
assert_eq!(handle.ask_permission(¶ms)["outcome"]["optionId"], "codex-keep-untrusted");
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn forks_rollbacks_and_steering() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -4138,3 +4238,14 @@ 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());
|
||||
}
|
||||
@@ -310,6 +310,8 @@ fn artifact_steps(
|
||||
.find(|f| f.module == artifact.module || f.module.is_empty() && artifact.module == ".")
|
||||
.or_else(|| ps.facets.iter().find(|f| f.kind == "web"));
|
||||
let staging = cache.join("artifacts").join(file_name(&artifact.name));
|
||||
// What the last build laid out in a folder the user chose, so the next one replaces only that.
|
||||
let record = cache.join("artifacts").join(format!("{}.files", file_name(&artifact.name)));
|
||||
let mut steps = Vec::new();
|
||||
match (artifact.kind, war) {
|
||||
(ArtifactKind::Jar, None) => {
|
||||
@@ -324,7 +326,11 @@ fn artifact_steps(
|
||||
manifest.push_str(&format!("Class-Path: {}\r\n", names.join(" ")));
|
||||
}
|
||||
steps.push(BuildStep::action(
|
||||
Action::Layout { into: staging.clone(), entries: vec![(classes.to_path_buf(), PathBuf::new())] },
|
||||
Action::Layout {
|
||||
into: staging.clone(),
|
||||
entries: vec![(classes.to_path_buf(), PathBuf::new())],
|
||||
record: None,
|
||||
},
|
||||
root,
|
||||
));
|
||||
// The jar's Class-Path names the libraries next to it.
|
||||
@@ -332,6 +338,7 @@ fn artifact_steps(
|
||||
Action::Layout {
|
||||
into: out.clone(),
|
||||
entries: libraries.iter().map(|l| (l.clone(), file_of(l))).collect(),
|
||||
record: Some(record),
|
||||
},
|
||||
root,
|
||||
));
|
||||
@@ -353,7 +360,9 @@ fn artifact_steps(
|
||||
for lib in &libraries {
|
||||
entries.push((lib.clone(), Path::new("WEB-INF/lib").join(file_of(lib))));
|
||||
}
|
||||
steps.push(BuildStep::action(Action::Layout { into: exploded.clone(), entries }, root));
|
||||
// The exploded output may be a folder the user chose; the staging folder is the IDE's own.
|
||||
let record = (exploded != staging).then_some(record);
|
||||
steps.push(BuildStep::action(Action::Layout { into: exploded.clone(), entries, record }, root));
|
||||
let archive = war
|
||||
.map(Path::to_path_buf)
|
||||
.or_else(|| (kind != ArtifactKind::WarExploded).then(|| artifact_file(root, artifact)));
|
||||
@@ -407,8 +416,10 @@ pub(crate) enum Action {
|
||||
/// relative paths; files that are already up to date are left alone.
|
||||
CopyResources { from: Vec<PathBuf>, to: PathBuf },
|
||||
/// Lays out an artifact in `into`: each folder's content or file goes to its relative
|
||||
/// place (`""` = the top). What is no longer laid out is removed.
|
||||
Layout { into: PathBuf, entries: Vec<(PathBuf, PathBuf)> },
|
||||
/// place (`""` = the top). What is no longer laid out is removed: without `record`, `into`
|
||||
/// is the IDE's own folder and is laid out afresh; with it, `into` is a folder the user chose
|
||||
/// and only the files the previous layout recorded there are removed, never anything else.
|
||||
Layout { into: PathBuf, entries: Vec<(PathBuf, PathBuf)>, record: Option<PathBuf> },
|
||||
/// Zips the folder `from` into the archive `to`, with this manifest first.
|
||||
Archive { from: PathBuf, to: PathBuf, manifest: Option<String> },
|
||||
}
|
||||
@@ -441,29 +452,39 @@ impl Action {
|
||||
}
|
||||
Ok(format!("{copied} resource file(s) copied"))
|
||||
}
|
||||
Action::Layout { into, entries } => {
|
||||
// A fresh layout: files dropped from the sources must not linger in the artifact.
|
||||
Action::Layout { into, entries, record } => {
|
||||
if entries.iter().any(|(from, _)| from.starts_with(into)) {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"The artifact output folder {} holds files the artifact is made of",
|
||||
into.display()
|
||||
)));
|
||||
}
|
||||
if into.exists() {
|
||||
if record.is_none() && into.exists() {
|
||||
fs::remove_dir_all(into)
|
||||
.map_err(|e| IdeError::internal(format!("cannot delete {} ({e})", into.display())))?;
|
||||
}
|
||||
let mut copied = 0;
|
||||
let mut written = Vec::new();
|
||||
for (from, to) in entries {
|
||||
let target = into.join(to);
|
||||
// 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() {
|
||||
copied += copy_tree(from, &target, cancel)?;
|
||||
copy_tree(from, &target, &mut written, cancel)?;
|
||||
} else if from.is_file() {
|
||||
copy_file(from, &target)?;
|
||||
copied += 1;
|
||||
written.push(target);
|
||||
}
|
||||
}
|
||||
Ok(format!("{copied} file(s) laid out"))
|
||||
if let Some(record) = record {
|
||||
replace_recorded(into, record, &written)?;
|
||||
}
|
||||
Ok(format!("{} file(s) laid out", written.len()))
|
||||
}
|
||||
Action::Archive { from, to, manifest } => {
|
||||
archive(from, to, manifest.as_deref(), cancel)?;
|
||||
@@ -474,6 +495,10 @@ 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())))?;
|
||||
@@ -482,23 +507,80 @@ fn copy_file(from: &Path, to: &Path) -> IdeResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn copy_tree(from: &Path, to: &Path, cancel: &CancellationToken) -> IdeResult<usize> {
|
||||
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<()> {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let Ok(entries) = fs::read_dir(from) else { return Ok(0) };
|
||||
let mut copied = 0;
|
||||
let Ok(entries) = fs::read_dir(from) else { return Ok(()) };
|
||||
for e in entries.flatten() {
|
||||
let Ok(t) = e.file_type() else { continue };
|
||||
let target = to.join(e.file_name());
|
||||
if t.is_dir() {
|
||||
copied += copy_tree(&e.path(), &target, cancel)?;
|
||||
refuse_link(&target)?;
|
||||
copy_tree(&e.path(), &target, written, cancel)?;
|
||||
} else if t.is_file() {
|
||||
copy_file(&e.path(), &target)?;
|
||||
copied += 1;
|
||||
written.push(target);
|
||||
}
|
||||
}
|
||||
Ok(copied)
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Removes the files the previous layout recorded in `into` that this one didn't write
|
||||
/// (and the folders that leaves empty), then records `written` for the next layout.
|
||||
fn replace_recorded(into: &Path, record: &Path, written: &[PathBuf]) -> IdeResult<()> {
|
||||
let now: std::collections::HashSet<PathBuf> =
|
||||
written.iter().filter_map(|p| p.strip_prefix(into).ok().map(Path::to_path_buf)).collect();
|
||||
let before = fs::read_to_string(record).unwrap_or_default();
|
||||
let mut lines = before.lines();
|
||||
// The record names its folder first: one made for another output folder removes nothing.
|
||||
let same = lines.next().is_some_and(|dir| Path::new(dir) == into);
|
||||
for rel in lines.filter(|_| same).map(PathBuf::from) {
|
||||
// Only plain relative paths inside `into`: a damaged record must not reach elsewhere.
|
||||
if rel.as_os_str().is_empty()
|
||||
|| now.contains(&rel)
|
||||
|| rel.components().any(|c| !matches!(c, std::path::Component::Normal(_)))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let file = into.join(&rel);
|
||||
// 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())))
|
||||
}
|
||||
|
||||
fn archive(from: &Path, to: &Path, manifest: Option<&str>, cancel: &CancellationToken) -> IdeResult<()> {
|
||||
@@ -812,8 +894,71 @@ mod tests {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let web = tmp.path().join("WebRoot");
|
||||
write(&web.join("a.jsp"), "");
|
||||
let action = Action::Layout { into: tmp.path().to_path_buf(), entries: vec![(web.clone(), PathBuf::new())] };
|
||||
let action = Action::Layout {
|
||||
into: tmp.path().to_path_buf(),
|
||||
entries: vec![(web.clone(), PathBuf::new())],
|
||||
record: None,
|
||||
};
|
||||
assert!(action.run(&CancellationToken::new()).is_err());
|
||||
assert!(web.join("a.jsp").is_file());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_chosen_output_folder_keeps_what_the_artifact_did_not_put_there() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let project = tmp.path().join("project");
|
||||
write(&project.join("src/A.java"), "class A {}");
|
||||
write(&project.join(".git/HEAD"), "ref: refs/heads/main");
|
||||
let libs = tmp.path().join("libs");
|
||||
write(&libs.join("a.jar"), "a");
|
||||
write(&libs.join("b.jar"), "b");
|
||||
let record = tmp.path().join("cache/artifacts/app.files");
|
||||
let layout = |names: &[&str]| Action::Layout {
|
||||
into: project.clone(),
|
||||
entries: names.iter().map(|n| (libs.join(n), PathBuf::from(n))).collect(),
|
||||
record: Some(record.clone()),
|
||||
};
|
||||
layout(&["a.jar", "b.jar"]).run(&CancellationToken::new()).unwrap();
|
||||
assert!(project.join("a.jar").is_file() && project.join("b.jar").is_file());
|
||||
// A library dropped from the artifact goes; the project's own files stay.
|
||||
layout(&["a.jar"]).run(&CancellationToken::new()).unwrap();
|
||||
assert!(project.join("a.jar").is_file() && !project.join("b.jar").exists());
|
||||
assert!(project.join("src/A.java").is_file() && project.join(".git/HEAD").is_file());
|
||||
// A damaged record never reaches outside the folder.
|
||||
write(&record, &format!("{}\n../outside.txt", project.display()));
|
||||
write(&tmp.path().join("outside.txt"), "x");
|
||||
layout(&["a.jar"]).run(&CancellationToken::new()).unwrap();
|
||||
assert!(tmp.path().join("outside.txt").is_file());
|
||||
// Nor 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());
|
||||
}
|
||||
}
|
||||
@@ -167,7 +167,10 @@ The `url` field in the result is as written in the file (unsubstituted); transpo
|
||||
}
|
||||
call.confirm(&subject, Some(detail)).await?;
|
||||
|
||||
let exchange = ide_http::run(input, &call.cancel).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 history = call.project().http_history.clone();
|
||||
let saved = exchange.clone();
|
||||
let _ = call.host().blocking(move || history.add(&saved)).await;
|
||||
@@ -188,7 +191,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(), &prepared.url),
|
||||
"error": redact_transport_error(exchange.entry.error.clone(), &redact_url),
|
||||
"body": body,
|
||||
"bodyTruncated": body_truncated,
|
||||
}))
|
||||
|
||||
@@ -97,6 +97,8 @@ 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(
|
||||
@@ -109,6 +111,7 @@ 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)?;
|
||||
@@ -137,7 +140,7 @@ async fn resolve_launch(
|
||||
&project.build_cache_dir(),
|
||||
&cancel,
|
||||
);
|
||||
merge_maven_launch_classpath(&mut class_paths, &mut info, maven_cp)?;
|
||||
merge_maven_launch_classpath(&mut class_paths, &mut info, maven_cp, &snapshotted)?;
|
||||
} else {
|
||||
append_unique_class_paths(&mut class_paths, std::mem::take(&mut info.class_paths));
|
||||
}
|
||||
@@ -298,17 +301,23 @@ 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.
|
||||
/// 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.
|
||||
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()),
|
||||
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)))),
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
@@ -471,20 +480,46 @@ 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,6 +550,24 @@ pub async fn lsp_implementations(
|
||||
result
|
||||
}
|
||||
|
||||
/// Refines the implementations `targets` of the method at `pos` to their declarations (Java
|
||||
/// dependencies' class files point at the start of the class). Cancel with
|
||||
/// `cancel_request(request)`.
|
||||
pub async fn lsp_implementation_locations(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
request: RequestId,
|
||||
doc: DocId,
|
||||
pos: Pos,
|
||||
targets: Vec<Location>,
|
||||
) -> IdeResult<Vec<Location>> {
|
||||
let lsp = host.project(window)?.lsp.clone();
|
||||
let (_, cancel) = begin_position_request(host, window, request, doc, pos).await?;
|
||||
let result = lsp.implementation_locations(doc, pos, targets, cancel).await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
/// Go to Implementation of the symbol at `pos`. Implementations found before a slower
|
||||
/// search for the rest (Java: the project's, before the dependencies') arrive on
|
||||
/// `on_partial`; the result has them all. Cancel with `cancel_request(request)`.
|
||||
@@ -1223,7 +1241,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 move arguments: {e}")))
|
||||
serde_json::from_str(args).map_err(|e| IdeError::invalid(format!("invalid refactoring arguments: {e}")))
|
||||
}
|
||||
|
||||
fn json_strings(values: Vec<serde_json::Value>) -> Vec<String> {
|
||||
@@ -1289,6 +1307,50 @@ 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,
|
||||
@@ -1943,6 +2005,17 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
let on_partial = c.sender("onPartial")?;
|
||||
lsp_goto_implementation(&c.host, &c.window, c.arg("request")?, c.arg("doc")?, c.arg("pos")?, on_partial).await
|
||||
});
|
||||
d.add("lsp_implementation_locations", |c| async move {
|
||||
lsp_implementation_locations(
|
||||
&c.host,
|
||||
&c.window,
|
||||
c.arg("request")?,
|
||||
c.arg("doc")?,
|
||||
c.arg("pos")?,
|
||||
c.arg("targets")?,
|
||||
)
|
||||
.await
|
||||
});
|
||||
d.add(
|
||||
"lsp_resolve_class_file",
|
||||
|c| async move { lsp_resolve_class_file(&c.host, &c.window, c.arg("path")?).await },
|
||||
@@ -2028,6 +2101,23 @@ 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
|
||||
|
||||
@@ -34,6 +34,16 @@ 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)
|
||||
@@ -57,7 +67,7 @@ pub async fn run(input: RunInput<'_>, cancel: &CancellationToken) -> IdeResult<H
|
||||
url: request.url.clone(),
|
||||
status: response.as_ref().map(|r| r.status),
|
||||
total_ms: response.as_ref().map(|r| r.total_ms),
|
||||
file: input.file.map(IpcPath::from),
|
||||
file: file.map(IpcPath::from),
|
||||
error,
|
||||
},
|
||||
request,
|
||||
|
||||
@@ -19,6 +19,7 @@ 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;
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
//! Extract Interface through jdtls' own requests: `java/checkExtractInterfaceStatus` lists the
|
||||
//! members of the file's class an interface can declare and the packages it can go to,
|
||||
//! `java/getRefactorEdit` (`extractInterface`) creates the interface, makes the class implement
|
||||
//! it and uses it where possible. The UI picks the name, package and members and applies the edit.
|
||||
use super::COMMAND_TIMEOUT;
|
||||
use super::signature::{RefactorEdit, changed};
|
||||
use crate::types::{ExtractInterfaceInfo, InterfaceMember, ProblemSeverity, RefactoringProblem, ServerRefactored};
|
||||
use crate::{LspManager, convert};
|
||||
use ide_core::{CancellationToken, DocId, IdeError, IdeResult, Pos};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
const FEATURE: &str = "Extract Interface";
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct Status {
|
||||
#[serde(default)]
|
||||
members: Vec<InterfaceMember>,
|
||||
#[serde(default)]
|
||||
sub_type_name: String,
|
||||
#[serde(default)]
|
||||
destination_response: Destinations,
|
||||
}
|
||||
|
||||
#[derive(Default, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct Destinations {
|
||||
#[serde(default)]
|
||||
destinations: Vec<Value>,
|
||||
}
|
||||
|
||||
fn info_of(status: Option<Status>) -> IdeResult<ExtractInterfaceInfo> {
|
||||
let status = status
|
||||
.filter(|s| !s.sub_type_name.is_empty())
|
||||
.ok_or_else(|| IdeError::invalid("The file should declare a class"))?;
|
||||
Ok(ExtractInterfaceInfo {
|
||||
class_name: status.sub_type_name,
|
||||
members: status.members,
|
||||
packages: status.destination_response.destinations.iter().map(Value::to_string).collect(),
|
||||
})
|
||||
}
|
||||
|
||||
impl LspManager {
|
||||
/// The class of the file at `doc`, its members and the packages for the interface.
|
||||
pub async fn extract_interface_info(
|
||||
&self,
|
||||
doc: DocId,
|
||||
pos: Pos,
|
||||
cancel: CancellationToken,
|
||||
) -> IdeResult<ExtractInterfaceInfo> {
|
||||
let (snap, t) = self.jdtls_target(doc, FEATURE).await?;
|
||||
let params = Self::signature_context(&snap, &t, pos);
|
||||
let status: Option<Status> =
|
||||
self.call(&t, "java/checkExtractInterfaceStatus", params, Some(&cancel), COMMAND_TIMEOUT).await?;
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
info_of(status)
|
||||
}
|
||||
|
||||
/// Checks extracting `members` into the interface `name` in `package` (a package from
|
||||
/// [`Self::extract_interface_info`]) and computes the edit without applying it.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn extract_interface(
|
||||
&self,
|
||||
doc: DocId,
|
||||
pos: Pos,
|
||||
members: Vec<String>,
|
||||
name: String,
|
||||
package: Value,
|
||||
confirmation: Option<String>,
|
||||
cancel: CancellationToken,
|
||||
) -> IdeResult<ServerRefactored> {
|
||||
let (snap, t) = self.jdtls_target(doc, FEATURE).await?;
|
||||
let mut params = json!({
|
||||
"command": "extractInterface",
|
||||
"context": Self::signature_context(&snap, &t, pos),
|
||||
"options": { "tabSize": 4, "insertSpaces": true },
|
||||
"commandArguments": [members, name, package],
|
||||
});
|
||||
if let Some(token) = confirmation {
|
||||
params["confirmationToken"] = json!(token);
|
||||
}
|
||||
let answer: Option<RefactorEdit> =
|
||||
self.call(&t, "java/getRefactorEdit", params, Some(&cancel), COMMAND_TIMEOUT).await?;
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
// jdtls answers nothing when its checks fail, and reports why in a message of its own.
|
||||
let Some(answer) = answer else {
|
||||
return Ok(ServerRefactored {
|
||||
problems: vec![RefactoringProblem {
|
||||
severity: ProblemSeverity::Fatal,
|
||||
message: "The interface could not be extracted".to_owned(),
|
||||
}],
|
||||
edit: None,
|
||||
confirmation: None,
|
||||
});
|
||||
};
|
||||
let conv = self.conv(t.enc());
|
||||
Ok(changed(answer, |e| convert::workspace_edit(&conv, e)))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn reads_the_members_and_packages() {
|
||||
let status: Status = serde_json::from_value(json!({
|
||||
"members": [
|
||||
{ "name": "area", "typeName": "double", "parameters": [], "handleIdentifier": "=p/src<a{Shape.java[Shape~area" },
|
||||
{ "name": "UNIT", "typeName": "int", "handleIdentifier": "=p/src<a{Shape.java[Shape^UNIT" },
|
||||
],
|
||||
"subTypeName": "Shape",
|
||||
"destinationResponse": { "destinations": [{ "displayName": "a", "isParentOfSelectedFile": true }] },
|
||||
}))
|
||||
.unwrap();
|
||||
let info = info_of(Some(status)).unwrap();
|
||||
assert_eq!(info.class_name, "Shape");
|
||||
assert_eq!(info.members[0].parameters.as_deref(), Some(&[][..]));
|
||||
assert_eq!(info.members[1].parameters, None);
|
||||
assert_eq!(serde_json::from_str::<Value>(&info.packages[0]).unwrap()["displayName"], "a");
|
||||
assert!(info_of(None).is_err());
|
||||
}
|
||||
}
|
||||
@@ -68,7 +68,7 @@ impl LspManager {
|
||||
Ok((snap, t))
|
||||
}
|
||||
|
||||
fn signature_context(snap: &DocSnap, t: &Target, pos: Pos) -> Value {
|
||||
pub(super) fn signature_context(snap: &DocSnap, t: &Target, pos: Pos) -> Value {
|
||||
let at = snap.position(t, pos);
|
||||
json!({
|
||||
"textDocument": { "uri": snap.uri },
|
||||
|
||||
@@ -434,6 +434,11 @@ async fn library_sources(snap: &DocSnap, root: &Path, pos: Pos, locs: Vec<Locati
|
||||
|
||||
const JAVA_IMPLEMENTATIONS: &str = "openidea.java.implementations";
|
||||
|
||||
/// jdtls' locations of the implementations of the method at a position in the classes named
|
||||
/// with it, for implementation classes in dependencies: its standard request puts those at the
|
||||
/// start of the decompiled class instead of at the method.
|
||||
const JAVA_IMPLEMENTATION_LOCATIONS: &str = "openidea.java.implementationLocations";
|
||||
|
||||
/// The answer of [`JAVA_IMPLEMENTATIONS`]: `complete` when the type is declared in the
|
||||
/// sources, so no dependency can implement it.
|
||||
#[derive(serde::Deserialize)]
|
||||
@@ -442,6 +447,13 @@ struct SourceImplementations {
|
||||
complete: bool,
|
||||
}
|
||||
|
||||
/// The answer of [`JAVA_IMPLEMENTATION_LOCATIONS`]: one entry per requested class, `None` when
|
||||
/// it has no implementation of the method.
|
||||
#[derive(serde::Deserialize)]
|
||||
struct TargetImplementations {
|
||||
locations: Vec<Option<lsp::Location>>,
|
||||
}
|
||||
|
||||
/// Receives the implementations found so far, before a slower search for the rest.
|
||||
type Partial<'a> = Option<&'a (dyn Fn(Vec<Location>) + Send + Sync)>;
|
||||
|
||||
@@ -1810,6 +1822,84 @@ impl LspManager {
|
||||
out
|
||||
}
|
||||
|
||||
/// jdtls: where the implementation methods of the method at `pos` are declared in the
|
||||
/// dependency classes `locs` point at. Its standard request answers those with `0:0`, the
|
||||
/// start of the class file's decompiled source; [`JAVA_IMPLEMENTATION_LOCATIONS`] resolves
|
||||
/// the declaration itself.
|
||||
async fn java_implementation_locations(
|
||||
&self,
|
||||
snap: &DocSnap,
|
||||
t: &Target,
|
||||
pos: Pos,
|
||||
locs: Vec<Location>,
|
||||
cancel: Option<&CancellationToken>,
|
||||
) -> Vec<Location> {
|
||||
if t.server.name != "jdtls" || !t.caps().commands().iter().any(|c| c == JAVA_IMPLEMENTATION_LOCATIONS) {
|
||||
return locs;
|
||||
}
|
||||
let targets: Vec<(usize, String)> = locs
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(i, l)| {
|
||||
let uri = l.uri.as_deref()?;
|
||||
(virtual_doc::scheme(uri) == "jdt" && l.range.start.line == 0).then(|| (i, uri.to_owned()))
|
||||
})
|
||||
.collect();
|
||||
if targets.is_empty() {
|
||||
return locs;
|
||||
}
|
||||
let params = snap.pos_params(t, pos);
|
||||
let arguments = json!([
|
||||
params["textDocument"]["uri"],
|
||||
params["position"]["line"],
|
||||
params["position"]["character"],
|
||||
targets.iter().map(|(_, uri)| uri).collect::<Vec<_>>(),
|
||||
]);
|
||||
let result: IdeResult<TargetImplementations> = self
|
||||
.call(
|
||||
t,
|
||||
"workspace/executeCommand",
|
||||
json!({ "command": JAVA_IMPLEMENTATION_LOCATIONS, "arguments": arguments }),
|
||||
cancel,
|
||||
LONG_TIMEOUT,
|
||||
)
|
||||
.await;
|
||||
let found = match result {
|
||||
Ok(found) if found.locations.len() == targets.len() => found,
|
||||
Ok(_) => return locs,
|
||||
Err(e) => {
|
||||
tracing::debug!("{JAVA_IMPLEMENTATION_LOCATIONS}: {}", e.message);
|
||||
return locs;
|
||||
}
|
||||
};
|
||||
let mut out = locs;
|
||||
for ((i, _), loc) in targets.into_iter().zip(found.locations) {
|
||||
if let Some(loc) = loc.as_ref().and_then(|l| self.conv(t.enc()).location(l)) {
|
||||
out[i] = loc;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Refines the implementation `locs` of the method at `pos`: jdtls puts an implementation in
|
||||
/// a dependency at the start of its decompiled class instead of at the method, which matters
|
||||
/// when the gutter marker's targets are opened one by one.
|
||||
pub async fn implementation_locations(
|
||||
&self,
|
||||
doc: DocId,
|
||||
pos: Pos,
|
||||
locs: Vec<Location>,
|
||||
cancel: CancellationToken,
|
||||
) -> IdeResult<Vec<Location>> {
|
||||
let (_, cap, feature) = goto_method(GotoKind::Implementation);
|
||||
let (snap, targets) = self.doc_targets(doc, feature, |c| c.has(cap)).await?;
|
||||
let mut out = locs;
|
||||
for t in &targets {
|
||||
out = self.java_implementation_locations(&snap, t, pos, out, Some(&cancel)).await;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
async fn goto_in(
|
||||
&self,
|
||||
snap: &DocSnap,
|
||||
@@ -1849,6 +1939,12 @@ impl LspManager {
|
||||
Ok(Some(r)) => {
|
||||
let locs = convert::goto_response(&self.conv(t.enc()), r);
|
||||
let locs = library_sources(snap, &self.project_root, pos, locs).await;
|
||||
// Only explicit Go to Implementation: gutter markers ask for every line.
|
||||
let locs = if method == "textDocument/implementation" && partial.is_some() {
|
||||
self.java_implementation_locations(snap, t, pos, locs, cancel).await
|
||||
} else {
|
||||
locs
|
||||
};
|
||||
self.note_virtual(&t.server, locs.iter().map(|l| l.uri.as_deref()));
|
||||
self.note_arduino_sources(&t.server, &locs);
|
||||
let locs = self.jdt_library_classes(snap, pos, locs).await;
|
||||
|
||||
@@ -539,7 +539,30 @@ pub struct MethodSignature {
|
||||
pub exceptions: Vec<SignatureException>,
|
||||
}
|
||||
|
||||
/// A refactoring checked by the server (Change Signature, Move): problems to show, the edit when
|
||||
/// A member Extract Interface can declare in the new interface.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct InterfaceMember {
|
||||
pub name: String,
|
||||
/// The method's return type or the field's type.
|
||||
pub type_name: String,
|
||||
/// The method's parameter types; `None` for a field.
|
||||
pub parameters: Option<Vec<String>>,
|
||||
/// The server's handle of the member, passed back unchanged.
|
||||
pub handle_identifier: String,
|
||||
}
|
||||
|
||||
/// What Extract Interface starts from: the file's class, the members the interface can declare and
|
||||
/// the packages it can go to (as JSON, passed back unchanged).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ExtractInterfaceInfo {
|
||||
pub class_name: String,
|
||||
pub members: Vec<InterfaceMember>,
|
||||
pub packages: Vec<String>,
|
||||
}
|
||||
|
||||
/// A refactoring checked by the server (Change Signature, Move, Extract Interface): problems to show, the edit when
|
||||
/// none is fatal, and the token that confirms going on despite warnings.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
|
||||
@@ -3483,6 +3483,52 @@ async fn java_implementations_come_from_sources_first() {
|
||||
assert_eq!(s.requested("textDocument/implementation").len(), 3);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn java_dependency_implementations_point_at_the_method() {
|
||||
let caps = json!({
|
||||
"textDocumentSync": 1,
|
||||
"implementationProvider": true,
|
||||
"executeCommandProvider": { "commands": ["openidea.java.implementations", "openidea.java.implementationLocations"] },
|
||||
});
|
||||
let h = harness_for("java", "java", &[("jdtls", caps)], &[]);
|
||||
let (doc, _) = h.open("Repo.java", "interface Repo {\n void save(String item);\n}\n");
|
||||
h.wait_status("jdtls", ServerStatus::Ready).await;
|
||||
let s = h.launcher.state("jdtls");
|
||||
let class_uri = "jdt://contents/lib.jar/zoo/RepoImpl.java?=p/lib.jar%3Czoo%28RepoImpl.class";
|
||||
let method = json!({
|
||||
"uri": class_uri,
|
||||
"range": {"start":{"line":4,"character":4},"end":{"line":6,"character":5}},
|
||||
});
|
||||
let at_zero = json!({
|
||||
"uri": class_uri,
|
||||
"range": {"start":{"line":0,"character":0},"end":{"line":0,"character":0}},
|
||||
});
|
||||
let refined = method.clone();
|
||||
*s.responder.lock() = Some(Arc::new(move |_, method, params| match method {
|
||||
"workspace/executeCommand" if params["command"] == "openidea.java.implementations" => {
|
||||
Some(json!({ "locations": [], "complete": false }))
|
||||
}
|
||||
"workspace/executeCommand" if params["command"] == "openidea.java.implementationLocations" => {
|
||||
assert_eq!(params["arguments"][3], json!([class_uri]));
|
||||
Some(json!({ "locations": [refined] }))
|
||||
}
|
||||
"textDocument/implementation" => Some(json!([at_zero])),
|
||||
_ => None,
|
||||
}));
|
||||
let partial = Mutex::new(Vec::new());
|
||||
let found = h
|
||||
.mgr
|
||||
.goto_implementation(doc, Pos::new(1, 9), Default::default(), &|locs| partial.lock().push(locs.to_vec()))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(found.len(), 1);
|
||||
assert_eq!(found[0].uri.as_deref(), Some(class_uri));
|
||||
assert_eq!(found[0].range.start.line, 4);
|
||||
assert_eq!(s.requested("textDocument/implementation").len(), 1);
|
||||
let commands = s.requested("workspace/executeCommand");
|
||||
assert!(commands.iter().any(|r| r["command"] == "openidea.java.implementationLocations"));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn navigation_rename_format_and_decorations() {
|
||||
let h = harness(&[("mock", incremental_caps())]);
|
||||
|
||||
@@ -1588,7 +1588,7 @@ pub fn usages_bundle(data_dir: &Path) -> Option<PathBuf> {
|
||||
install_bundle(
|
||||
data_dir,
|
||||
"java-usages",
|
||||
"1.14.0",
|
||||
"1.15.0",
|
||||
include_bytes!("../../../java/java-usages/openidea-java-usages.jar"),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -32,6 +32,8 @@ These agents are built in. Install the agent's own CLI and sign in once in a ter
|
||||
|
||||
Agents are unavailable in a project you have not marked as trusted.
|
||||
|
||||
Codex keeps its own project trust decision. If it disables the current project's `.codex` configuration, the task asks whether to **Trust Project in Codex** or **Keep Untrusted**. Trusting saves only that project's trust entry through Codex's configuration API before the session loads its configuration, including MCP servers, hooks and exec policies. This confirmation is required even in Full Access mode; declining keeps the configuration disabled and shows the reason without stopping the conversation. Codex configuration and runtime warnings also appear in the task.
|
||||
|
||||
## Start a task
|
||||
|
||||
| Action | macOS | Windows / Linux |
|
||||
|
||||
@@ -24,6 +24,7 @@ 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 |
|
||||
@@ -82,6 +83,10 @@ In the editor, **Move…** on a symbol runs the server's move refactoring, where
|
||||
|
||||
These move fields and methods between a class and its superclasses or subclasses, in Java and, with Phoxite as the PHP server, in PHP (methods, properties and constants). A dialog lets you pick the members and the destination; problems the move would cause are listed in **Problems Detected** before you continue. For Java they are provided by the extension bundled with OpenIDEA, for PHP by Phoxite; they are not available for other languages or other PHP servers.
|
||||
|
||||
## 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.
|
||||
|
||||
@@ -32,6 +32,8 @@ OpenIDEA 本身不带模型或账号:它启动你已安装并登录的 agent
|
||||
|
||||
未被标记为受信任的项目中无法使用 agent。
|
||||
|
||||
Codex 有自己的项目信任设置。如果它禁用了当前项目的 `.codex` 配置,任务会询问选择**在 Codex 中信任项目**还是**保持不信任**。选择信任后,会在会话加载配置(包括 MCP 服务器、hooks 和 exec policies)之前,通过 Codex 的配置 API 只写入这个项目的信任条目。即使在 Full Access 模式下也需要这一步确认;选择不信任时配置保持禁用,任务中会显示原因,对话照常进行。Codex 的配置警告和运行时警告也会显示在任务中。
|
||||
|
||||
## 新建任务
|
||||
|
||||
| 操作 | macOS | Windows / Linux |
|
||||
|
||||
@@ -24,6 +24,7 @@ description: "重命名、引入与提取、内联、移动、更改签名和安
|
||||
| **引入字段…** | `⌥⌘F` | `Ctrl+Alt+F` | 语言服务器 |
|
||||
| **引入参数…** | `⌥⌘P` | `Ctrl+Alt+P` | 语言服务器 |
|
||||
| **提取方法…** | `⌥⌘M` | `Ctrl+Alt+M` | 语言服务器 |
|
||||
| **提取接口…** | — | — | Java |
|
||||
| **内联…** | `⌥⌘N` | `Ctrl+Alt+N` | 语言服务器 |
|
||||
| **移动…** | `F6` | `F6` | 语言服务器(符号);IDE(文件和文件夹) |
|
||||
| **安全删除…** | `⌘⌦` | `Alt+Delete` | IDE,借助服务器查找引用 |
|
||||
@@ -75,6 +76,10 @@ description: "重命名、引入与提取、内联、移动、更改签名和安
|
||||
|
||||
用于在类和它的父类或子类之间移动字段和方法:支持 Java,以及使用 Phoxite 作为 PHP 服务器时的 PHP(方法、属性和常量)。在对话框中选择成员和目标类;移动会引起的问题会先在 **检测到问题** 中列出,再决定是否继续。Java 由 OpenIDEA 自带的扩展提供,PHP 由 Phoxite 提供;其他语言和其他 PHP 服务器不可用。
|
||||
|
||||
## 提取接口
|
||||
|
||||
在 Java 中,**重构 › 提取接口…** 会从当前文件的类创建一个接口。在对话框中输入接口名称,选择所在软件包,并勾选接口要声明的方法(以及常量)。**重构** 会创建接口、让该类实现它、在可行的地方把对该类的使用替换为接口,并打开新文件;**预览** 会先列出所有改动。
|
||||
|
||||
## 更改签名
|
||||
|
||||
在 Java 方法上执行 **更改签名…**(`⌘F6`)会打开对话框,可以修改可见性、返回类型和方法名,添加、删除和调整形参顺序。新形参需要填写默认值,所有已有调用处都会传入这个值;勾选 **通过重载方法委托** 会保留旧签名作为重载并调用新方法。签名预览显示修改后的声明。**重构** 会一次更新方法本身、覆盖它的方法和所有调用;**预览** 先列出改动。其他语言在服务器把签名重写作为代码操作提供时才会出现。
|
||||
|
||||
@@ -60,6 +60,70 @@ const entries: AgentEntry[] = [
|
||||
},
|
||||
];
|
||||
|
||||
for (const choice of ["codex-trust-project", "codex-keep-untrusted"]) {
|
||||
test(`project trust has explicit choices and submits ${choice}`, async ({ page }, testInfo) => {
|
||||
await page.setViewportSize({ width: 1050, height: 800 });
|
||||
await page.goto("/");
|
||||
await page.getByRole("tree", { name: "Project" }).waitFor();
|
||||
await page.evaluate(
|
||||
async ({ task }) => {
|
||||
const path = "/src/features/agents/store.ts";
|
||||
const store = await import(path);
|
||||
store.useAgents.setState({
|
||||
loaded: true,
|
||||
tasks: new Map([[task.id, task]]),
|
||||
entries: new Map([
|
||||
[
|
||||
task.id,
|
||||
[
|
||||
{ type: "user", text: "Load the project's MCP configuration.", attachments: [], steered: false },
|
||||
{ type: "error", message: "Project-local config is disabled until the project is trusted in Codex." },
|
||||
{
|
||||
type: "permission",
|
||||
id: 2,
|
||||
title:
|
||||
"Trust project in Codex: /dev/acme-api? This saves trust in your Codex user configuration and allows this project's MCP servers, hooks and exec policies to load.",
|
||||
command: null,
|
||||
options: [
|
||||
{ id: "codex-trust-project", name: "Trust Project in Codex", kind: "allow_always" },
|
||||
{ id: "codex-keep-untrusted", name: "Keep Untrusted", kind: "reject_once" },
|
||||
],
|
||||
chosen: null,
|
||||
},
|
||||
],
|
||||
],
|
||||
]),
|
||||
});
|
||||
store.openTaskInEditorLocation(task.id);
|
||||
const ipcPath = "/src/platform/ipc.ts";
|
||||
(await import(ipcPath)).commands.agentRespond = async (task: string, permission: number, option: string) => {
|
||||
(window as unknown as { trustAnswer: unknown }).trustAnswer = { task, permission, option };
|
||||
return { status: "ok", data: null };
|
||||
};
|
||||
},
|
||||
{ task },
|
||||
);
|
||||
const card = page.getByRole("region", { name: "Trust Project in Codex" });
|
||||
await expect(card).toBeVisible();
|
||||
await expect(
|
||||
page.getByText("Project-local config is disabled until the project is trusted in Codex."),
|
||||
).toBeVisible();
|
||||
await expect(card.getByRole("button")).toHaveText(["Trust Project in Codex", "Keep Untrusted"]);
|
||||
await expect(card).toContainText("MCP servers, hooks and exec policies");
|
||||
expect(await page.evaluate(() => (window as unknown as { trustAnswer?: unknown }).trustAnswer)).toBeUndefined();
|
||||
await page.screenshot({ path: testInfo.outputPath("project-trust-confirmation.png"), animations: "disabled" });
|
||||
await card
|
||||
.getByRole("button", {
|
||||
name: choice === "codex-trust-project" ? "Trust Project in Codex" : "Keep Untrusted",
|
||||
exact: true,
|
||||
})
|
||||
.click();
|
||||
await expect
|
||||
.poll(() => page.evaluate(() => (window as unknown as { trustAnswer?: unknown }).trustAnswer))
|
||||
.toEqual({ task: task.id, permission: 2, option: choice });
|
||||
});
|
||||
}
|
||||
|
||||
for (const theme of ["dark", "light"] as const) {
|
||||
for (const width of [760, 1400]) {
|
||||
test(`approval is asked above the composer at ${width}px in ${theme}`, async ({ page }) => {
|
||||
|
||||
@@ -219,8 +219,11 @@ 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(modelButton(page)).toHaveAttribute("title", new RegExp(`Reasoning: ${name}(?: ·|$)`));
|
||||
await expect(effortButton(page)).toHaveText(name);
|
||||
}
|
||||
async function selected(box: Locator) {
|
||||
return box.evaluate((element) => {
|
||||
@@ -255,7 +258,7 @@ async function selectDraft(page: Page) {
|
||||
}
|
||||
async function chooseModel(page: Page, name: string) {
|
||||
await modelButton(page).click();
|
||||
// A model row also holds its Configure button, whose label joins the option's name.
|
||||
// A model row also holds its Pin 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();
|
||||
@@ -292,7 +295,7 @@ for (const placement of ["editor", "toolWindow"] as const) {
|
||||
option: effortId,
|
||||
value,
|
||||
});
|
||||
await expect(page.getByRole("dialog", { name: "Model & effort settings", exact: true })).toHaveCount(0);
|
||||
await expect(page.getByRole("listbox", { name: "Reasoning", exact: true })).toHaveCount(0);
|
||||
}
|
||||
await expectNoSubmission(page);
|
||||
await stream.click({ position: { x: 12, y: 20 } });
|
||||
@@ -350,7 +353,7 @@ test("subagent conversation never changes its hidden parent's effort", async ({
|
||||
await expectEffort(page, "Gentle");
|
||||
});
|
||||
|
||||
test("Settings and model popup exclude the agent shortcut", async ({ workbench: page }) => {
|
||||
test("Settings and effort popup exclude the agent shortcut", async ({ workbench: page }) => {
|
||||
await seed(page, "editor");
|
||||
await box(page).fill(draft);
|
||||
await page.keyboard.press("Meta+,");
|
||||
@@ -361,14 +364,10 @@ test("Settings and model 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 modelButton(page).click();
|
||||
const popup = page.getByRole("dialog", { name: "Model & effort settings", exact: true });
|
||||
await effortButton(page).click();
|
||||
const popup = page.getByRole("listbox", { name: "Reasoning", 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,3 +1,4 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import { expect, test } from "./fixtures";
|
||||
|
||||
test.beforeEach(async ({ workbench: page }) => {
|
||||
@@ -52,7 +53,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 expect(page.getByText("omp · 18.20.0 · ACP v1", { exact: true })).toBeVisible();
|
||||
await expectVersion(page, "18.20.0");
|
||||
});
|
||||
|
||||
test("refreshes an upgraded agent's version on window focus without losing the draft", async ({ workbench: page }) => {
|
||||
@@ -63,7 +64,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 expect(page.getByText("omp · 18.20.2 · ACP v1", { exact: true })).toBeVisible();
|
||||
await expectVersion(page, "18.20.2");
|
||||
await expect(message).toHaveText("Keep this unsent draft");
|
||||
});
|
||||
|
||||
@@ -71,5 +72,10 @@ 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 expect(page.getByText("omp · 18.20.2 · ACP v1", { exact: true })).toBeVisible();
|
||||
await expectVersion(page, "18.20.2");
|
||||
});
|
||||
|
||||
/** 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);
|
||||
}
|
||||
@@ -167,3 +167,49 @@ test("terminal ⌘F highlights active/inactive search matches and seeds with a n
|
||||
await expect(input).toHaveValue("gamma");
|
||||
await expect(search.locator("[aria-live=polite]")).toHaveText(/\d+\/2/);
|
||||
});
|
||||
|
||||
test("terminal shows URLs in the link colour with an underline without hovering, in light and dark themes", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.evaluate(async () => {
|
||||
const path = "/src/workbench/toolwindows/store.ts";
|
||||
const layout = await import(path);
|
||||
layout.showToolWindow("terminal", true);
|
||||
});
|
||||
const terminal = page.getByRole("region", { name: "Terminal", exact: true });
|
||||
await expect(terminal.locator(".xterm-helper-textarea")).toBeFocused();
|
||||
await page.evaluate(async () => {
|
||||
const path = "/src/features/terminal/runtime.ts";
|
||||
const { activeSession } = await import(path);
|
||||
const s = activeSession()!;
|
||||
s.term.reset();
|
||||
await new Promise<void>((resolve) =>
|
||||
s.term.write(
|
||||
" ➜ Local: http://localhost:5173/\r\n文档 https://example.com/docs 和 https://example.org/a\r\nno link\r\n",
|
||||
resolve,
|
||||
),
|
||||
);
|
||||
});
|
||||
const links = terminal.locator(".openidea-terminal-link");
|
||||
await expect(links).toHaveCount(3);
|
||||
|
||||
for (const theme of ["light", "dark"]) {
|
||||
const link = await page.evaluate(async (theme) => {
|
||||
const path = "/src/workbench/theme.ts";
|
||||
const { setTheme } = await import(path);
|
||||
await setTheme(theme);
|
||||
const probe = document.createElement("span");
|
||||
probe.style.color = "var(--link)";
|
||||
document.body.append(probe);
|
||||
const color = getComputedStyle(probe).color;
|
||||
probe.remove();
|
||||
return color;
|
||||
}, theme);
|
||||
await expect(page.locator("html")).toHaveAttribute("data-theme", theme);
|
||||
// The underline and the recoloured text both follow the theme's `--link`.
|
||||
await expect(links.first()).toHaveCSS("border-bottom-color", link);
|
||||
await expect(terminal.locator(".xterm-rows span", { hasText: /^h$/ }).first()).toHaveCSS("color", link);
|
||||
if (process.env.OPENIDEA_TERMINAL_SHOTS)
|
||||
await terminal.screenshot({ path: `${process.env.OPENIDEA_TERMINAL_SHOTS}/terminal-links-${theme}.png` });
|
||||
}
|
||||
});
|
||||
@@ -2,7 +2,7 @@ Manifest-Version: 1.0
|
||||
Bundle-ManifestVersion: 2
|
||||
Bundle-Name: OpenIDEA Java usages
|
||||
Bundle-SymbolicName: ai.openidea.usages;singleton:=true
|
||||
Bundle-Version: 1.14.0
|
||||
Bundle-Version: 1.15.0
|
||||
Bundle-RequiredExecutionEnvironment: JavaSE-21
|
||||
Require-Bundle: org.eclipse.jdt.ls.core,org.eclipse.jdt.core,
|
||||
org.eclipse.jdt.core.manipulation,org.eclipse.core.runtime,
|
||||
|
||||
@@ -88,7 +88,7 @@ is not a claim of full IntelliJ feature parity.
|
||||
## Rebuild and delivery
|
||||
|
||||
The checked-in jar is embedded by ide-sdk `include_bytes!`, installed as
|
||||
`java-usages-1.13.0.jar`, and added alongside existing initialization bundles.
|
||||
`java-usages-1.15.0.jar`, and added alongside existing initialization bundles.
|
||||
Users need no compiler, Maven or Python. Manifest/install version must change
|
||||
when replacing the bundle because OSGi caches bundles.
|
||||
|
||||
@@ -133,6 +133,9 @@ its reproducible SHA-256 is
|
||||
Version 1.12.0 caches usages answers until the Java model or an unsaved edit changes and adds
|
||||
`openidea.workspace.coveredRoots`; its reproducible SHA-256 is
|
||||
`c1bd28d7b956cb64af3e936aac0553413a5dc5fd373a043ddba003009e0ea783`.
|
||||
Version 1.15.0 adds `openidea.java.implementationLocations`, which resolves the method an
|
||||
implementation in a dependency declares (the standard request starts at its class file); its
|
||||
reproducible SHA-256 is `c29e5455c02c245523b2e7a5861e00ae670cefc66cda33ec19fdce280f94c40c`.
|
||||
|
||||
```sh
|
||||
export PATH=/path/to/jdk25/bin:$PATH
|
||||
|
||||
Бінарний файл не відображається.
@@ -20,6 +20,9 @@
|
||||
<delegateCommandHandler class="ai.openidea.archives.RefreshArchivesCommand">
|
||||
<command id="openidea.java.refreshArchives"/>
|
||||
</delegateCommandHandler>
|
||||
<delegateCommandHandler class="ai.openidea.implementations.ImplementationTargetsCommand">
|
||||
<command id="openidea.java.implementationLocations"/>
|
||||
</delegateCommandHandler>
|
||||
<delegateCommandHandler class="ai.openidea.hierarchy.HierarchyCommand">
|
||||
<command id="openidea.java.hierarchy.members"/>
|
||||
<command id="openidea.java.hierarchy.refactor"/>
|
||||
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
package ai.openidea.implementations;
|
||||
|
||||
import ai.openidea.Documents;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import org.eclipse.core.runtime.IProgressMonitor;
|
||||
import org.eclipse.core.runtime.OperationCanceledException;
|
||||
import org.eclipse.jdt.core.*;
|
||||
import org.eclipse.jdt.internal.corext.util.MethodOverrideTester;
|
||||
import org.eclipse.jdt.ls.core.internal.IDelegateCommandHandler;
|
||||
import org.eclipse.jdt.ls.core.internal.JDTUtils;
|
||||
import org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin;
|
||||
import org.eclipse.lsp4j.Location;
|
||||
|
||||
/**
|
||||
* Where the implementations of the method at a position declare it, in the classes named by the
|
||||
* caller: one location per target URI, or null when the target has no such method. The standard
|
||||
* implementation request answers with the start of a class file's decompiled source for an
|
||||
* implementation in a dependency; this resolves the method's own declaration there.
|
||||
*/
|
||||
public final class ImplementationTargetsCommand implements IDelegateCommandHandler {
|
||||
@Override
|
||||
public Object executeCommand(String command, List<Object> arguments, IProgressMonitor monitor) throws Exception {
|
||||
Documents.awaitChanges(monitor);
|
||||
String uri = (String) arguments.get(0);
|
||||
int line = ((Number) arguments.get(1)).intValue();
|
||||
int column = ((Number) arguments.get(2)).intValue();
|
||||
@SuppressWarnings("unchecked")
|
||||
List<String> targets = (List<String>) arguments.get(3);
|
||||
ITypeRoot root = JDTUtils.resolveTypeRoot(uri, true, monitor);
|
||||
if (root == null) return Map.of("locations", List.of());
|
||||
try {
|
||||
var preferences = JavaLanguageServerPlugin.getPreferencesManager();
|
||||
IJavaElement element = JDTUtils.findElementAtSelection(root, line, column, preferences, monitor);
|
||||
if (!(element instanceof IMethod method)) return Map.of("locations", List.of());
|
||||
List<Location> locations = new ArrayList<>(targets.size());
|
||||
for (String targetUri : targets) {
|
||||
if (monitor.isCanceled()) throw new OperationCanceledException();
|
||||
locations.add(find(method, targetUri, monitor));
|
||||
}
|
||||
return Map.of("locations", locations);
|
||||
} finally {
|
||||
JDTUtils.discardClassFileWorkingCopy(root);
|
||||
}
|
||||
}
|
||||
|
||||
/** The declaration of {@code method}'s implementation in the class {@code targetUri}, or null. */
|
||||
private static Location find(IMethod method, String targetUri, IProgressMonitor monitor) throws JavaModelException {
|
||||
ITypeRoot targetRoot = JDTUtils.resolveTypeRoot(targetUri);
|
||||
if (targetRoot == null) return null;
|
||||
IType target = targetRoot.findPrimaryType();
|
||||
if (target == null) return null;
|
||||
ITypeHierarchy hierarchy = target.newSupertypeHierarchy(monitor);
|
||||
// Seen from the subtype, so its type arguments substitute the method's type variables.
|
||||
IMethod found = new MethodOverrideTester(target, hierarchy).findOverridingMethodInType(target, method);
|
||||
if (found == null || Flags.isAbstract(found.getFlags())) return null;
|
||||
IClassFile classFile = found.getClassFile();
|
||||
if (classFile == null) return JDTUtils.toLocation(found);
|
||||
List<Location> decompiled = JDTUtils.searchDecompiledSources(found, classFile, true, true, monitor);
|
||||
return decompiled.isEmpty() ? null : decompiled.get(0);
|
||||
}
|
||||
}
|
||||
@@ -23,9 +23,30 @@ config_source = next(home / name / 'config.ini' for name in config_names if (hom
|
||||
(config / 'config.ini').write_bytes(config_source.read_bytes())
|
||||
project = work / 'project'
|
||||
(project / 'src/zoo').mkdir(parents=True)
|
||||
(project / 'lib').mkdir()
|
||||
libs = work / 'libsrc/zoo'
|
||||
libs.mkdir(parents=True)
|
||||
(libs / 'ExternalRepo.java').write_text('''package zoo;
|
||||
|
||||
public interface ExternalRepo {
|
||||
String find(String id, int limit);
|
||||
}
|
||||
''')
|
||||
(libs / 'ExternalImpl.java').write_text('''package zoo;
|
||||
|
||||
public class ExternalImpl implements ExternalRepo {
|
||||
public String find(String id, int limit) {
|
||||
return id + limit;
|
||||
}
|
||||
}
|
||||
''')
|
||||
lib_classes = work / 'libclasses'
|
||||
lib_classes.mkdir()
|
||||
subprocess.run(['javac', '--release', '8', '-d', str(lib_classes)] + [str(p) for p in libs.glob('*.java')], check=True)
|
||||
subprocess.run(['jar', 'cf', str(project / 'lib/external-api.jar'), '-C', str(lib_classes), '.'], check=True)
|
||||
(project / '.project').write_text('<projectDescription><name>zoo</name><buildSpec><buildCommand><name>org.eclipse.jdt.core.javabuilder</name></buildCommand></buildSpec><natures><nature>org.eclipse.jdt.core.javanature</nature></natures></projectDescription>')
|
||||
# `kotlin`: the project's compiled Kotlin classes, as the Kotlin bridge attaches them.
|
||||
(project / '.classpath').write_text('<classpath><classpathentry kind="src" path="src"/><classpathentry kind="lib" path="kotlin"><attributes><attribute name="ai.openidea.kotlin" value="true"/></attributes></classpathentry><classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/><classpathentry kind="output" path="bin"/></classpath>')
|
||||
(project / '.classpath').write_text('<classpath><classpathentry kind="src" path="src"/><classpathentry kind="lib" path="lib/external-api.jar"/><classpathentry kind="lib" path="kotlin"><attributes><attribute name="ai.openidea.kotlin" value="true"/></attributes></classpathentry><classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/><classpathentry kind="output" path="bin"/></classpath>')
|
||||
sources = {
|
||||
'Repo.java': '''package zoo;
|
||||
|
||||
@@ -87,6 +108,14 @@ public class Anon {
|
||||
};
|
||||
}
|
||||
}
|
||||
''',
|
||||
'UseExternal.java': '''package zoo;
|
||||
|
||||
public class UseExternal {
|
||||
void use(ExternalRepo repo) {
|
||||
repo.find("x", 1);
|
||||
}
|
||||
}
|
||||
''',
|
||||
'Use.java': '''package zoo;
|
||||
|
||||
@@ -180,6 +209,28 @@ def implementations(file, needle):
|
||||
return sorted(names), found['complete']
|
||||
|
||||
|
||||
def definition(file, needle):
|
||||
line, col = position(file, needle)
|
||||
return request('textDocument/definition', {'textDocument': {'uri': uri(file)}, 'position': {'line': line, 'character': col}})
|
||||
|
||||
|
||||
def class_contents(class_uri):
|
||||
return request('java/classFileContents', {'uri': class_uri})
|
||||
|
||||
|
||||
def standard_implementations(class_uri, line, col):
|
||||
found = request('textDocument/implementation', {'textDocument': {'uri': class_uri}, 'position': {'line': line, 'character': col}})
|
||||
return found or []
|
||||
|
||||
|
||||
def implementation_locations(class_uri, line, col, targets):
|
||||
found = command('openidea.java.implementationLocations', class_uri, line, col, targets)
|
||||
return [
|
||||
(pathlib.Path(urllib.parse.unquote(urllib.parse.urlparse(loc['uri']).path)).name, loc['range']['start']['line'])
|
||||
for loc in found['locations'] if loc is not None
|
||||
]
|
||||
|
||||
|
||||
try:
|
||||
init = request('initialize', {'processId': None, 'rootUri': project.as_uri(), 'workspaceFolders': [{'uri': project.as_uri(), 'name': 'zoo'}], 'capabilities': {}, 'initializationOptions': {'bundles': [str(bundle)], 'extendedClientCapabilities': {'classFileContentsSupport': True}, 'settings': {'java': {'import': {'gradle': {'enabled': False}, 'maven': {'enabled': False}}}}}})
|
||||
assert 'openidea.java.implementations' in init['capabilities']['executeCommandProvider']['commands']
|
||||
@@ -207,6 +258,20 @@ try:
|
||||
if actual != expected:
|
||||
failures.append((file, needle, expected, actual))
|
||||
assert not failures, failures
|
||||
|
||||
# An interface in a dependency: the standard request starts at the class file, and the
|
||||
# extension resolves the implementing method's declaration in the dependency.
|
||||
defs = definition('UseExternal.java', 'ExternalRepo repo')
|
||||
class_uri = defs[0]['uri']
|
||||
text = class_contents(class_uri)
|
||||
method_line = next(i for i, line in enumerate(text.splitlines()) if 'find(' in line)
|
||||
method_col = text.splitlines()[method_line].index('find')
|
||||
std = standard_implementations(class_uri, method_line, method_col)
|
||||
targets = [loc['uri'] for loc in std]
|
||||
resolved = implementation_locations(class_uri, method_line, method_col, targets)
|
||||
print('dependency implementation:', resolved)
|
||||
expected = [(pathlib.Path(urllib.parse.unquote(urllib.parse.urlparse(targets[0]).path)).name, 7)]
|
||||
assert resolved == expected, (resolved, expected)
|
||||
print('ok')
|
||||
finally:
|
||||
proc.kill()
|
||||
|
||||
@@ -97,6 +97,22 @@ pub async fn lsp_goto_implementation(
|
||||
ide_host::ops::lsp::lsp_goto_implementation(&state.host, window.label(), request, doc, pos, on_partial).await
|
||||
}
|
||||
|
||||
/// Refines the implementations `targets` of the method at `pos` to their declarations (Java
|
||||
/// dependencies' class files point at the start of the class). Cancel with
|
||||
/// `cancel_request(request)`.
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn lsp_implementation_locations(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
request: RequestId,
|
||||
doc: DocId,
|
||||
pos: Pos,
|
||||
targets: Vec<Location>,
|
||||
) -> IdeResult<Vec<Location>> {
|
||||
ide_host::ops::lsp::lsp_implementation_locations(&state.host, window.label(), request, doc, pos, targets).await
|
||||
}
|
||||
|
||||
/// Implementations of the symbols at `positions`, one list per position (the
|
||||
/// editor's "is implemented / overridden" gutter markers). Cancel with
|
||||
/// `cancel_request(request)`.
|
||||
@@ -395,6 +411,46 @@ pub async fn lsp_java_move(
|
||||
ide_host::ops::lsp::lsp_java_move(&state.host, window.label(), request, doc, kind, args, confirmation).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn lsp_extract_interface_info(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
request: RequestId,
|
||||
doc: DocId,
|
||||
pos: Pos,
|
||||
) -> IdeResult<ExtractInterfaceInfo> {
|
||||
ide_host::ops::lsp::lsp_extract_interface_info(&state.host, window.label(), request, doc, pos).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn lsp_extract_interface(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
request: RequestId,
|
||||
doc: DocId,
|
||||
pos: Pos,
|
||||
members: Vec<String>,
|
||||
name: String,
|
||||
destination: String,
|
||||
confirmation: Option<String>,
|
||||
) -> IdeResult<ServerRefactored> {
|
||||
ide_host::ops::lsp::lsp_extract_interface(
|
||||
&state.host,
|
||||
window.label(),
|
||||
request,
|
||||
doc,
|
||||
pos,
|
||||
members,
|
||||
name,
|
||||
destination,
|
||||
confirmation,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn lsp_format(
|
||||
|
||||
@@ -287,6 +287,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
|
||||
lsp::lsp_goto,
|
||||
lsp::lsp_implementations,
|
||||
lsp::lsp_goto_implementation,
|
||||
lsp::lsp_implementation_locations,
|
||||
lsp::lsp_virtual_document,
|
||||
lsp::lsp_can_download_sources,
|
||||
lsp::lsp_library_sources,
|
||||
@@ -304,6 +305,8 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
|
||||
lsp::lsp_hierarchy_refactor,
|
||||
lsp::lsp_signature_info,
|
||||
lsp::lsp_change_signature,
|
||||
lsp::lsp_extract_interface_info,
|
||||
lsp::lsp_extract_interface,
|
||||
lsp::lsp_java_move_destinations,
|
||||
lsp::lsp_java_source_types,
|
||||
lsp::lsp_java_move,
|
||||
|
||||
@@ -594,6 +594,7 @@ pub fn spec(os: Os) -> Vec<Entry> {
|
||||
act("refactor.extractField", "Introduce Field…"),
|
||||
act("refactor.extractParameter", "Introduce Parameter…"),
|
||||
act("refactor.extractMethod", "Extract Method…"),
|
||||
act("refactor.extractInterface", "Extract Interface…"),
|
||||
act("refactor.inline", "Inline…"),
|
||||
SEP,
|
||||
act("refactor.pullMembersUp", "Pull Members Up…"),
|
||||
|
||||
@@ -306,12 +306,15 @@ lsp_document_highlights trusted project_host bin
|
||||
lsp_document_links trusted project_host bindings async
|
||||
lsp_execute_code_action trusted project_host bindings async
|
||||
lsp_execute_command trusted project_host bindings async
|
||||
lsp_extract_interface trusted project_host bindings async
|
||||
lsp_extract_interface_info trusted project_host bindings async
|
||||
lsp_format trusted project_host bindings async
|
||||
lsp_goto trusted project_host bindings async
|
||||
lsp_goto_implementation trusted project_host bindings async
|
||||
lsp_hierarchy_members trusted project_host bindings async
|
||||
lsp_hierarchy_refactor trusted project_host bindings async
|
||||
lsp_hover trusted project_host bindings async
|
||||
lsp_implementation_locations trusted project_host bindings async
|
||||
lsp_implementations trusted project_host bindings async
|
||||
lsp_inlay_hints trusted project_host bindings async
|
||||
lsp_inline_completion trusted project_host bindings async
|
||||
|
||||
+30
-1
@@ -597,6 +597,12 @@ export const commands = {
|
||||
* Cancel with `cancel_request(request)`.
|
||||
*/
|
||||
lspGotoImplementation: (request: RequestId, doc: DocId, pos: Pos, onPartial: Channel<Location[]>) => typedError<Location[], IdeError>(__TAURI_INVOKE("lsp_goto_implementation", { request, doc, pos, onPartial })),
|
||||
/**
|
||||
* Refines the implementations `targets` of the method at `pos` to their declarations (Java
|
||||
* dependencies' class files point at the start of the class). Cancel with
|
||||
* `cancel_request(request)`.
|
||||
*/
|
||||
lspImplementationLocations: (request: RequestId, doc: DocId, pos: Pos, targets: Location[]) => typedError<Location[], IdeError>(__TAURI_INVOKE("lsp_implementation_locations", { request, doc, pos, targets })),
|
||||
/**
|
||||
* Contents of a read-only language-server document, including JDT library
|
||||
* classes and disk class files. Cached per project.
|
||||
@@ -644,6 +650,8 @@ export const commands = {
|
||||
lspHierarchyRefactor: (request: RequestId, doc: DocId, pos: Pos, kind: HierarchyRefactoring, target: string | null, choices: HierarchyChoice[]) => typedError<HierarchyRefactored, IdeError>(__TAURI_INVOKE("lsp_hierarchy_refactor", { request, doc, pos, kind, target, choices })),
|
||||
lspSignatureInfo: (request: RequestId, doc: DocId, pos: Pos) => typedError<MethodSignature, IdeError>(__TAURI_INVOKE("lsp_signature_info", { request, doc, pos })),
|
||||
lspChangeSignature: (request: RequestId, doc: DocId, pos: Pos, signature: MethodSignature, delegate: boolean, confirmation: string | null) => typedError<ServerRefactored, IdeError>(__TAURI_INVOKE("lsp_change_signature", { request, doc, pos, signature, delegate, confirmation })),
|
||||
lspExtractInterfaceInfo: (request: RequestId, doc: DocId, pos: Pos) => typedError<ExtractInterfaceInfo, IdeError>(__TAURI_INVOKE("lsp_extract_interface_info", { request, doc, pos })),
|
||||
lspExtractInterface: (request: RequestId, doc: DocId, pos: Pos, members: string[], name: string, destination: string, confirmation: string | null) => typedError<ServerRefactored, IdeError>(__TAURI_INVOKE("lsp_extract_interface", { request, doc, pos, members, name, destination, confirmation })),
|
||||
lspJavaMoveDestinations: (request: RequestId, doc: DocId, kind: string, args: string) => typedError<string[], IdeError>(__TAURI_INVOKE("lsp_java_move_destinations", { request, doc, kind, args })),
|
||||
lspJavaSourceTypes: (request: RequestId, doc: DocId, projectName: string | null) => typedError<string[], IdeError>(__TAURI_INVOKE("lsp_java_source_types", { request, doc, projectName })),
|
||||
lspJavaMove: (request: RequestId, doc: DocId, kind: string, args: string, confirmation: string | null) => typedError<ServerRefactored, IdeError>(__TAURI_INVOKE("lsp_java_move", { request, doc, kind, args, confirmation })),
|
||||
@@ -5383,6 +5391,16 @@ export type ExternalTool = {
|
||||
openConsole?: boolean,
|
||||
};
|
||||
|
||||
/**
|
||||
* What Extract Interface starts from: the file's class, the members the interface can declare and
|
||||
* the packages it can go to (as JSON, passed back unchanged).
|
||||
*/
|
||||
export type ExtractInterfaceInfo = {
|
||||
className: string,
|
||||
members: InterfaceMember[],
|
||||
packages: string[],
|
||||
};
|
||||
|
||||
/** Framework facet attached to a module (Project Structure › Facets). */
|
||||
export type FacetConfig = {
|
||||
/** `"web"` | `"spring"` | `"jpa"`. */
|
||||
@@ -6774,6 +6792,17 @@ export type IntellijThemeSource = {
|
||||
themes: IntellijThemeFile[],
|
||||
};
|
||||
|
||||
/** A member Extract Interface can declare in the new interface. */
|
||||
export type InterfaceMember = {
|
||||
name: string,
|
||||
/** The method's return type or the field's type. */
|
||||
typeName: string,
|
||||
/** The method's parameter types; `None` for a field. */
|
||||
parameters: string[] | null,
|
||||
/** The server's handle of the member, passed back unchanged. */
|
||||
handleIdentifier: string,
|
||||
};
|
||||
|
||||
/** Optional parts of the invalidation; the symbol index is always rebuilt. */
|
||||
export type InvalidateCachesOptions = {
|
||||
/** Local History of every project. */
|
||||
@@ -10055,7 +10084,7 @@ export type ServerInfo = {
|
||||
};
|
||||
|
||||
/**
|
||||
* A refactoring checked by the server (Change Signature, Move): problems to show, the edit when
|
||||
* A refactoring checked by the server (Change Signature, Move, Extract Interface): problems to show, the edit when
|
||||
* none is fatal, and the token that confirms going on despite warnings.
|
||||
*/
|
||||
export type ServerRefactored = {
|
||||
|
||||
@@ -34,7 +34,7 @@ import type { LineEnding } from "@/platform/ipc";
|
||||
import { create } from "zustand";
|
||||
import { maybeEditorService } from "@/workbench/contributions";
|
||||
import { cornerInset } from "@/editor/core/cm/cornerInset";
|
||||
export { iconAreaSource, type IconAreaSource } from "@/editor/core/cm/iconArea";
|
||||
export { iconAreaSource, mapLineStart, type IconAreaSource } from "@/editor/core/cm/iconArea";
|
||||
|
||||
/** Documents above this size (UTF-16 units) skip per-line decorations. */
|
||||
export const HEAVY_LIMIT = 8_000_000;
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { fireEvent } from "@testing-library/react";
|
||||
import { EditorState, RangeSet } from "@codemirror/state";
|
||||
import { EditorState, RangeSet, StateEffect, StateField } from "@codemirror/state";
|
||||
import { EditorView, GutterMarker } from "@codemirror/view";
|
||||
import { iconAreaExtension, iconAreaSource } from "./iconArea";
|
||||
import { SETTLE_MS, iconAreaExtension, iconAreaSource, mapLineStart } from "./iconArea";
|
||||
|
||||
class Dot extends GutterMarker {
|
||||
constructor(readonly name: string) {
|
||||
@@ -73,3 +73,99 @@ it("keeps an icon's width only while a source asks for it", () => {
|
||||
const v = open([{ order: 1, markers: () => RangeSet.empty, reserve: () => true }]);
|
||||
expect(v.dom.querySelector(".cm-openidea-iconArea .cm-openidea-iconSpacer")).toBeTruthy();
|
||||
});
|
||||
|
||||
describe("while edits place icons again", () => {
|
||||
// Line numbers each source has an icon on, as set by the test.
|
||||
const setRun = StateEffect.define<number[]>();
|
||||
const setImpl = StateEffect.define<number[]>();
|
||||
const linesField = (effect: typeof setRun, initial: number[]) =>
|
||||
StateField.define<number[]>({
|
||||
create: () => initial,
|
||||
update: (value, tr) => tr.effects.find((e) => e.is(effect))?.value ?? value,
|
||||
});
|
||||
const run = linesField(setRun, [2]);
|
||||
const impl = linesField(setImpl, [2]);
|
||||
const dots = (name: string, field: StateField<number[]>) => (view: EditorView) =>
|
||||
RangeSet.of(view.state.field(field).map((l) => new Dot(name).range(lineStart(view.state, l))));
|
||||
|
||||
const spacerIcons = (v: EditorView) => v.dom.querySelectorAll(".cm-openidea-iconSpacer").length;
|
||||
|
||||
beforeEach(() => vi.useFakeTimers());
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
function openTwoSources() {
|
||||
view = new EditorView({
|
||||
state: EditorState.create({
|
||||
doc: DOC,
|
||||
extensions: [
|
||||
run,
|
||||
impl,
|
||||
iconAreaExtension,
|
||||
iconAreaSource.of({ order: 10, markers: dots("run", run) }),
|
||||
iconAreaSource.of({ order: 50, markers: dots("impl", impl) }),
|
||||
],
|
||||
}),
|
||||
parent: document.body,
|
||||
});
|
||||
return view;
|
||||
}
|
||||
|
||||
// Enter at the start of line 2: the run icon moves to line 3 first, the inheritance icon later.
|
||||
const pressEnter = (v: EditorView) => v.dispatch({ changes: { from: lineStart(v.state, 2), insert: "\n" } });
|
||||
|
||||
it("keeps the widest line's width while a line's icons are apart, then narrows once they settle", () => {
|
||||
const v = openTwoSources();
|
||||
expect(spacerIcons(v)).toBe(2);
|
||||
|
||||
pressEnter(v);
|
||||
v.dispatch({ effects: setRun.of([3]) });
|
||||
expect(spacerIcons(v)).toBe(2);
|
||||
vi.advanceTimersByTime(SETTLE_MS - 1);
|
||||
v.dispatch({ effects: setImpl.of([3]) });
|
||||
expect(spacerIcons(v)).toBe(2);
|
||||
|
||||
// An icon that really went away: the area narrows only after nothing changed for a while.
|
||||
v.dispatch({ effects: setImpl.of([]) });
|
||||
vi.advanceTimersByTime(SETTLE_MS - 1);
|
||||
expect(spacerIcons(v)).toBe(2);
|
||||
vi.advanceTimersByTime(1);
|
||||
expect(spacerIcons(v)).toBe(1);
|
||||
});
|
||||
|
||||
it("does not narrow while typing goes on", () => {
|
||||
const v = openTwoSources();
|
||||
v.dispatch({ effects: setImpl.of([]) });
|
||||
for (let i = 0; i < 5; i++) {
|
||||
vi.advanceTimersByTime(SETTLE_MS / 2);
|
||||
pressEnter(v);
|
||||
expect(spacerIcons(v)).toBe(2);
|
||||
}
|
||||
vi.advanceTimersByTime(SETTLE_MS);
|
||||
expect(spacerIcons(v)).toBe(1);
|
||||
});
|
||||
|
||||
it("widens at once", () => {
|
||||
const v = openTwoSources();
|
||||
v.dispatch({ effects: setImpl.of([]) });
|
||||
vi.advanceTimersByTime(SETTLE_MS);
|
||||
expect(spacerIcons(v)).toBe(1);
|
||||
pressEnter(v);
|
||||
v.dispatch({ effects: setImpl.of([2]) });
|
||||
expect(spacerIcons(v)).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
it("moves a line's marker down with its text when Enter is pressed at the line's start", () => {
|
||||
const state = EditorState.create({ doc: "a\nclass B {}\nc" });
|
||||
const lineB = state.doc.line(2).from;
|
||||
const tr = state.update({ changes: { from: lineB, insert: "\n" } });
|
||||
expect(mapLineStart(tr, lineB)).toBe(tr.state.doc.line(3).from);
|
||||
const after = (from: number, insert: string, to = from) =>
|
||||
mapLineStart(state.update({ changes: { from, to, insert } }), lineB);
|
||||
// Other edits keep it at the start of its line.
|
||||
expect(after(lineB, " ")).toBe(lineB);
|
||||
expect(after(1, "\nnew")).toBe(lineB + 4);
|
||||
expect(after(lineB + 5, "\n")).toBe(lineB);
|
||||
// Joined into the line above, it goes with its text.
|
||||
expect(after(1, "", lineB)).toBe(0);
|
||||
});
|
||||
@@ -3,8 +3,16 @@
|
||||
* rendered-doc toggle share one column, as wide as the most icons on any line, instead of a
|
||||
* column per kind that stays empty on the lines where another kind has its icon.
|
||||
*/
|
||||
import { Facet, type EditorState, type Extension, type RangeSet } from "@codemirror/state";
|
||||
import { EditorView, GutterMarker, gutter, type BlockInfo, type ViewUpdate, type WidgetType } from "@codemirror/view";
|
||||
import { Facet, type EditorState, type Extension, type RangeSet, type Transaction } from "@codemirror/state";
|
||||
import {
|
||||
EditorView,
|
||||
GutterMarker,
|
||||
ViewPlugin,
|
||||
gutter,
|
||||
type BlockInfo,
|
||||
type ViewUpdate,
|
||||
type WidgetType,
|
||||
} from "@codemirror/view";
|
||||
|
||||
export interface IconAreaSource {
|
||||
/** Left to right within a line: lower first. */
|
||||
@@ -20,23 +28,94 @@ export interface IconAreaSource {
|
||||
mousedown?(view: EditorView, block: BlockInfo, event: MouseEvent): boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a marker on the line starting at `pos` goes after `tr`: the start of the line its text is
|
||||
* on now. An Enter at the start of the line moves the marker down with its text, as every source
|
||||
* must agree; one left on the new blank line until its source refreshes would split a line's icons
|
||||
* and briefly narrow the area, shifting the code.
|
||||
*/
|
||||
export function mapLineStart(tr: Transaction, pos: number): number {
|
||||
return tr.state.doc.lineAt(tr.changes.mapPos(pos, 1)).from;
|
||||
}
|
||||
|
||||
export const iconAreaSource = Facet.define<IconAreaSource, readonly IconAreaSource[]>({
|
||||
combine: (sources) => [...sources].sort((a, b) => a.order - b.order),
|
||||
});
|
||||
|
||||
/** The width of one icon, for the reserved column. Hidden; not a button. */
|
||||
/** `count` icons of width, the room the area keeps. Hidden; not buttons. */
|
||||
class IconSpacer extends GutterMarker {
|
||||
constructor(readonly count: number) {
|
||||
super();
|
||||
}
|
||||
override eq(other: GutterMarker): boolean {
|
||||
return other instanceof IconSpacer && other.count === this.count;
|
||||
}
|
||||
override toDOM(): Node {
|
||||
const el = document.createElement("span");
|
||||
el.className = "cm-openidea-iconSpacer";
|
||||
el.className = "cm-openidea-iconAreaSpacer";
|
||||
for (let i = 0; i < this.count; i++)
|
||||
el.appendChild(document.createElement("span")).className = "cm-openidea-iconSpacer";
|
||||
return el;
|
||||
}
|
||||
}
|
||||
|
||||
const iconSpacer = new IconSpacer();
|
||||
const noSpacer = new (class extends GutterMarker {})();
|
||||
|
||||
const reserved = (state: EditorState) => state.facet(iconAreaSource).some((s) => s.reserve?.(state));
|
||||
/** The most icons on one line, at least one while a source reserves room. */
|
||||
function mostIcons(view: EditorView): number {
|
||||
const sources = view.state.facet(iconAreaSource);
|
||||
const lines = new Map<number, number>();
|
||||
let most = sources.some((s) => s.reserve?.(view.state)) ? 1 : 0;
|
||||
for (const s of sources)
|
||||
for (const it = s.markers(view).iter(); it.value; it.next()) {
|
||||
const line = view.state.doc.lineAt(it.from).from;
|
||||
const n = (lines.get(line) ?? 0) + 1;
|
||||
lines.set(line, n);
|
||||
most = Math.max(most, n);
|
||||
}
|
||||
return most;
|
||||
}
|
||||
|
||||
/** How long the text and its icons stay unchanged before the area may narrow. */
|
||||
export const SETTLE_MS = 2000;
|
||||
|
||||
/**
|
||||
* After an edit each source places its icons again on its own schedule (a run icon before the
|
||||
* language server's inheritance icons), so a line's icons briefly part. The area widens at once
|
||||
* but narrows only once nothing changed for `SETTLE_MS`, so the text does not shift back and forth.
|
||||
*/
|
||||
const areaWidth = ViewPlugin.fromClass(
|
||||
class {
|
||||
private holdUntil = 0;
|
||||
/** The most icons on a line now, and the icons of width the spacer keeps. */
|
||||
private icons = 0;
|
||||
private kept = 0;
|
||||
private timer: ReturnType<typeof setTimeout> | undefined;
|
||||
constructor(readonly view: EditorView) {}
|
||||
|
||||
spacer(prev: GutterMarker | null, update: ViewUpdate | null): GutterMarker {
|
||||
const icons = mostIcons(this.view);
|
||||
const now = Date.now();
|
||||
if (update && (update.docChanged || icons !== this.icons)) {
|
||||
this.holdUntil = now + SETTLE_MS;
|
||||
clearTimeout(this.timer);
|
||||
// Once settled, any update asks for the spacer again.
|
||||
this.timer = setTimeout(() => this.kept > this.icons && this.view.dispatch({}), SETTLE_MS);
|
||||
}
|
||||
this.icons = icons;
|
||||
if (prev && now < this.holdUntil && icons < this.kept) return prev;
|
||||
this.kept = icons;
|
||||
return icons ? new IconSpacer(icons) : noSpacer;
|
||||
}
|
||||
|
||||
destroy() {
|
||||
clearTimeout(this.timer);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
const spacer = (view: EditorView, prev: GutterMarker | null, update: ViewUpdate | null) =>
|
||||
view.plugin(areaWidth)?.spacer(prev, update) ?? noSpacer;
|
||||
|
||||
const areaGutter = gutter({
|
||||
class: "cm-openidea-iconArea",
|
||||
@@ -51,8 +130,8 @@ const areaGutter = gutter({
|
||||
lineMarkerChange: (update) =>
|
||||
update.startState.facet(iconAreaSource) !== update.state.facet(iconAreaSource) ||
|
||||
update.state.facet(iconAreaSource).some((s) => s.lineMarkerChange?.(update)),
|
||||
initialSpacer: (view) => (reserved(view.state) ? iconSpacer : noSpacer),
|
||||
updateSpacer: (_spacer, update) => (reserved(update.state) ? iconSpacer : noSpacer),
|
||||
initialSpacer: (view) => spacer(view, null, null),
|
||||
updateSpacer: (prev, update) => spacer(update.view, prev, update),
|
||||
domEventHandlers: {
|
||||
mousedown: (view, block, event) =>
|
||||
view.state.facet(iconAreaSource).some((s) => s.mousedown?.(view, block, event as MouseEvent) ?? false),
|
||||
@@ -67,10 +146,14 @@ const areaTheme = EditorView.baseTheme({
|
||||
gap: "2px",
|
||||
},
|
||||
// Room around the icons, not the element: an area without icons takes no width.
|
||||
".cm-openidea-iconArea .cm-gutterElement > *": { margin: "0 1px" },
|
||||
".cm-openidea-iconArea .cm-gutterElement > :first-child": { marginLeft: "5px" },
|
||||
".cm-openidea-iconArea .cm-gutterElement > *, .cm-openidea-iconAreaSpacer > *": { margin: "0 1px" },
|
||||
".cm-openidea-iconArea .cm-gutterElement > :first-child, .cm-openidea-iconAreaSpacer > :first-child": {
|
||||
marginLeft: "5px",
|
||||
},
|
||||
// The spacer's icons are laid out as the line's own.
|
||||
".cm-openidea-iconAreaSpacer": { display: "contents" },
|
||||
".cm-openidea-iconSpacer": { display: "inline-block", width: "14px" },
|
||||
});
|
||||
|
||||
/** Installed in every editor; empty (no width) while no source has markers or reserves room. */
|
||||
export const iconAreaExtension: Extension = [areaGutter, areaTheme];
|
||||
export const iconAreaExtension: Extension = [areaWidth, areaGutter, areaTheme];
|
||||
@@ -5,6 +5,7 @@
|
||||
*/
|
||||
import { writeClipboardText } from "@/platform/clipboard";
|
||||
import { pasteEditorClipboard } from "./cm/clipboard";
|
||||
import { saveOnBlur } from "./saveOnBlur";
|
||||
import type { ReactNode } from "react";
|
||||
import { EditorSelection } from "@codemirror/state";
|
||||
import { create } from "zustand";
|
||||
@@ -808,19 +809,7 @@ export class EditorController implements SlotHost {
|
||||
setContext("editorTextFocus", false);
|
||||
if (!this.autoSave()) return;
|
||||
const save = () => void slot.model.save("auto").catch(() => {});
|
||||
if (typeof document === "undefined") return save();
|
||||
// A popup (intentions, completion, …) belongs to the editor: saving under it would change
|
||||
// the text (save cleanup) its items were computed for. Save once focus leaves it elsewhere.
|
||||
setTimeout(() => {
|
||||
if (slot.view?.hasFocus) return;
|
||||
if (!inPopup(document.activeElement)) return save();
|
||||
const onFocusIn = (e: FocusEvent) => {
|
||||
if (inPopup(e.target)) return;
|
||||
document.removeEventListener("focusin", onFocusIn);
|
||||
if (!slot.view?.hasFocus) save();
|
||||
};
|
||||
document.addEventListener("focusin", onFocusIn);
|
||||
});
|
||||
saveOnBlur(() => !!slot.view?.hasFocus, save);
|
||||
}
|
||||
|
||||
onSelection(slot: EditorSlot, navigatedFrom?: { line: number; col: number }) {
|
||||
@@ -949,6 +938,7 @@ export class EditorController implements SlotHost {
|
||||
{ kind: "action", action: "refactor.extractVariable" },
|
||||
{ kind: "action", action: "refactor.extractConstant" },
|
||||
{ kind: "action", action: "refactor.extractMethod" },
|
||||
{ kind: "action", action: "refactor.extractInterface" },
|
||||
{ kind: "action", action: "refactor.inline" },
|
||||
{ kind: "action", action: "refactor.pullMembersUp" },
|
||||
{ kind: "action", action: "refactor.pushMembersDown" },
|
||||
@@ -2348,7 +2338,3 @@ let controller: EditorController | null = null;
|
||||
export function editorController(): EditorController {
|
||||
return (controller ??= new EditorController());
|
||||
}
|
||||
|
||||
function inPopup(target: EventTarget | null): boolean {
|
||||
return target instanceof Element && !!target.closest("[data-popup]");
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { history, undo } from "@codemirror/commands";
|
||||
import { editorsFor } from "@/editor/api";
|
||||
import type { Settings } from "@/bindings";
|
||||
import { createMemoryBackend } from "../backend";
|
||||
import { _resetLanguages } from "../cm/languages";
|
||||
import { attachDocument } from "./attachment";
|
||||
@@ -20,11 +22,13 @@ async function settle() {
|
||||
for (let i = 0; i < 10; i++) await new Promise((r) => setTimeout(r, 0));
|
||||
}
|
||||
|
||||
function setup(files: Record<string, string>) {
|
||||
function setup(files: Record<string, string>, settings: Settings = {}) {
|
||||
_resetLanguages();
|
||||
const backend = createMemoryBackend(files);
|
||||
const scheduled: Array<() => void> = [];
|
||||
const manager = new DocumentManager(backend, { settings: () => ({}), notify: vi.fn() }, (fn) => scheduled.push(fn));
|
||||
const manager = new DocumentManager(backend, { settings: () => settings, notify: vi.fn() }, (fn) =>
|
||||
scheduled.push(fn),
|
||||
);
|
||||
manager.start();
|
||||
const frame = async () => {
|
||||
scheduled.splice(0).forEach((f) => f());
|
||||
@@ -36,6 +40,140 @@ function setup(files: Record<string, string>) {
|
||||
afterEach(() => useDocMeta.setState({}, true));
|
||||
|
||||
describe("attached document views (editable diff side)", () => {
|
||||
it.each([
|
||||
{ autoSave: true, tabOpen: false, ensureFinalNewline: false },
|
||||
{ autoSave: false, tabOpen: false, ensureFinalNewline: false },
|
||||
{ autoSave: true, tabOpen: true, ensureFinalNewline: false },
|
||||
{ autoSave: true, tabOpen: true, ensureFinalNewline: true },
|
||||
])(
|
||||
"saves reverted diff edits on blur respecting $autoSave / $tabOpen / $ensureFinalNewline",
|
||||
async ({ autoSave, tabOpen, ensureFinalNewline }) => {
|
||||
const { backend, manager, frame } = setup(
|
||||
{ "/p/a.txt": "original\n" },
|
||||
{ files: { autoSave, ensureFinalNewline } },
|
||||
);
|
||||
const att = await attachDocument(manager, "/p/a.txt");
|
||||
const tab = tabOpen ? new EditorSlot(manager.get("/p/a.txt")!, "t1", host) : null;
|
||||
const parent = document.createElement("div");
|
||||
const elsewhere = document.createElement("button");
|
||||
document.body.append(parent, elsewhere);
|
||||
const view = new EditorView({ parent, doc: att.text(), extensions: [att.extension] });
|
||||
try {
|
||||
view.focus();
|
||||
view.dispatch({ changes: { from: 8, to: 9 }, userEvent: "delete.backward" });
|
||||
elsewhere.focus();
|
||||
await frame();
|
||||
expect(backend.docs.get(att.doc)?.saved).toBe(autoSave && !ensureFinalNewline ? "original" : "original\n");
|
||||
expect(att.dirty()).toBe(!autoSave);
|
||||
if (!autoSave) {
|
||||
await att.save();
|
||||
expect(backend.docs.get(att.doc)?.saved).toBe("original");
|
||||
}
|
||||
} finally {
|
||||
view.destroy();
|
||||
att.release();
|
||||
tab?.dispose();
|
||||
manager.stop();
|
||||
parent.remove();
|
||||
elsewhere.remove();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("cancels popup-delayed autosave when an attached view is destroyed", async () => {
|
||||
const { backend, manager, frame } = setup({ "/p/a.txt": "original\n" });
|
||||
const att = await attachDocument(manager, "/p/a.txt");
|
||||
const parent = document.createElement("div");
|
||||
const popup = document.createElement("button");
|
||||
popup.setAttribute("data-popup", "");
|
||||
const elsewhere = document.createElement("button");
|
||||
document.body.append(parent, popup, elsewhere);
|
||||
const view = new EditorView({ parent, doc: att.text(), extensions: [att.extension] });
|
||||
try {
|
||||
view.focus();
|
||||
view.dispatch({ changes: { from: 8, to: 9 } });
|
||||
popup.focus();
|
||||
await frame();
|
||||
view.destroy();
|
||||
elsewhere.focus();
|
||||
await frame();
|
||||
expect(backend.docs.get(att.doc)?.saved).toBe("original\n");
|
||||
} finally {
|
||||
view.destroy();
|
||||
att.release();
|
||||
manager.stop();
|
||||
parent.remove();
|
||||
popup.remove();
|
||||
elsewhere.remove();
|
||||
}
|
||||
});
|
||||
|
||||
it("waits until focus leaves an editor popup before autosaving a diff", async () => {
|
||||
const { backend, manager, frame } = setup({ "/p/a.txt": "original\n" });
|
||||
const att = await attachDocument(manager, "/p/a.txt");
|
||||
const parent = document.createElement("div");
|
||||
const popup = document.createElement("div");
|
||||
popup.setAttribute("data-popup", "");
|
||||
const item = document.createElement("button");
|
||||
popup.append(item);
|
||||
const elsewhere = document.createElement("button");
|
||||
document.body.append(parent, popup, elsewhere);
|
||||
const view = new EditorView({ parent, doc: att.text(), extensions: [att.extension] });
|
||||
try {
|
||||
view.focus();
|
||||
view.dispatch({ changes: { from: 8, to: 9 } });
|
||||
item.focus();
|
||||
await frame();
|
||||
expect(backend.docs.get(att.doc)?.saved).toBe("original\n");
|
||||
view.focus();
|
||||
await frame();
|
||||
expect(att.dirty()).toBe(true);
|
||||
item.focus();
|
||||
await frame();
|
||||
elsewhere.focus();
|
||||
await frame();
|
||||
expect(backend.docs.get(att.doc)?.saved).toBe("original");
|
||||
expect(att.dirty()).toBe(false);
|
||||
} finally {
|
||||
view.destroy();
|
||||
att.release();
|
||||
manager.stop();
|
||||
parent.remove();
|
||||
popup.remove();
|
||||
elsewhere.remove();
|
||||
}
|
||||
});
|
||||
|
||||
it("does not save another view's edits when leaving a read-only preview", async () => {
|
||||
const { backend, manager, frame } = setup({ "/p/a.txt": "original\n" });
|
||||
const model = await manager.acquire("/p/a.txt");
|
||||
const tab = new EditorSlot(model, "t1", host);
|
||||
const att = await attachDocument(manager, "/p/a.txt");
|
||||
const parent = document.createElement("div");
|
||||
const elsewhere = document.createElement("button");
|
||||
document.body.append(parent, elsewhere);
|
||||
const view = new EditorView({
|
||||
parent,
|
||||
doc: att.text(),
|
||||
extensions: [att.extension, EditorState.readOnly.of(true)],
|
||||
});
|
||||
try {
|
||||
tab.dispatchLocal({ changes: { from: 8, to: 9 } });
|
||||
view.focus();
|
||||
elsewhere.focus();
|
||||
await frame();
|
||||
expect(backend.docs.get(att.doc)?.saved).toBe("original\n");
|
||||
expect(att.dirty()).toBe(true);
|
||||
} finally {
|
||||
view.destroy();
|
||||
att.release();
|
||||
tab.dispose();
|
||||
manager.stop();
|
||||
parent.remove();
|
||||
elsewhere.remove();
|
||||
}
|
||||
});
|
||||
|
||||
it("can save a confirmed merge result without trimming or adding a final newline", async () => {
|
||||
const { backend, manager } = setup({ "/p/merge.txt": "old\n" });
|
||||
const att = await attachDocument(manager, "/p/merge.txt");
|
||||
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
type TextEditorHandle,
|
||||
} from "@/editor/api";
|
||||
import type { DocAttachmentTarget, DocumentManager } from "./document";
|
||||
import { saveOnBlur } from "../saveOnBlur";
|
||||
|
||||
class AttachedView implements DocAttachmentTarget {
|
||||
view: EditorView | null = null;
|
||||
@@ -62,6 +63,7 @@ export async function attachDocument(
|
||||
}
|
||||
model.attach(target);
|
||||
let released = false;
|
||||
let cancelBlurSave: (() => void) | undefined;
|
||||
let detachHistory: (() => void) | null = null;
|
||||
const historyTarget = {
|
||||
path,
|
||||
@@ -93,6 +95,7 @@ export async function attachDocument(
|
||||
return {
|
||||
destroy() {
|
||||
destroyed = true;
|
||||
cancelBlurSave?.();
|
||||
if (!options.sharedHistory) {
|
||||
detachHistory?.();
|
||||
detachHistory = null;
|
||||
@@ -143,6 +146,19 @@ export async function attachDocument(
|
||||
}
|
||||
},
|
||||
extension: [
|
||||
EditorView.domEventHandlers({
|
||||
blur: (_event, view) => {
|
||||
cancelBlurSave?.();
|
||||
if (view.state.readOnly || !view.state.facet(EditorView.editable)) return;
|
||||
cancelBlurSave = saveOnBlur(
|
||||
() => view.hasFocus,
|
||||
() => {
|
||||
if (released || model.closed || manager.settings()?.files?.autoSave === false) return;
|
||||
void model.save("auto").catch((e) => console.warn(`autosave of ${path} failed`, e));
|
||||
},
|
||||
);
|
||||
},
|
||||
}),
|
||||
options.sharedHistory ? target.history.of(history()) : [],
|
||||
options.sharedHistory
|
||||
? EditorView.domEventHandlers({
|
||||
@@ -187,6 +203,7 @@ export async function attachDocument(
|
||||
release: () => {
|
||||
if (released) return;
|
||||
released = true;
|
||||
cancelBlurSave?.();
|
||||
detachHistory?.();
|
||||
detachHistory = null;
|
||||
target.view = null;
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
/** Popups belong to the editor; defer save cleanup until focus leaves them too. */
|
||||
export function saveOnBlur(hasFocus: () => boolean, save: () => void): () => void {
|
||||
if (typeof document === "undefined") {
|
||||
save();
|
||||
return () => {};
|
||||
}
|
||||
const inPopup = (target: EventTarget | null) => target instanceof Element && !!target.closest("[data-popup]");
|
||||
const onFocusIn = (event: FocusEvent) => {
|
||||
if (inPopup(event.target)) return;
|
||||
document.removeEventListener("focusin", onFocusIn);
|
||||
if (!hasFocus()) save();
|
||||
};
|
||||
const timer = setTimeout(() => {
|
||||
if (hasFocus()) return;
|
||||
if (inPopup(document.activeElement)) document.addEventListener("focusin", onFocusIn);
|
||||
else save();
|
||||
});
|
||||
return () => {
|
||||
clearTimeout(timer);
|
||||
document.removeEventListener("focusin", onFocusIn);
|
||||
};
|
||||
}
|
||||
@@ -230,6 +230,7 @@ function PaneView({ paneId }: { paneId: string }) {
|
||||
color: colors[i] || undefined,
|
||||
tint:
|
||||
tints[i] || (fileColors && t.input.kind === "file" && t.input.path ? fileColors(t.input.path) : undefined),
|
||||
tintStrength: tints[i] ? undefined : "var(--file-tint-strength)",
|
||||
tooltip: virtualTooltip(t.input) ?? (showFullPathOnHover ? (t.input.path ?? name) : undefined),
|
||||
trailing:
|
||||
kindMark || pin ? (
|
||||
|
||||
@@ -320,6 +320,9 @@ export function registerLspActions(): () => void {
|
||||
editorAction("refactor.extractParameter", "Introduce Parameter…", "Refactor", (v) =>
|
||||
runRefactoring(v, "extractParameter"),
|
||||
),
|
||||
editorAction("refactor.extractInterface", "Extract Interface…", "Refactor", (v) =>
|
||||
runRefactoring(v, "extractInterface"),
|
||||
),
|
||||
editorAction("refactor.move", "Move…", "Refactor", (v) => runRefactoring(v, "move")),
|
||||
editorAction("refactor.changeSignature", "Change Signature…", "Refactor", (v) =>
|
||||
runRefactoring(v, "changeSignature"),
|
||||
|
||||
@@ -44,6 +44,7 @@ import { outsideProjectBanner } from "./outsideProject";
|
||||
import { implementationGutter, registerNavigationActions } from "@/editor/navigation";
|
||||
import {
|
||||
ChangeSignatureDialog,
|
||||
ExtractInterfaceDialog,
|
||||
HierarchyDialog,
|
||||
JAVA_REFACTORING_COMMAND,
|
||||
runJavaRefactoringCommand,
|
||||
@@ -122,6 +123,7 @@ export function activate(): () => void {
|
||||
registerOverlay({ id: "editor-lsp.popups", component: LspPopups }),
|
||||
registerOverlay({ id: "editor-lsp.hierarchyDialog", component: HierarchyDialog }),
|
||||
registerOverlay({ id: "editor-lsp.changeSignatureDialog", component: ChangeSignatureDialog }),
|
||||
registerOverlay({ id: "editor-lsp.extractInterfaceDialog", component: ExtractInterfaceDialog }),
|
||||
registerClientCommand(JAVA_REFACTORING_COMMAND, runJavaRefactoringCommand),
|
||||
registerEditorBanner(outsideProjectBanner),
|
||||
registerStatusItem({ id: "editor-lsp.usagesStatus", align: "left", priority: 10, component: UsagesStatus }),
|
||||
|
||||
@@ -195,27 +195,25 @@ export async function locationItems(locs: readonly DeclarationTarget[]): Promise
|
||||
const root = useProject.getState().project?.root ?? "";
|
||||
const names = locs.map((l) => targetLabel(files.get(l.path)?.[l.range.start.line] ?? "", l.range.start.col));
|
||||
const indexed = await indexContainers(locs, names);
|
||||
return locs.map((l, i) => {
|
||||
const rows = locs.map((l, i) => {
|
||||
const where = chooserWhere(root, l.path, l.range.start.line + 1);
|
||||
// Index symbols carry their container; server targets take the index's answer or the enclosing type.
|
||||
if (l.kind && l.name)
|
||||
return {
|
||||
id: `${i}`,
|
||||
label: l.name,
|
||||
detail: [l.container, where].filter(Boolean).join(" · "),
|
||||
symbol: l.kind,
|
||||
location: { path: l.path, line: l.range.start.line },
|
||||
run: () => navigateTo(l),
|
||||
};
|
||||
return {
|
||||
id: `${i}`,
|
||||
label: l.name ?? names[i] ?? basename(l.path),
|
||||
detail: [indexed.get(i) ?? enclosingType(files.get(l.path), l), where].filter(Boolean).join(" · "),
|
||||
icon: fileIconName(basename(l.path), l.path),
|
||||
location: { path: l.path, line: l.range.start.line },
|
||||
run: () => navigateTo(l),
|
||||
};
|
||||
const indexSymbol = !!(l.kind && l.name);
|
||||
const label = indexSymbol ? l.name! : (l.name ?? names[i] ?? basename(l.path));
|
||||
const container = indexSymbol ? l.container : (indexed.get(i) ?? enclosingType(files.get(l.path), l));
|
||||
return { l, where, label, container: container || null, indexSymbol };
|
||||
});
|
||||
// Targets that all share one name (the implementations of a method) are told apart, and
|
||||
// speed-searched, by their containers, which become the rows' text.
|
||||
const byContainer = rows.length > 1 && rows.every((r) => r.container && r.label === rows[0]!.label);
|
||||
return rows.map(({ l, where, label, container, indexSymbol }, i) => ({
|
||||
id: `${i}`,
|
||||
label: byContainer ? container! : label,
|
||||
detail: (byContainer ? [where] : [container, where]).filter(Boolean).join(" · "),
|
||||
...(indexSymbol ? { symbol: l.kind! } : { icon: fileIconName(basename(l.path), l.path) }),
|
||||
location: { path: l.path, line: l.range.start.line },
|
||||
run: () => navigateTo(l),
|
||||
}));
|
||||
}
|
||||
|
||||
/** "Choose Implementation of foo (3 found)". */
|
||||
|
||||
@@ -187,6 +187,24 @@ describe("locationItems", () => {
|
||||
expect(item.detail).toBe("config · src/mod.py:1");
|
||||
});
|
||||
|
||||
it("names same-named targets (a method's implementations) by their containers", async () => {
|
||||
const lines = (cls: string) => ["", `class ${cls}(Base):`, "", " def refresh(self) -> None:"];
|
||||
readManyFileLines.mockResolvedValue(
|
||||
new Map([
|
||||
["/p/src/a.py", lines("Cached")],
|
||||
["/p/src/b.py", lines("Remote")],
|
||||
]),
|
||||
);
|
||||
project("/p");
|
||||
const items = await locationItems([target("/p/src/a.py", "refresh", 3), target("/p/src/b.py", "refresh", 3)]);
|
||||
expect(items.map((i) => [i.label, i.detail])).toEqual([
|
||||
["Cached", "src/a.py:4"],
|
||||
["Remote", "src/b.py:4"],
|
||||
]);
|
||||
// A single target, or targets with different names, keep their own names.
|
||||
expect((await locationItems([target("/p/src/a.py", "refresh", 3)]))[0]!.label).toBe("refresh");
|
||||
});
|
||||
|
||||
it("does not query the index for index symbols, which carry their container", async () => {
|
||||
readManyFileLines.mockResolvedValue(new Map());
|
||||
project("/p");
|
||||
|
||||
@@ -585,9 +585,10 @@ describe("navigation wiring", () => {
|
||||
if (popup?.kind !== "list") return;
|
||||
expect(popup.title).toBe("Choose Declaration of run (2 found, based on syntax)");
|
||||
expect(popup.pin?.label).toBe("Open in Find Tool Window");
|
||||
expect(popup.items.map((i) => [i.label, i.symbol, i.detail?.split(" · ")[0]])).toEqual([
|
||||
["run", "method", "A"],
|
||||
["run", "method", "B"],
|
||||
// Same-named candidates read by their containers.
|
||||
expect(popup.items.map((i) => [i.label, i.symbol, i.detail])).toEqual([
|
||||
["A", "method", "p/a.ts:4"],
|
||||
["B", "method", "p/b.ts:4"],
|
||||
]);
|
||||
expect(openFile).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -295,9 +295,10 @@ export const lspTheme = EditorView.theme({
|
||||
padding: "6px 10px",
|
||||
borderRadius: "var(--radius-popup)",
|
||||
boxShadow: "var(--shadow-popup)",
|
||||
maxWidth: "480px",
|
||||
whiteSpace: "pre-wrap",
|
||||
},
|
||||
// The hint is the tooltip element itself: beat the editor theme's `.cm-tooltip` width.
|
||||
".cm-tooltip.cm-lsp-hint": { maxWidth: "min(480px, 100%)" },
|
||||
".cm-lsp-hint-error": {
|
||||
backgroundColor: "var(--bg-feedback-error, color-mix(in srgb, var(--danger) 8%, var(--bg-popup)))",
|
||||
borderColor: "color-mix(in srgb, var(--danger) 35%, var(--border-popup))",
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
*/
|
||||
import { RangeSet, StateEffect, StateField, type Extension, type Text } from "@codemirror/state";
|
||||
import { EditorView, GutterMarker, ViewPlugin, type ViewUpdate } from "@codemirror/view";
|
||||
import { iconAreaSource } from "@/editor/core/cm/iconArea";
|
||||
import { iconAreaSource, mapLineStart } from "@/editor/core/cm/iconArea";
|
||||
import { shownAgain, type EditorDocContext } from "@/editor/api";
|
||||
import { docOf, debounce, isUnavailable, lspRequest } from "@/editor/lsp/lsp";
|
||||
import { featureBackoff, onServerSettled } from "@/editor/lsp/availability";
|
||||
@@ -29,6 +29,7 @@ import {
|
||||
nextRequestId,
|
||||
onIdeEvent,
|
||||
type ClassInheritance,
|
||||
type DocId,
|
||||
type HierarchyItem,
|
||||
type Location,
|
||||
type OutlineItem,
|
||||
@@ -315,7 +316,7 @@ export async function fillMarkers(
|
||||
const c = up[i]!;
|
||||
const self = classOf(c);
|
||||
if (!self) continue;
|
||||
const found = resolver ? await superMethodsFrom(resolver, self.name, c.symbol, deps) : [];
|
||||
const found = resolver ? await superMethodsFrom(resolver, self, c.symbol, deps) : [];
|
||||
if (!found.length) continue;
|
||||
const known = supers[i]!;
|
||||
// Same merge rule as ↓: add the graph's super methods to what the server answered.
|
||||
@@ -324,6 +325,8 @@ export async function fillMarkers(
|
||||
entry(c).supers = {
|
||||
kind: "overriding",
|
||||
line: c.line,
|
||||
col: c.col,
|
||||
method: c.method,
|
||||
name: c.name,
|
||||
targets: [...known.map((s) => s.location), ...extra],
|
||||
tooltip: tx`Overrides method in ${owners.join(", ")}`,
|
||||
@@ -366,41 +369,37 @@ function mergeLocations(first: readonly Location[], more: readonly Location[]):
|
||||
return [...first, ...more.filter((l) => !first.some((f) => sameDeclarationLine(f, l)))];
|
||||
}
|
||||
|
||||
/** Identifies one class declaration in the inheritance graph. */
|
||||
/**
|
||||
* Super methods of `method` declared by a class in `byName`, walking the inheritance
|
||||
* graph's bases up to a few levels. Empty when no base declares the method.
|
||||
* Super methods of `method` declared by a base of the class declaration `start`, walking the
|
||||
* inheritance graph's concrete declarations up to a few levels: a base resolves from the file
|
||||
* that names it, so an unrelated class of the same name never joins the walk. Empty when no
|
||||
* base declares the method.
|
||||
*/
|
||||
async function superMethodsFrom(
|
||||
resolver: InheritanceIndex,
|
||||
start: string,
|
||||
start: ClassInheritance,
|
||||
method: string,
|
||||
deps: MarkerDeps,
|
||||
depth = 3,
|
||||
): Promise<{ location: Location; owner: string }[]> {
|
||||
const bare = method.replace(/\s*[(<].*$/, "");
|
||||
const seen = new Set<string>([start]);
|
||||
const key = (c: ClassInheritance) => `${c.path}:${c.line}:${c.col}`;
|
||||
const seen = new Set<string>([key(start)]);
|
||||
let level = [start];
|
||||
for (let d = 0; d < depth && level.length; d++) {
|
||||
const next: string[] = [];
|
||||
const next: ClassInheritance[] = [];
|
||||
const found: { location: Location; owner: string }[] = [];
|
||||
for (const name of level) {
|
||||
for (const cls of resolver.byName.get(name) ?? []) {
|
||||
for (const base of cls.bases) {
|
||||
if (!seen.add(base)) continue;
|
||||
// Same rule as the graph: a base the imports name, else a unique one.
|
||||
const declarations = await resolver.resolve(base, cls.path);
|
||||
let answered = false;
|
||||
for (const baseCls of declarations) {
|
||||
const outline = await deps.supers.outline(baseCls.path).catch(() => [] as OutlineItem[]);
|
||||
const m = methodInOutline(outline, baseCls, bare);
|
||||
if (m) {
|
||||
found.push({ location: { path: baseCls.path, range: m.selection_range }, owner: base });
|
||||
answered = true;
|
||||
}
|
||||
}
|
||||
// Not found in a base that declares nothing: keep walking its own bases.
|
||||
if (!answered) next.push(base);
|
||||
for (const cls of level) {
|
||||
for (const base of cls.bases) {
|
||||
// Same rule as the graph: a base the imports name, else a unique one.
|
||||
for (const baseCls of await resolver.resolve(base, cls.path)) {
|
||||
if (seen.has(key(baseCls))) continue;
|
||||
seen.add(key(baseCls));
|
||||
const outline = await deps.supers.outline(baseCls.path).catch(() => [] as OutlineItem[]);
|
||||
const m = methodInOutline(outline, baseCls, bare);
|
||||
if (m) found.push({ location: { path: baseCls.path, range: m.selection_range }, owner: base });
|
||||
// Not declared there: keep walking that class's own bases.
|
||||
else next.push(baseCls);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -510,18 +509,46 @@ export function cachedMarkers(
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* A dependency's implementation (Java) starts at `0:0` of the class file: the server resolves
|
||||
* the method's declaration when the marker is opened, not for every marker in the gutter.
|
||||
*/
|
||||
async function markerTargets(marker: LineMarker, doc: DocId | null): Promise<Location[]> {
|
||||
if (
|
||||
doc === null ||
|
||||
doc < 0 ||
|
||||
!marker.method ||
|
||||
(marker.kind !== "implemented" && marker.kind !== "overridden") ||
|
||||
!marker.targets.some((t) => t.range.start.line === 0 && t.uri?.startsWith("jdt:"))
|
||||
)
|
||||
return marker.targets;
|
||||
const request = nextRequestId();
|
||||
try {
|
||||
return await lspRequest(() =>
|
||||
commands.lspImplementationLocations(request, doc, { line: marker.line, col: marker.col }, marker.targets),
|
||||
);
|
||||
} catch {
|
||||
return marker.targets;
|
||||
}
|
||||
}
|
||||
|
||||
/** Opens the single target, or the chooser over several. */
|
||||
export async function openMarkerTargets(marker: LineMarker, anchor: { x: number; y: number }) {
|
||||
if (marker.targets.length === 1) {
|
||||
await navigateTo(marker.targets[0]!);
|
||||
export async function openMarkerTargets(
|
||||
marker: LineMarker,
|
||||
anchor: { x: number; y: number },
|
||||
doc: DocId | null = null,
|
||||
) {
|
||||
const targets = await markerTargets(marker, doc);
|
||||
if (targets.length === 1) {
|
||||
await navigateTo(targets[0]!);
|
||||
return;
|
||||
}
|
||||
openPopup({
|
||||
kind: "list",
|
||||
anchor,
|
||||
title: marker.chooserTitle,
|
||||
items: await locationItems(marker.targets),
|
||||
pin: pinToFind(marker.name, marker.targets),
|
||||
items: await locationItems(targets),
|
||||
pin: pinToFind(marker.name, targets),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -541,7 +568,7 @@ const markersField = StateField.define<PlacedMarker[]>({
|
||||
update(value, tr) {
|
||||
for (const e of tr.effects) if (e.is(setMarkers)) return e.value;
|
||||
if (!tr.docChanged || !value.length) return value;
|
||||
return value.map((m) => ({ ...m, pos: tr.state.doc.lineAt(tr.changes.mapPos(m.pos, -1)).from }));
|
||||
return value.map((m) => ({ ...m, pos: mapLineStart(tr, m.pos) }));
|
||||
},
|
||||
});
|
||||
|
||||
@@ -785,7 +812,7 @@ export function implementationGutter(ctx: EditorDocContext): Extension {
|
||||
if (!marker) return false;
|
||||
e.preventDefault();
|
||||
const rect = (target.closest(`.${styles.marker}`) ?? target).getBoundingClientRect();
|
||||
void openMarkerTargets(marker, { x: rect.left, y: rect.bottom + 2 });
|
||||
void openMarkerTargets(marker, { x: rect.left, y: rect.bottom + 2 }, ctx.doc);
|
||||
return true;
|
||||
},
|
||||
}),
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
IpcError,
|
||||
commands,
|
||||
type ClassInheritance,
|
||||
type HierarchyItem,
|
||||
type Location,
|
||||
@@ -498,13 +499,48 @@ describe("clicking a marker", () => {
|
||||
it("navigates to a single target", async () => {
|
||||
const target = loc("/p/Circle.java", 0, 13);
|
||||
await openMarkerTargets(
|
||||
{ kind: "implemented", line: 0, name: "Shape", targets: [target], tooltip: "", chooserTitle: "" },
|
||||
{
|
||||
kind: "implemented",
|
||||
line: 0,
|
||||
col: 17,
|
||||
method: false,
|
||||
name: "Shape",
|
||||
targets: [target],
|
||||
tooltip: "",
|
||||
chooserTitle: "",
|
||||
},
|
||||
{ x: 1, y: 2 },
|
||||
);
|
||||
expect(nav.navigateTo).toHaveBeenCalledWith(target);
|
||||
expect(nav.openPopup).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("resolves a dependency's implementation at its method", async () => {
|
||||
vi.stubGlobal("__TAURI_INTERNALS__", {});
|
||||
const zero = loc("jdt://contents/lib.jar/zoo/Impl.java?=p/lib.jar", 0, 0);
|
||||
zero.uri = zero.path;
|
||||
const method = { ...zero, range: { start: { line: 5, col: 4 }, end: { line: 7, col: 5 } } };
|
||||
const spy = vi.spyOn(commands, "lspImplementationLocations").mockResolvedValue({ status: "ok", data: [method] });
|
||||
await openMarkerTargets(
|
||||
{
|
||||
kind: "implemented",
|
||||
line: 1,
|
||||
col: 9,
|
||||
method: true,
|
||||
name: "save",
|
||||
targets: [zero],
|
||||
tooltip: "",
|
||||
chooserTitle: "",
|
||||
},
|
||||
{ x: 1, y: 2 },
|
||||
7,
|
||||
);
|
||||
expect(spy).toHaveBeenCalledWith(expect.any(Number), 7, { line: 1, col: 9 }, [zero]);
|
||||
expect(nav.navigateTo).toHaveBeenCalledWith(method);
|
||||
spy.mockRestore();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it("opens the chooser over several targets", async () => {
|
||||
const targets = [loc("/p/Circle.java", 0, 13), loc("/p/Square.java", 0, 13)];
|
||||
expect(candidateKey(candidate())).toBe("0:17:Shape");
|
||||
@@ -512,6 +548,8 @@ describe("clicking a marker", () => {
|
||||
{
|
||||
kind: "implemented",
|
||||
line: 0,
|
||||
col: 17,
|
||||
method: false,
|
||||
name: "Shape",
|
||||
targets,
|
||||
tooltip: "",
|
||||
@@ -765,6 +803,26 @@ describe("python inheritance fallback", () => {
|
||||
expect(cachedMarkers(candidates, ALL, cache).map((m) => [m.line, m.kind])).toEqual([[0, "overridden"]]);
|
||||
});
|
||||
|
||||
it("walks up from the class itself, not every class of its name", async () => {
|
||||
// a.py: `class BaseA` with `foo`, `class Child(BaseA)` with `foo`; b.py the same with BaseB.
|
||||
const outline = (base: string) => [
|
||||
item(base, "class", 0, 2, [item("foo", "method", 1, 1)], 6),
|
||||
item("Child", "class", 3, 5, [item("foo", "method", 4, 4)], 6),
|
||||
];
|
||||
const graph: ClassInheritance[] = [
|
||||
{ path: "/p/a.py", line: 0, col: 6, name: "BaseA", bases: [] },
|
||||
{ path: "/p/a.py", line: 3, col: 6, name: "Child", bases: ["BaseA"] },
|
||||
{ path: "/p/b.py", line: 0, col: 6, name: "BaseB", bases: [] },
|
||||
{ path: "/p/b.py", line: 3, col: 6, name: "Child", bases: ["BaseB"] },
|
||||
];
|
||||
const { deps } = pythonServer(graph, { "/p/a.py": outline("BaseA"), "/p/b.py": outline("BaseB") });
|
||||
const candidates = markerCandidates(outline("BaseA"), () => "");
|
||||
const cache = emptyCache();
|
||||
await fillMarkers("/p/a.py", candidates, ALL, deps(), cache);
|
||||
const up = cachedMarkers(candidates, ALL, cache).find((m) => m.line === 4 && m.kind === "overriding");
|
||||
expect(up?.targets.map((t) => [t.path, t.range.start.line])).toEqual([["/p/a.py", 1]]);
|
||||
});
|
||||
|
||||
it("resolves an ambiguous base name through the subclass file's imports", async () => {
|
||||
// Two modules declare `Config`; `from pkg.b import Config` picks one of them, so
|
||||
// only b.py's Config is marked as subclassed.
|
||||
|
||||
@@ -48,6 +48,10 @@ export interface MarkerCandidate {
|
||||
export interface LineMarker {
|
||||
kind: MarkerKind;
|
||||
line: number;
|
||||
/** UTF-16 column of the declaration's identifier, the position implementation requests use. */
|
||||
col: number;
|
||||
/** A method (not a type): its implementations are methods, not classes. */
|
||||
method: boolean;
|
||||
/** Name of the declaration the marker is on. */
|
||||
name: string;
|
||||
targets: Location[];
|
||||
@@ -249,7 +253,16 @@ export function inheritorsMarker(
|
||||
? tx`Choose Implementation of ${c.name} (${n} found)`
|
||||
: tx`Choose Overriding Method of ${c.name} (${n} found)`;
|
||||
}
|
||||
return { kind, line: c.line, name: c.name, targets: [...targets], tooltip, chooserTitle };
|
||||
return {
|
||||
kind,
|
||||
line: c.line,
|
||||
col: c.col,
|
||||
method: c.method,
|
||||
name: c.name,
|
||||
targets: [...targets],
|
||||
tooltip,
|
||||
chooserTitle,
|
||||
};
|
||||
}
|
||||
|
||||
/** ↑ marker of a Go type or method from the interfaces (methods) it satisfies; null without any. */
|
||||
@@ -264,6 +277,8 @@ export function implementsMarker(
|
||||
return {
|
||||
kind: "implementing",
|
||||
line: c.line,
|
||||
col: c.col,
|
||||
method: c.method,
|
||||
name: c.name,
|
||||
targets: [...targets],
|
||||
tooltip: c.method ? tx`Implements method in ${names}` : tx`Implements ${names}`,
|
||||
@@ -293,6 +308,8 @@ export function supersMarker(
|
||||
return {
|
||||
kind: implementing ? "implementing" : "overriding",
|
||||
line: c.line,
|
||||
col: c.col,
|
||||
method: true,
|
||||
name: c.name,
|
||||
targets: supers.map((s) => s.location),
|
||||
tooltip: implementing ? tx`Implements method in ${owners}` : tx`Overrides method in ${owners}`,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/** IDEA's Change Signature dialog for Java methods (`signature.ts`). */
|
||||
import { useState } from "react";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import type { MethodSignature } from "@/bindings";
|
||||
import { Checkbox, Dialog, IconButton, Input, Select, Spinner, T, Toolbar } from "@/ui";
|
||||
import { useTx } from "@/platform/i18n";
|
||||
@@ -46,7 +46,11 @@ function ChangeSignatureDialogInner({ request }: { request: SignatureRequest })
|
||||
const ready = !busy && !problem && signatureChanged(info, signature);
|
||||
const current = Math.min(selected, rows.length - 1);
|
||||
|
||||
// Closing the dialog cancels a refactoring still being checked: it applies nothing.
|
||||
const running = useRef<AbortController | null>(null);
|
||||
useEffect(() => () => running.current?.abort(), []);
|
||||
const close = () => {
|
||||
running.current?.abort();
|
||||
useSignatureDialog.setState({ request: null });
|
||||
request.view.focus();
|
||||
};
|
||||
@@ -72,9 +76,10 @@ function ChangeSignatureDialogInner({ request }: { request: SignatureRequest })
|
||||
};
|
||||
const submit = async (preview: boolean) => {
|
||||
if (!ready) return;
|
||||
const run = (running.current = new AbortController());
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
const outcome = await changeSignature(request, signature, delegate, preview);
|
||||
const outcome = await changeSignature(request, signature, delegate, preview, run.signal);
|
||||
if (useSignatureDialog.getState().request !== request) return;
|
||||
setBusy(false);
|
||||
if (outcome.status === "done") close();
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
.dialog [data-dialog-body] {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.body {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-3);
|
||||
padding: 14px;
|
||||
font-size: var(--fs-ui);
|
||||
color: var(--fg);
|
||||
}
|
||||
|
||||
.field {
|
||||
flex: none;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-1-5);
|
||||
}
|
||||
|
||||
.source {
|
||||
font-family: var(--font-mono);
|
||||
color: var(--fg-muted);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.table {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 4px;
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.head,
|
||||
.row {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
padding: 0 8px;
|
||||
min-height: var(--h-list-row);
|
||||
}
|
||||
|
||||
.head {
|
||||
color: var(--fg-muted);
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.rows {
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.row:hover {
|
||||
background: var(--bg-hover);
|
||||
}
|
||||
|
||||
.member {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.label {
|
||||
font-family: var(--font-mono);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.error {
|
||||
flex: none;
|
||||
color: var(--danger);
|
||||
font-size: var(--fs-small);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.busy {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
/** IDEA's Extract Interface dialog for Java classes (`extractInterface.ts`). */
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { Checkbox, Dialog, Input, Select, Spinner, T } from "@/ui";
|
||||
import { useTx } from "@/platform/i18n";
|
||||
import {
|
||||
extractInterface,
|
||||
interfaceProblem,
|
||||
memberLabel,
|
||||
useExtractInterfaceDialog,
|
||||
type InterfaceRequest,
|
||||
} from "./extractInterface";
|
||||
import styles from "./ExtractInterfaceDialog.module.css";
|
||||
|
||||
export function ExtractInterfaceDialog() {
|
||||
const request = useExtractInterfaceDialog((s) => s.request);
|
||||
if (!request) return null;
|
||||
return <ExtractInterfaceDialogInner key={request.seq} request={request} />;
|
||||
}
|
||||
|
||||
function ExtractInterfaceDialogInner({ request }: { request: InterfaceRequest }) {
|
||||
const tx = useTx();
|
||||
const { info, packages } = request;
|
||||
const [name, setName] = useState("");
|
||||
const [pkg, setPkg] = useState(() =>
|
||||
String(
|
||||
Math.max(
|
||||
0,
|
||||
packages.findIndex((p) => p.current),
|
||||
),
|
||||
),
|
||||
);
|
||||
const [checked, setChecked] = useState<ReadonlySet<string>>(new Set());
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const trimmed = name.trim();
|
||||
const problem = interfaceProblem(trimmed, info.className, checked.size);
|
||||
const target = packages[Number(pkg)];
|
||||
const ready = !busy && !problem && !!target;
|
||||
const allChecked = checked.size === info.members.length;
|
||||
|
||||
// Closing the dialog cancels a refactoring still being checked: it applies nothing.
|
||||
const running = useRef<AbortController | null>(null);
|
||||
useEffect(() => () => running.current?.abort(), []);
|
||||
const close = () => {
|
||||
running.current?.abort();
|
||||
useExtractInterfaceDialog.setState({ request: null });
|
||||
request.view.focus();
|
||||
};
|
||||
const toggle = (id: string, on: boolean) =>
|
||||
setChecked((all) => {
|
||||
const next = new Set(all);
|
||||
if (on) next.add(id);
|
||||
else next.delete(id);
|
||||
return next;
|
||||
});
|
||||
const submit = async (preview: boolean) => {
|
||||
if (!ready) return;
|
||||
const run = (running.current = new AbortController());
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
const members = info.members.map((m) => m.handleIdentifier).filter((id) => checked.has(id));
|
||||
const outcome = await extractInterface(request, trimmed, target, members, preview, run.signal);
|
||||
if (useExtractInterfaceDialog.getState().request !== request) return;
|
||||
setBusy(false);
|
||||
if (outcome.status === "done") close();
|
||||
else if (outcome.error) setError(outcome.error);
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open
|
||||
onClose={close}
|
||||
title="Extract Interface"
|
||||
className={styles.dialog}
|
||||
width={560}
|
||||
minHeight={360}
|
||||
maxHeight={600}
|
||||
resizable="both"
|
||||
buttons={[
|
||||
{ label: "Preview", role: "extra", disabled: !ready, onClick: () => void submit(true) },
|
||||
{ label: "Refactor", role: "default", disabled: !ready, onClick: () => void submit(false) },
|
||||
{ label: "Cancel", role: "cancel" },
|
||||
]}
|
||||
footerStart={
|
||||
busy ? (
|
||||
<span className={styles.busy}>
|
||||
<Spinner size={12} />
|
||||
<T>Checking for conflicts…</T>
|
||||
</span>
|
||||
) : undefined
|
||||
}
|
||||
>
|
||||
<div className={styles.body}>
|
||||
<div className={styles.field}>
|
||||
<T>Extract interface from:</T>
|
||||
<span className={styles.source}>{info.className}</span>
|
||||
</div>
|
||||
<label className={styles.field}>
|
||||
<T>Interface name:</T>
|
||||
<Input mono autoFocus value={name} onChange={(e) => setName(e.target.value)} />
|
||||
</label>
|
||||
<label className={styles.field}>
|
||||
<T>Package for new interface:</T>
|
||||
<Select
|
||||
aria-label="Package for new interface"
|
||||
value={pkg}
|
||||
options={packages.map((p, i) => ({ value: String(i), label: p.name, icon: "package" }))}
|
||||
onChange={setPkg}
|
||||
/>
|
||||
</label>
|
||||
<div className={styles.table} role="table" aria-label={tx("Members to Form Interface")}>
|
||||
<div className={styles.head} role="row">
|
||||
<Checkbox
|
||||
checked={allChecked}
|
||||
indeterminate={checked.size > 0 && !allChecked}
|
||||
onChange={(on) => setChecked(on ? new Set(info.members.map((m) => m.handleIdentifier)) : new Set())}
|
||||
label={<T>Members to Form Interface</T>}
|
||||
/>
|
||||
</div>
|
||||
<div className={styles.rows}>
|
||||
{info.members.map((m) => (
|
||||
<div key={m.handleIdentifier} className={styles.row} role="row">
|
||||
<Checkbox
|
||||
className={styles.member}
|
||||
checked={checked.has(m.handleIdentifier)}
|
||||
onChange={(on) => toggle(m.handleIdentifier, on)}
|
||||
label={<span className={styles.label}>{memberLabel(m)}</span>}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
{(error ?? (trimmed && problem)) && (
|
||||
<span className={styles.error} role="alert">
|
||||
{tx(error ?? problem!)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
const cancelRequest = vi.fn(async (_id: number) => ({ status: "ok", data: null }));
|
||||
vi.mock("@/platform/ipc", async (original) => {
|
||||
const ipc = await original<typeof import("@/platform/ipc")>();
|
||||
return { ...ipc, commands: { ...ipc.commands, cancelRequest } };
|
||||
});
|
||||
|
||||
const { cancellable } = await import("./signature");
|
||||
const { isCancelled } = await import("@/platform/ipc");
|
||||
|
||||
describe("cancellable refactoring requests", () => {
|
||||
it("cancels the request in flight when the dialog closes", async () => {
|
||||
const run = new AbortController();
|
||||
let sent = -1;
|
||||
let answer!: (v: string) => void;
|
||||
const reply = cancellable(run.signal, (id) => {
|
||||
sent = id;
|
||||
return new Promise<string>((r) => (answer = r));
|
||||
});
|
||||
run.abort();
|
||||
expect(cancelRequest).toHaveBeenCalledWith(sent);
|
||||
answer("late");
|
||||
await expect(reply).resolves.toBe("late");
|
||||
});
|
||||
|
||||
it("leaves a request alone once it answered", async () => {
|
||||
cancelRequest.mockClear();
|
||||
const run = new AbortController();
|
||||
await cancellable(run.signal, async () => "done");
|
||||
run.abort();
|
||||
expect(cancelRequest).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("never sends a request the dialog closed before", async () => {
|
||||
const run = new AbortController();
|
||||
run.abort();
|
||||
const send = vi.fn(async () => "sent");
|
||||
const err = await cancellable(run.signal, send).catch((e: unknown) => e);
|
||||
expect(isCancelled(err)).toBe(true);
|
||||
expect(send).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("tells the sender once the dialog closed after the request was handed over", async () => {
|
||||
const run = new AbortController();
|
||||
let wanted!: () => boolean;
|
||||
const reply = cancellable(run.signal, async (_id, w) => {
|
||||
wanted = w;
|
||||
return "sent";
|
||||
});
|
||||
expect(wanted()).toBe(true);
|
||||
run.abort();
|
||||
expect(wanted()).toBe(false);
|
||||
await reply;
|
||||
});
|
||||
});
|
||||
@@ -2,7 +2,8 @@
|
||||
* IDEA's refactorings and how language-server code actions map onto them:
|
||||
* `refactor.extract.*` → Extract Method / Introduce Variable…, `refactor.inline*`
|
||||
* → Inline, `refactor.move*` → Move, signature rewrites → Change Signature.
|
||||
* Pull Members Up / Push Members Down come from the Java extension, not code actions.
|
||||
* Pull Members Up / Push Members Down come from the Java extension, Extract Interface from jdtls
|
||||
* requests, not code actions.
|
||||
* Pure; used by Refactor This (⌃T) and the Refactor menu actions.
|
||||
*/
|
||||
import type { CodeAction } from "@/bindings";
|
||||
@@ -17,6 +18,7 @@ export type RefactoringId =
|
||||
| "extractConstant"
|
||||
| "extractField"
|
||||
| "extractParameter"
|
||||
| "extractInterface"
|
||||
| "inline"
|
||||
| "pullMembersUp"
|
||||
| "pushMembersDown";
|
||||
@@ -96,6 +98,13 @@ export const REFACTORINGS: readonly Refactoring[] = [
|
||||
reason: (sel) =>
|
||||
sel ? "Selected block should represent an expression" : "Caret should be inside an expression in a function",
|
||||
},
|
||||
{
|
||||
id: "extractInterface",
|
||||
action: "refactor.extractInterface",
|
||||
label: "Extract Interface…",
|
||||
kind: null,
|
||||
reason: () => "Caret should be inside a class",
|
||||
},
|
||||
{ id: "inline", action: "refactor.inline", label: "Inline…", kind: "refactor.inline", reason: () => AT_NAME },
|
||||
{
|
||||
id: "pullMembersUp",
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { interfaceProblem, memberLabel, packageChoices } from "./extractInterface";
|
||||
|
||||
describe("extract interface", () => {
|
||||
it("labels methods with their parameter types and fields with their type", () => {
|
||||
const m = { name: "area", typeName: "double", parameters: ["int", "String"], handleIdentifier: "m" };
|
||||
expect(memberLabel(m)).toBe("area(int, String): double");
|
||||
expect(memberLabel({ ...m, parameters: [] })).toBe("area(): double");
|
||||
expect(memberLabel({ name: "UNIT", typeName: "int", parameters: null, handleIdentifier: "f" })).toBe("UNIT: int");
|
||||
});
|
||||
|
||||
it("keeps each package's server JSON and marks the file's own package", () => {
|
||||
const json = [
|
||||
JSON.stringify({ displayName: "com.a", path: "src/com/a", isParentOfSelectedFile: true }),
|
||||
JSON.stringify({ displayName: "", path: "src" }),
|
||||
];
|
||||
const [own, root] = packageChoices(json);
|
||||
expect(own).toMatchObject({ name: "com.a", current: true, json: json[0] });
|
||||
expect(root).toMatchObject({ name: "(default package)", current: false });
|
||||
});
|
||||
|
||||
it("needs a valid name other than the class's and at least one member", () => {
|
||||
expect(interfaceProblem("", "Shape", 1)).toBe("No interface name specified");
|
||||
expect(interfaceProblem("1x", "Shape", 1)).toBe("Interface name is not a valid identifier");
|
||||
expect(interfaceProblem("Shape", "Shape", 1)).toBe("Interface name should differ from the class name");
|
||||
expect(interfaceProblem("HasArea", "Shape", 0)).toBe("Select the members to form the interface");
|
||||
expect(interfaceProblem("HasArea", "Shape", 2)).toBeNull();
|
||||
// Java identifiers take letters of any script.
|
||||
expect(interfaceProblem("处理器", "Shape", 1)).toBeNull();
|
||||
expect(interfaceProblem("Größe", "Shape", 1)).toBeNull();
|
||||
expect(interfaceProblem("a-b", "Shape", 1)).toBe("Interface name is not a valid identifier");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,178 @@
|
||||
/**
|
||||
* Extract Interface for Java: jdtls lists the members of the file's class and the packages, the
|
||||
* dialog (`ExtractInterfaceDialog.tsx`) picks the interface's name, package and members, and
|
||||
* jdtls creates the interface, makes the class implement it and uses it where possible.
|
||||
*/
|
||||
import type { Text } from "@codemirror/state";
|
||||
import type { EditorView } from "@codemirror/view";
|
||||
import { create } from "zustand";
|
||||
import type { ExtractInterfaceInfo, InterfaceMember, Pos, ServerRefactored } from "@/bindings";
|
||||
import { whenSynced } from "@/editor/api";
|
||||
import { docOf, isUnavailable, lspRequest } from "@/editor/lsp/lsp";
|
||||
import { offsetToPos } from "@/editor/lsp/positions";
|
||||
import { showHint } from "@/editor/lsp/hint";
|
||||
import { openPopup } from "@/editor/lsp/popupStore";
|
||||
import { summarizeWorkspaceEdit } from "@/editor/lsp/workspaceEdit";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { commands, isCancelled, nextRequestId, unavailableText } from "@/platform/ipc";
|
||||
import { editorService } from "@/workbench/contributions";
|
||||
import { cannotPerform } from "./catalog";
|
||||
import { JAVA_NAME, applyEdit, cancellable, confirmProblems } from "./signature";
|
||||
|
||||
/** Languages whose server extracts interfaces through the dialog. */
|
||||
export const EXTRACT_INTERFACE_LANGUAGES = new Set(["java"]);
|
||||
|
||||
type Json = Record<string, unknown>;
|
||||
|
||||
/** A package the interface can go to; `json` is passed back to the server unchanged. */
|
||||
export interface PackageChoice {
|
||||
name: string;
|
||||
path: string;
|
||||
current: boolean;
|
||||
json: string;
|
||||
}
|
||||
|
||||
export function packageChoices(packages: readonly string[]): PackageChoice[] {
|
||||
return packages.map((json) => {
|
||||
const p = JSON.parse(json) as Json;
|
||||
const text = (v: unknown) => (typeof v === "string" ? v : "");
|
||||
return {
|
||||
name: text(p.displayName) || "(default package)",
|
||||
path: text(p.path),
|
||||
current: !!p.isParentOfSelectedFile,
|
||||
json,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/** `area(double): double` for a method, `UNIT: int` for a field. */
|
||||
export function memberLabel(m: InterfaceMember): string {
|
||||
const params = m.parameters ? `(${m.parameters.join(", ")})` : "";
|
||||
return `${m.name}${params}: ${m.typeName}`;
|
||||
}
|
||||
|
||||
/** Why the interface can't be extracted yet, or null. */
|
||||
export function interfaceProblem(name: string, className: string, members: number): string | null {
|
||||
if (!name) return "No interface name specified";
|
||||
if (!JAVA_NAME.test(name)) return "Interface name is not a valid identifier";
|
||||
if (name === className) return "Interface name should differ from the class name";
|
||||
if (!members) return "Select the members to form the interface";
|
||||
return null;
|
||||
}
|
||||
|
||||
export interface InterfaceRequest {
|
||||
seq: number;
|
||||
view: EditorView;
|
||||
doc: number;
|
||||
pos: Pos;
|
||||
/** The document `pos` refers to. */
|
||||
text: Text;
|
||||
info: ExtractInterfaceInfo;
|
||||
packages: PackageChoice[];
|
||||
}
|
||||
|
||||
export const useExtractInterfaceDialog = create<{ request: InterfaceRequest | null }>(() => ({ request: null }));
|
||||
let seq = 0;
|
||||
let running: AbortController | null = null;
|
||||
|
||||
function errorText(e: unknown): string {
|
||||
if (isUnavailable(e)) return unavailableText(e, "No language server available");
|
||||
return e instanceof Error ? e.message : String(e);
|
||||
}
|
||||
|
||||
/** Extract Interface…: reads the file's class, then opens the dialog. */
|
||||
export async function startExtractInterface(view: EditorView): Promise<void> {
|
||||
const ctx = docOf(view);
|
||||
if (!ctx) return;
|
||||
if (ctx.readOnly) {
|
||||
showHint(view, cannotPerform("The file is read-only"));
|
||||
return;
|
||||
}
|
||||
running?.abort();
|
||||
const run = (running = new AbortController());
|
||||
await whenSynced(view);
|
||||
const state = view.state;
|
||||
const pos = offsetToPos(state.doc, state.selection.main.head);
|
||||
const request = nextRequestId();
|
||||
const abort = () => void commands.cancelRequest(request);
|
||||
run.signal.addEventListener("abort", abort);
|
||||
try {
|
||||
const info = await lspRequest(() => commands.lspExtractInterfaceInfo(request, ctx.doc, pos));
|
||||
if (run.signal.aborted || view.state.doc !== state.doc) return;
|
||||
if (!info.members.length) {
|
||||
showHint(view, cannotPerform("The class has no members to form an interface"));
|
||||
return;
|
||||
}
|
||||
const packages = packageChoices(info.packages);
|
||||
useExtractInterfaceDialog.setState({
|
||||
request: { seq: ++seq, view, doc: ctx.doc, pos, text: state.doc, info, packages },
|
||||
});
|
||||
} catch (e) {
|
||||
if (isCancelled(e) || run.signal.aborted) return;
|
||||
showHint(view, cannotPerform(errorText(e)));
|
||||
} finally {
|
||||
run.signal.removeEventListener("abort", abort);
|
||||
if (running === run) running = null;
|
||||
}
|
||||
}
|
||||
|
||||
export type InterfaceOutcome = { status: "done" } | { status: "stay"; error?: string };
|
||||
|
||||
/** Checks the extraction, confirms its problems and applies the edit (opening the new interface), or previews it. */
|
||||
export async function extractInterface(
|
||||
request: InterfaceRequest,
|
||||
name: string,
|
||||
pkg: PackageChoice,
|
||||
members: readonly string[],
|
||||
preview: boolean,
|
||||
/** The dialog closed: nothing is confirmed, previewed or applied any more. */
|
||||
signal?: AbortSignal,
|
||||
): Promise<InterfaceOutcome> {
|
||||
const { view } = request;
|
||||
if (view.state.doc !== request.text) return { status: "stay", error: "The file changed; open the dialog again" };
|
||||
let confirmation: string | null = null;
|
||||
let extracted: ServerRefactored;
|
||||
try {
|
||||
for (;;) {
|
||||
await whenSynced(view);
|
||||
const token: string | null = confirmation;
|
||||
extracted = await cancellable(signal, (id, wanted) =>
|
||||
lspRequest(
|
||||
() => commands.lspExtractInterface(id, request.doc, request.pos, [...members], name, pkg.json, token),
|
||||
wanted,
|
||||
),
|
||||
);
|
||||
if (signal?.aborted) return { status: "stay" };
|
||||
const fatal = extracted.problems.find((p) => p.severity === "fatal");
|
||||
if (fatal || (!extracted.edit && !extracted.confirmation))
|
||||
return { status: "stay", error: fatal?.message ?? "Nothing to change" };
|
||||
if (!extracted.confirmation) break;
|
||||
if (!(await confirmProblems(extracted.problems.map((p) => p.message))) || signal?.aborted)
|
||||
return { status: "stay" };
|
||||
confirmation = extracted.confirmation;
|
||||
}
|
||||
} catch (e) {
|
||||
if (isCancelled(e) || signal?.aborted) return { status: "stay" };
|
||||
return { status: "stay", error: errorText(e) };
|
||||
}
|
||||
const edit = extracted.edit!;
|
||||
const summary = summarizeWorkspaceEdit(edit);
|
||||
if (!summary.files) return { status: "stay", error: "Nothing to change" };
|
||||
const created = edit.files.find((f) => f.kind === "create")?.path;
|
||||
const apply = async (cancel?: AbortSignal) => {
|
||||
await applyEdit(view, edit, cancel);
|
||||
if (created && !cancel?.aborted) await editorService().openFile(created, { focus: true });
|
||||
};
|
||||
if (preview) {
|
||||
openPopup({
|
||||
kind: "preview",
|
||||
title: tx`Extract Interface from '${request.info.className}'`,
|
||||
summary,
|
||||
confirmLabel: "Do Refactor",
|
||||
onConfirm: () => void apply(),
|
||||
});
|
||||
} else {
|
||||
await apply(signal);
|
||||
}
|
||||
return { status: "done" };
|
||||
}
|
||||
@@ -4,3 +4,4 @@ export { startHierarchyRefactoring } from "./hierarchy";
|
||||
export { ChangeSignatureDialog } from "./ChangeSignatureDialog";
|
||||
export { JAVA_REFACTORING_COMMAND, runJavaRefactoringCommand } from "./javaMove";
|
||||
export { HierarchyDialog } from "./HierarchyDialog";
|
||||
export { ExtractInterfaceDialog } from "./ExtractInterfaceDialog";
|
||||
@@ -66,6 +66,8 @@ const safeDelete = vi.fn();
|
||||
vi.mock("./safeDelete", () => ({ safeDelete }));
|
||||
const startHierarchyRefactoring = vi.fn();
|
||||
vi.mock("./hierarchy", () => ({ startHierarchyRefactoring }));
|
||||
const startExtractInterface = vi.fn();
|
||||
vi.mock("./extractInterface", () => ({ EXTRACT_INTERFACE_LANGUAGES: new Set(["java"]), startExtractInterface }));
|
||||
|
||||
const { classifyAction, kindAdvertised, cannotPerform } = await import("./catalog");
|
||||
const { refactorThis, runRefactoring } = await import("./refactorThis");
|
||||
@@ -195,19 +197,27 @@ describe("Refactor This", () => {
|
||||
expect(lspCodeActionQuery.mock.calls[0]![3]).toEqual(["refactor"]);
|
||||
});
|
||||
|
||||
it("offers Pull Members Up / Push Members Down in Java files, after IDEA's other refactorings", async () => {
|
||||
it("offers Extract Interface, Pull Members Up and Push Members Down in Java files, after IDEA's other refactorings", async () => {
|
||||
query = answer([action("Convert to switch expression", "refactor.rewrite")]);
|
||||
const v = editor("class Dog extends Animal { int price; }", "java");
|
||||
await refactorThis(v, vi.fn());
|
||||
expect(labels()).toEqual(["Pull Members Up…", "Push Members Down…", "Convert to switch expression"]);
|
||||
expect(labels()).toEqual([
|
||||
"Extract Interface…",
|
||||
"Pull Members Up…",
|
||||
"Push Members Down…",
|
||||
"Convert to switch expression",
|
||||
]);
|
||||
const items = (useLspPopup.getState().popup as { items: { label: string; run: () => void }[] }).items;
|
||||
items.find((i) => i.label === "Push Members Down…")!.run();
|
||||
expect(startHierarchyRefactoring).toHaveBeenCalledWith(v, "pushDown");
|
||||
items.find((i) => i.label === "Extract Interface…")!.run();
|
||||
expect(startExtractInterface).toHaveBeenCalledWith(v);
|
||||
closePopup();
|
||||
v.destroy();
|
||||
// Other languages have no server for them; nor does Java while its server is down.
|
||||
await refactorThis(editor(), vi.fn());
|
||||
expect(labels()).not.toContain("Pull Members Up…");
|
||||
expect(labels()).not.toContain("Extract Interface…");
|
||||
query = async () => unavailable;
|
||||
await refactorThis(editor("class Dog {}", "java"), vi.fn());
|
||||
expect(labels()).toEqual(["Nothing here"]);
|
||||
|
||||
@@ -41,6 +41,7 @@ import {
|
||||
import { safeDelete } from "./safeDelete";
|
||||
import { startHierarchyRefactoring } from "./hierarchy";
|
||||
import { SIGNATURE_LANGUAGES, startChangeSignature } from "./signature";
|
||||
import { EXTRACT_INTERFACE_LANGUAGES, startExtractInterface } from "./extractInterface";
|
||||
|
||||
/** Languages with a server that runs the class-hierarchy refactorings (the app-owned JDT extension; Phoxite for PHP). */
|
||||
const HIERARCHY_LANGUAGES = new Set(["java", "php"]);
|
||||
@@ -158,6 +159,11 @@ export async function runRefactoring(view: EditorView, id: RefactoringId): Promi
|
||||
await startChangeSignature(view);
|
||||
return;
|
||||
}
|
||||
if (id === "extractInterface") {
|
||||
if (EXTRACT_INTERFACE_LANGUAGES.has(ctx.language)) await startExtractInterface(view);
|
||||
else showHint(view, cannotPerform(`Extract Interface is not supported for ${await languageName(ctx.language)}`));
|
||||
return;
|
||||
}
|
||||
// IDEA picks the expression first (and the server then extracts exactly that one).
|
||||
if (EXPRESSION_REFACTORINGS.has(id) && view.state.selection.main.empty) {
|
||||
if (await chooseExpressionFirst(view, () => runRefactoring(view, id))) return;
|
||||
@@ -224,12 +230,13 @@ async function expressionAtCaret(view: EditorView, signal: AbortSignal): Promise
|
||||
export function refactorThisItems(
|
||||
view: EditorView,
|
||||
answer: ServerAnswer,
|
||||
facts: { symbol: boolean; expression: boolean; hierarchy?: boolean; signature?: boolean },
|
||||
facts: { symbol: boolean; expression: boolean; hierarchy?: boolean; signature?: boolean; extractInterface?: boolean },
|
||||
run: {
|
||||
rename: (view: EditorView) => unknown;
|
||||
safeDelete: (view: EditorView) => unknown;
|
||||
hierarchy?: (view: EditorView, kind: "pullUp" | "pushDown") => unknown;
|
||||
signature?: (view: EditorView) => unknown;
|
||||
extractInterface?: (view: EditorView) => unknown;
|
||||
},
|
||||
): ListPopupItem[] {
|
||||
const { mapped, other } = groupActions(answer.status === "ok" ? answer.query.actions : []);
|
||||
@@ -245,6 +252,8 @@ export function refactorThisItems(
|
||||
go = () => runRefactoring(view, r.id);
|
||||
else if (r.id === "changeSignature" && facts.signature && serverUsable && run.signature)
|
||||
go = () => run.signature!(view);
|
||||
else if (r.id === "extractInterface" && facts.extractInterface && serverUsable && run.extractInterface)
|
||||
go = () => run.extractInterface!(view);
|
||||
else if (actions.length) go = () => runActions(view, r.label.replace(/…$/, ""), actions, r.id);
|
||||
else if (r.id === "rename" && facts.symbol) go = () => run.rename(view);
|
||||
else if (r.id === "safeDelete" && facts.symbol && !docOf(view)?.readOnly) go = () => run.safeDelete(view);
|
||||
@@ -287,11 +296,18 @@ export async function refactorThis(view: EditorView, rename: (view: EditorView)
|
||||
]);
|
||||
const hierarchy = HIERARCHY_LANGUAGES.has(ctx.language) && !ctx.readOnly;
|
||||
const signature = SIGNATURE_LANGUAGES.has(ctx.language) && !ctx.readOnly && symbol;
|
||||
const extractInterface = EXTRACT_INTERFACE_LANGUAGES.has(ctx.language) && !ctx.readOnly;
|
||||
items = refactorThisItems(
|
||||
view,
|
||||
answer,
|
||||
{ symbol, expression, hierarchy, signature },
|
||||
{ rename, safeDelete, hierarchy: startHierarchyRefactoring, signature: startChangeSignature },
|
||||
{ symbol, expression, hierarchy, signature, extractInterface },
|
||||
{
|
||||
rename,
|
||||
safeDelete,
|
||||
hierarchy: startHierarchyRefactoring,
|
||||
signature: startChangeSignature,
|
||||
extractInterface: startExtractInterface,
|
||||
},
|
||||
);
|
||||
} catch (e) {
|
||||
if (isCancelled(e)) return;
|
||||
|
||||
@@ -23,6 +23,10 @@ describe("change signature", () => {
|
||||
it("tells what keeps the signature from being submitted", () => {
|
||||
expect(signatureProblem(info)).toBeNull();
|
||||
expect(signatureProblem({ ...info, methodName: "2x" })).toBe("Method name is not a valid identifier");
|
||||
expect(signatureProblem({ ...info, methodName: "处理" })).toBeNull();
|
||||
expect(
|
||||
signatureProblem({ ...info, parameters: info.parameters.map((p, i) => ({ ...p, name: `数量${i}` })) }),
|
||||
).toBeNull();
|
||||
expect(signatureProblem({ ...info, returnType: " " })).toBe("Return type is not specified");
|
||||
const dup = { ...info, parameters: [info.parameters[0]!, { ...info.parameters[1]!, name: "a" }] };
|
||||
expect(signatureProblem(dup)).toBe("Duplicate parameter name");
|
||||
|
||||
@@ -15,7 +15,7 @@ import { showHint } from "@/editor/lsp/hint";
|
||||
import { openPopup } from "@/editor/lsp/popupStore";
|
||||
import { summarizeWorkspaceEdit } from "@/editor/lsp/workspaceEdit";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { commands, isCancelled, nextRequestId, unavailableText } from "@/platform/ipc";
|
||||
import { IpcError, commands, isCancelled, nextRequestId, unavailableText } from "@/platform/ipc";
|
||||
import { ask } from "@/workbench/messages";
|
||||
import { cannotPerform } from "./catalog";
|
||||
|
||||
@@ -50,7 +50,8 @@ export function signatureText(sig: {
|
||||
return head + throws;
|
||||
}
|
||||
|
||||
const JAVA_NAME = /^[A-Za-z_$][\w$]*$/;
|
||||
/** A Java identifier: letters of any script, `$` and `_`, then digits and combining marks too. */
|
||||
export const JAVA_NAME = /^[\p{L}\p{Nl}\p{Sc}\p{Pc}][\p{L}\p{Nl}\p{Sc}\p{Pc}\p{Nd}\p{Mn}\p{Mc}]*$/u;
|
||||
|
||||
/** Why the edited signature can't be submitted yet, or null. */
|
||||
export function signatureProblem(sig: MethodSignature): string | null {
|
||||
@@ -128,15 +129,40 @@ export async function startChangeSignature(view: EditorView): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
export async function applyEdit(view: EditorView, edit: WorkspaceEdit) {
|
||||
export async function applyEdit(view: EditorView, edit: WorkspaceEdit, signal?: AbortSignal) {
|
||||
try {
|
||||
await whenAllSynced();
|
||||
await lspRequest(() => commands.applyWorkspaceEdit(edit));
|
||||
// The dialog closed while the editors were syncing: nothing is applied.
|
||||
if (signal?.aborted) return;
|
||||
await lspRequest(
|
||||
() => commands.applyWorkspaceEdit(edit),
|
||||
() => !signal?.aborted,
|
||||
);
|
||||
} catch (e) {
|
||||
reportLspError(view, e, true);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends `send(id, wanted)` with a fresh request id that `signal` cancels. `wanted` goes to
|
||||
* `lspRequest`, which syncs editors first: a dialog closed meanwhile never sends the request.
|
||||
*/
|
||||
export async function cancellable<T>(
|
||||
signal: AbortSignal | undefined,
|
||||
send: (id: number, wanted: () => boolean) => Promise<T>,
|
||||
): Promise<T> {
|
||||
// Closed before the request went out: it never does (a cancel can't reach an unsent request).
|
||||
if (signal?.aborted) throw new IpcError({ kind: "cancelled", message: "Cancelled" });
|
||||
const id = nextRequestId();
|
||||
const abort = () => void commands.cancelRequest(id);
|
||||
signal?.addEventListener("abort", abort);
|
||||
try {
|
||||
return await send(id, () => !signal?.aborted);
|
||||
} finally {
|
||||
signal?.removeEventListener("abort", abort);
|
||||
}
|
||||
}
|
||||
|
||||
export async function confirmProblems(messages: readonly string[]): Promise<boolean> {
|
||||
const { button } = await ask({
|
||||
title: "Problems Detected",
|
||||
@@ -158,6 +184,8 @@ export async function changeSignature(
|
||||
signature: MethodSignature,
|
||||
delegate: boolean,
|
||||
preview: boolean,
|
||||
/** The dialog closed: nothing is confirmed, previewed or applied any more. */
|
||||
signal?: AbortSignal,
|
||||
): Promise<SignatureOutcome> {
|
||||
const { view } = request;
|
||||
if (view.state.doc !== request.text) return { status: "stay", error: "The file changed; open the dialog again" };
|
||||
@@ -167,18 +195,20 @@ export async function changeSignature(
|
||||
for (;;) {
|
||||
await whenSynced(view);
|
||||
const token: string | null = confirmation;
|
||||
changed = await lspRequest(() =>
|
||||
commands.lspChangeSignature(nextRequestId(), request.doc, request.pos, signature, delegate, token),
|
||||
changed = await cancellable(signal, (id, wanted) =>
|
||||
lspRequest(() => commands.lspChangeSignature(id, request.doc, request.pos, signature, delegate, token), wanted),
|
||||
);
|
||||
if (signal?.aborted) return { status: "stay" };
|
||||
const fatal = changed.problems.find((p) => p.severity === "fatal");
|
||||
if (fatal || (!changed.edit && !changed.confirmation))
|
||||
return { status: "stay", error: fatal?.message ?? "Nothing to change" };
|
||||
if (!changed.confirmation) break;
|
||||
if (!(await confirmProblems(changed.problems.map((p) => p.message)))) return { status: "stay" };
|
||||
if (!(await confirmProblems(changed.problems.map((p) => p.message))) || signal?.aborted)
|
||||
return { status: "stay" };
|
||||
confirmation = changed.confirmation;
|
||||
}
|
||||
} catch (e) {
|
||||
if (isCancelled(e)) return { status: "stay" };
|
||||
if (isCancelled(e) || signal?.aborted) return { status: "stay" };
|
||||
return { status: "stay", error: errorText(e) };
|
||||
}
|
||||
const edit = changed.edit!;
|
||||
@@ -193,7 +223,7 @@ export async function changeSignature(
|
||||
onConfirm: () => void applyEdit(view, edit),
|
||||
});
|
||||
} else {
|
||||
await applyEdit(view, edit);
|
||||
await applyEdit(view, edit, signal);
|
||||
}
|
||||
return { status: "done" };
|
||||
}
|
||||
@@ -173,9 +173,6 @@
|
||||
.chipDetail > span {
|
||||
grid-area: 1 / 1;
|
||||
}
|
||||
.chipSizer {
|
||||
visibility: hidden;
|
||||
}
|
||||
.chipChevron {
|
||||
flex: none;
|
||||
color: var(--fg-muted);
|
||||
@@ -222,46 +219,38 @@
|
||||
color: var(--fg-muted);
|
||||
cursor: default;
|
||||
}
|
||||
.activeModelBar {
|
||||
/* The model popup's top: effort (and context size) as segmented controls. */
|
||||
.quickSettings {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-1-5);
|
||||
padding: 4px 10px 10px;
|
||||
margin-bottom: 4px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.quickRow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
width: calc(100% - 12px);
|
||||
margin: 2px 6px 6px;
|
||||
padding: 6px 8px;
|
||||
border: 0;
|
||||
border-radius: var(--radius-control);
|
||||
background: var(--bg-elev);
|
||||
box-shadow: inset 0 0 0 1px var(--border);
|
||||
color: var(--fg-strong);
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
transition: background var(--dur-fast) var(--ease);
|
||||
}
|
||||
.activeModelBar:hover,
|
||||
.activeModelBar:focus-visible {
|
||||
outline: none;
|
||||
background: var(--bg-hover);
|
||||
}
|
||||
.activeModelName {
|
||||
flex: 1 1 auto;
|
||||
.quickRow > .segmented {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
font-weight: 600;
|
||||
}
|
||||
.activeModelMeta {
|
||||
.quickLabel {
|
||||
flex: none;
|
||||
width: 52px;
|
||||
color: var(--fg-muted);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
.activeModelGear {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--space-0-5);
|
||||
flex: none;
|
||||
color: var(--fg-muted);
|
||||
/* A model's configure button shows on its row's hover only. */
|
||||
.modelEffortPopup [role="option"] .modelRowConfigure {
|
||||
opacity: 0;
|
||||
}
|
||||
.modelEffortPopup [role="option"]:hover .modelRowConfigure,
|
||||
.modelEffortPopup [role="option"][aria-selected="true"] .modelRowConfigure,
|
||||
.modelEffortPopup .modelRowConfigure:focus-visible {
|
||||
opacity: 1;
|
||||
}
|
||||
.modelRowConfigure {
|
||||
display: grid;
|
||||
@@ -299,52 +288,9 @@
|
||||
color: var(--warning);
|
||||
}
|
||||
|
||||
/* Page 2: per-model configuration view. */
|
||||
.modelDetail {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-3);
|
||||
padding: 6px 12px 8px;
|
||||
}
|
||||
.modelDetailHeader {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
}
|
||||
.modelDetailTitle {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
color: var(--fg-strong);
|
||||
font-weight: 600;
|
||||
}
|
||||
.modelDetailActions {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--space-0-5);
|
||||
flex: none;
|
||||
}
|
||||
.pinnedButton {
|
||||
color: var(--accent);
|
||||
}
|
||||
.detailSection {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-1-5);
|
||||
}
|
||||
.detailSectionLabel {
|
||||
color: var(--fg-strong);
|
||||
font-weight: 600;
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
.detailRow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-3);
|
||||
}
|
||||
.segmented {
|
||||
display: flex;
|
||||
align-items: stretch;
|
||||
@@ -384,84 +330,6 @@
|
||||
color: var(--fg-strong);
|
||||
font-weight: 600;
|
||||
}
|
||||
.costCard {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-1);
|
||||
padding: 8px 10px;
|
||||
border-radius: var(--radius-popup);
|
||||
background: var(--bg-elev);
|
||||
box-shadow: inset 0 0 0 1px var(--border);
|
||||
}
|
||||
.costCardHeader {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
.costCardTitle {
|
||||
color: var(--fg-strong);
|
||||
font-weight: 600;
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
.costCardRow {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-3);
|
||||
color: var(--fg-secondary);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
.costCardValue {
|
||||
color: var(--fg-strong);
|
||||
font-weight: 600;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.pricingCard {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
border-radius: var(--radius-popup);
|
||||
background: var(--bg-elev);
|
||||
box-shadow: inset 0 0 0 1px var(--border);
|
||||
}
|
||||
.pricingHeader {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
width: 100%;
|
||||
padding: 8px 10px;
|
||||
border: 0;
|
||||
border-radius: inherit;
|
||||
background: transparent;
|
||||
color: var(--fg-strong);
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
}
|
||||
.pricingHeader:hover,
|
||||
.pricingHeader:focus-visible {
|
||||
outline: none;
|
||||
background: var(--bg-hover);
|
||||
}
|
||||
.pricingChevron {
|
||||
flex: none;
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
.pricingTitle {
|
||||
flex: 1 1 auto;
|
||||
font-weight: 600;
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
.pricingBody {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-1);
|
||||
padding: 2px 12px 10px;
|
||||
}
|
||||
.pricingSubhead {
|
||||
margin-bottom: 2px;
|
||||
color: var(--fg-muted);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
.modePopup {
|
||||
min-width: 200px;
|
||||
padding: 6px 0;
|
||||
@@ -561,9 +429,6 @@
|
||||
gap: 5px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.pickerName {
|
||||
color: var(--fg-subtle);
|
||||
}
|
||||
|
||||
/* Above the text: the current file to reference, attached files and images. */
|
||||
.context {
|
||||
|
||||
@@ -33,7 +33,9 @@ import {
|
||||
Icon,
|
||||
IconButton,
|
||||
List,
|
||||
Menu,
|
||||
Popup,
|
||||
type MenuItem,
|
||||
firstSelectable,
|
||||
listNavigate,
|
||||
fileIconName,
|
||||
@@ -141,6 +143,8 @@ export interface ComposerProps {
|
||||
toolbar?: ReactNode;
|
||||
/** Right of the bottom row: send / stop buttons. */
|
||||
actions?: ReactNode;
|
||||
/** Extra items for the Add Context menu, after the file and image items. */
|
||||
addMenu?: MenuItem[];
|
||||
className?: string;
|
||||
}
|
||||
|
||||
@@ -979,6 +983,18 @@ export function Composer(props: ComposerProps) {
|
||||
[id, projectRoot, root],
|
||||
);
|
||||
|
||||
const [addOpen, setAddOpen] = useState(false);
|
||||
const addAnchor = useRef<HTMLButtonElement>(null);
|
||||
const insertMention = () => {
|
||||
const view = viewRef.current;
|
||||
if (!view) return;
|
||||
// At the caret while typing, else after the text.
|
||||
const end = view.state.doc.length;
|
||||
const { from, to } = view.hasFocus ? view.state.selection.main : { from: end, to: end };
|
||||
const before = view.state.sliceDoc(Math.max(0, from - 1), from);
|
||||
replace(from, to, before && !/\s/.test(before) ? " @" : "@");
|
||||
view.focus();
|
||||
};
|
||||
const showContext = images.length > 0 || attached.length > 0 || !!suggested;
|
||||
|
||||
return (
|
||||
@@ -1107,14 +1123,23 @@ export function Composer(props: ComposerProps) {
|
||||
<Icon name={fileIconName(basename(suggested.rel), suggested.rel)} size={14} />
|
||||
<span className={styles.attachmentName}>{basename(suggested.rel)}</span>
|
||||
<span className={styles.suggestionHint}>{tx("Current File")}</span>
|
||||
{/* The chip is the IDE context switch: off here, back on from the dashed chip. */}
|
||||
<button
|
||||
type="button"
|
||||
className={styles.removeChip}
|
||||
aria-label={tx("Don't Add the Current File")}
|
||||
onClick={() => setIdeContext(false)}
|
||||
>
|
||||
<Icon name="close" size={10} />
|
||||
</button>
|
||||
</span>
|
||||
)}
|
||||
{suggested && !ideContext && (
|
||||
<button
|
||||
type="button"
|
||||
className={styles.suggestion}
|
||||
title={tx`Reference ${suggested.rel}`}
|
||||
onClick={() => addPaths([suggested.path])}
|
||||
title={tx`Add ${suggested.rel} and the selection to your requests`}
|
||||
onClick={() => setIdeContext(true)}
|
||||
>
|
||||
<Icon name="plus" size={12} />
|
||||
<Icon name={fileIconName(basename(suggested.rel), suggested.rel)} size={14} />
|
||||
@@ -1167,35 +1192,25 @@ export function Composer(props: ComposerProps) {
|
||||
<div className={styles.toolbar}>{props.toolbar}</div>
|
||||
<div className={styles.actions}>
|
||||
<IconButton
|
||||
icon="paperclip"
|
||||
title="Reference a File (@)"
|
||||
ref={addAnchor}
|
||||
icon="plus"
|
||||
title="Add Context"
|
||||
aria-haspopup="menu"
|
||||
aria-expanded={addOpen}
|
||||
className={styles.composerButton}
|
||||
onClick={() => {
|
||||
const view = viewRef.current;
|
||||
if (!view) return;
|
||||
// At the caret while typing, else after the text.
|
||||
const end = view.state.doc.length;
|
||||
const { from, to } = view.hasFocus ? view.state.selection.main : { from: end, to: end };
|
||||
const before = view.state.sliceDoc(Math.max(0, from - 1), from);
|
||||
replace(from, to, before && !/\s/.test(before) ? " @" : "@");
|
||||
}}
|
||||
onClick={() => setAddOpen((v) => !v)}
|
||||
/>
|
||||
<IconButton
|
||||
icon="file-code"
|
||||
title={
|
||||
ideContext
|
||||
? "IDE Context Enabled: the current file and selection are added to your request"
|
||||
: "IDE Context Disabled: the current file and selection are not added to your request"
|
||||
}
|
||||
pressed={ideContext}
|
||||
className={styles.composerButton}
|
||||
onClick={() => setIdeContext(!ideContext)}
|
||||
/>
|
||||
<IconButton
|
||||
icon="image"
|
||||
title="Attach Image…"
|
||||
className={styles.composerButton}
|
||||
onClick={() => imageInput.current?.click()}
|
||||
<Menu
|
||||
open={addOpen}
|
||||
anchor={addAnchor}
|
||||
placement="bottom-end"
|
||||
onClose={() => setAddOpen(false)}
|
||||
aria-label="Add Context"
|
||||
items={[
|
||||
{ id: "reference", label: "Reference a File (@)", icon: "paperclip", run: insertMention },
|
||||
{ id: "image", label: "Attach Image…", icon: "image", run: () => imageInput.current?.click() },
|
||||
...(props.addMenu ?? []),
|
||||
]}
|
||||
/>
|
||||
<input
|
||||
ref={imageInput}
|
||||
|
||||
@@ -273,15 +273,19 @@ describe("model and effort button", () => {
|
||||
},
|
||||
];
|
||||
|
||||
it("shows the model with the agent's effort name and the mode with Allow All", () => {
|
||||
render(<ConfigPickers config={copilotConfig()} onChange={vi.fn()} />);
|
||||
const model = screen.getByRole("button", { name: "Model" });
|
||||
expect(model).toHaveTextContent("Claude Sonnet 5.5medium");
|
||||
it("shows the effort as its own picker beside the model, and the mode with Allow All", () => {
|
||||
const onChange = vi.fn();
|
||||
render(<ConfigPickers config={copilotConfig()} onChange={onChange} />);
|
||||
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("Claude Sonnet 5.5");
|
||||
expect(screen.getByRole("button", { name: "Mode" })).toHaveTextContent("AgentAllow All");
|
||||
expect(screen.queryByRole("button", { name: "Reasoning Effort" })).not.toBeInTheDocument();
|
||||
const effort = screen.getByRole("button", { name: "Reasoning Effort" });
|
||||
expect(effort).toHaveTextContent("medium");
|
||||
fireEvent.click(effort);
|
||||
fireEvent.click(screen.getByRole("option", { name: "XHigh" }));
|
||||
expect(onChange).toHaveBeenCalledExactlyOnceWith("reasoning_effort", "xhigh");
|
||||
});
|
||||
|
||||
it("tucks Fast into the model popup with effort", () => {
|
||||
it("tucks Fast into the model popup", () => {
|
||||
const config = [
|
||||
...copilotConfig().filter((o) => o.category !== "thought_level"),
|
||||
{
|
||||
@@ -297,23 +301,21 @@ describe("model and effort button", () => {
|
||||
render(<ConfigPickers config={config} onChange={vi.fn()} />);
|
||||
expect(screen.queryByRole("switch", { name: "Fast" })).not.toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Model" }));
|
||||
const dialog = screen.getByRole("dialog", { name: "Model & effort settings" });
|
||||
const dialog = screen.getByRole("dialog", { name: "Model" });
|
||||
expect(within(dialog).getByRole("switch", { name: "Fast" })).toHaveAttribute("aria-checked", "false");
|
||||
});
|
||||
|
||||
it("navigates to the detail page for segmented effort, Reset, Pin, and cost badge", () => {
|
||||
it("lists models by name in one page, with context size, cost and pinning", () => {
|
||||
const onChange = vi.fn();
|
||||
const cfg = copilotConfig().map((o) =>
|
||||
o.id === "model"
|
||||
? {
|
||||
...o,
|
||||
values: o.values.map((v) =>
|
||||
v.value === "claude-sonnet-5.5" ? { ...v, costCategory: "medium", usageMultiplier: "1x" } : v,
|
||||
v.value === "claude-sonnet-5.5" ? { ...v, costCategory: "medium", description: "Balanced" } : v,
|
||||
),
|
||||
}
|
||||
: o.id === "reasoning_effort"
|
||||
? { ...o, defaultValue: "medium" }
|
||||
: o,
|
||||
: o,
|
||||
);
|
||||
cfg.push({
|
||||
id: "contextTier",
|
||||
@@ -325,106 +327,37 @@ describe("model and effort button", () => {
|
||||
via: "option",
|
||||
values: [value("default", "200K"), value("long_context", "1M")],
|
||||
});
|
||||
render(<ConfigPickers config={cfg} values={{ reasoning_effort: "high" }} onChange={onChange} />);
|
||||
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("Claude Sonnet 5.5high · 1M");
|
||||
render(<ConfigPickers config={cfg} onChange={onChange} />);
|
||||
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("Claude Sonnet 5.51M");
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Model" }));
|
||||
const dialog = screen.getByRole("dialog", { name: "Model & effort settings" });
|
||||
const dialog = screen.getByRole("dialog", { name: "Model" });
|
||||
expect(within(dialog).queryByText("Balanced")).not.toBeInTheDocument();
|
||||
expect(within(dialog).getByText("Medium cost")).toBeVisible();
|
||||
|
||||
// Pick another model directly from Page 1.
|
||||
fireEvent.click(within(dialog).getByRole("option", { name: /GPT-6 Sol/ }));
|
||||
expect(onChange).toHaveBeenCalledWith("model", "gpt-6-sol");
|
||||
|
||||
// Open Page 2 (detail configuration view) for the active model.
|
||||
fireEvent.click(within(dialog).getByRole("button", { name: "Configure model" }));
|
||||
const effortGroup = within(dialog).getByRole("radiogroup", { name: "Reasoning Effort" });
|
||||
expect(within(effortGroup).getByRole("radio", { name: "high" })).toHaveAttribute("aria-checked", "true");
|
||||
fireEvent.click(within(effortGroup).getByRole("radio", { name: "XHigh" }));
|
||||
expect(onChange).toHaveBeenCalledWith("reasoning_effort", "xhigh");
|
||||
|
||||
const contextGroup = within(dialog).getByRole("radiogroup", { name: "Context Size" });
|
||||
expect(within(contextGroup).getByRole("radio", { name: "1M" })).toHaveAttribute("aria-checked", "true");
|
||||
fireEvent.click(within(contextGroup).getByRole("radio", { name: "200K" }));
|
||||
expect(onChange).toHaveBeenCalledWith("contextTier", "default");
|
||||
|
||||
// Cost badge & multiplier render in the detail card.
|
||||
expect(within(dialog).getByText("Medium cost")).toBeVisible();
|
||||
expect(within(dialog).getByText("1x")).toBeVisible();
|
||||
|
||||
// Reset restores both effort and contextTier to their agent defaults.
|
||||
onChange.mockClear();
|
||||
fireEvent.click(within(dialog).getByRole("button", { name: "Reset to defaults" }));
|
||||
expect(onChange).toHaveBeenCalledWith("reasoning_effort", "medium");
|
||||
expect(onChange).toHaveBeenCalledWith("contextTier", "default");
|
||||
|
||||
// Pin model, navigate back to Page 1, and verify Pinned + Models sections appear.
|
||||
fireEvent.click(within(dialog).getByRole("button", { name: "Pin model" }));
|
||||
fireEvent.click(within(dialog).getByRole("button", { name: "Back to models" }));
|
||||
fireEvent.click(within(dialog).getAllByRole("button", { name: "Pin model" })[0]!);
|
||||
const listbox = within(dialog).getByRole("listbox", { name: "Model" });
|
||||
expect(within(listbox).getByText("Pinned")).toBeVisible();
|
||||
expect(within(listbox).getByText("Models")).toBeVisible();
|
||||
});
|
||||
|
||||
it("updates per-tier token pricing live when switching Context Size", () => {
|
||||
const cfg = copilotConfig().map((o) =>
|
||||
o.id === "model"
|
||||
? {
|
||||
...o,
|
||||
values: o.values.map((v) =>
|
||||
v.value === "claude-sonnet-5.5"
|
||||
? {
|
||||
...v,
|
||||
pricing: {
|
||||
costTier: "medium",
|
||||
multiplier: 1,
|
||||
tiers: {
|
||||
default: { input: 200, output: 1000, cacheRead: 10, cacheWrite: 0, contextTokens: 200_000 },
|
||||
long_context: {
|
||||
input: 400,
|
||||
output: 2000,
|
||||
cacheRead: 20,
|
||||
cacheWrite: 0,
|
||||
contextTokens: 1_000_000,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
: v,
|
||||
),
|
||||
}
|
||||
: o,
|
||||
);
|
||||
cfg.push({
|
||||
id: "context_tier",
|
||||
name: "Context Size",
|
||||
category: "model_config",
|
||||
description: null,
|
||||
current: "long_context",
|
||||
via: "option",
|
||||
values: [value("default", "200K"), value("long_context", "1M")],
|
||||
});
|
||||
const { rerender } = render(<ConfigPickers config={cfg} onChange={vi.fn()} />);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Model" }));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Configure model" }));
|
||||
expect(screen.getByText("Credits per 1M tokens")).toBeVisible();
|
||||
expect(screen.getByText("400")).toBeVisible();
|
||||
expect(screen.getByText("2000")).toBeVisible();
|
||||
|
||||
rerender(<ConfigPickers config={cfg} values={{ context_tier: "default" }} onChange={vi.fn()} />);
|
||||
expect(screen.getByText("200")).toBeVisible();
|
||||
expect(screen.getByText("1000")).toBeVisible();
|
||||
fireEvent.click(within(dialog).getByRole("option", { name: /GPT-6 Sol/ }));
|
||||
expect(onChange).toHaveBeenCalledWith("model", "gpt-6-sol");
|
||||
expect(screen.queryByRole("dialog", { name: "Model" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("filters the model list and picks the highlighted model with the keyboard", () => {
|
||||
const onChange = vi.fn();
|
||||
render(<ConfigPickers config={copilotConfig()} onChange={onChange} />);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Model" }));
|
||||
const dialog = screen.getByRole("dialog", { name: "Model & effort settings" });
|
||||
const search = within(dialog).getByPlaceholderText("Search…");
|
||||
const search = screen.getByPlaceholderText("Search…");
|
||||
expect(search).toHaveFocus();
|
||||
fireEvent.change(search, { target: { value: "sol" } });
|
||||
expect(within(dialog).getAllByRole("option")).toHaveLength(1);
|
||||
expect(screen.getAllByRole("option")).toHaveLength(1);
|
||||
fireEvent.keyDown(search, { key: "ArrowDown" });
|
||||
fireEvent.keyDown(search, { key: "Enter" });
|
||||
expect(onChange).toHaveBeenLastCalledWith("model", "gpt-6-sol");
|
||||
|
||||
@@ -1,21 +1,24 @@
|
||||
/**
|
||||
* Model, mode, approvals and thinking-effort controls for a composer's bottom row.
|
||||
* With a model plus effort, model-config or cost metadata, one button shows the active
|
||||
* summary and opens a two-page popup: a searchable model list (with pinned models and
|
||||
* per-row configure buttons) and a per-model configuration view with segmented Effort
|
||||
* Level, optional segmented Context Size, Reset / Pin actions, and a cost badge.
|
||||
* Model, effort, mode and approvals controls for a composer's bottom row. The model button
|
||||
* opens a searchable model list (pinned models first, context size above it); the effort is
|
||||
* its own picker beside it, one click away.
|
||||
*/
|
||||
import { useEffect, useRef, useState, type KeyboardEvent } from "react";
|
||||
import clsx from "clsx";
|
||||
import type { AgentConfigOption, AgentModelPricing } from "@/bindings";
|
||||
import { tx as rawTx, useTx } from "@/platform/i18n";
|
||||
import type { AgentConfigOption } from "@/bindings";
|
||||
import { useTx } from "@/platform/i18n";
|
||||
import { Icon, IconButton, Popup, Select, T, Toggle } from "@/ui";
|
||||
import { SelectListbox, type SelectOption } from "@/ui/Select";
|
||||
import { formatCreditRate, isContextOption, mainOptions, modelConfigOptions, modeIcon } from "./composerModel";
|
||||
import { isContextOption, mainOptions, modelConfigOptions, modeIcon } from "./composerModel";
|
||||
import { togglePinnedModel, useAgents } from "./store";
|
||||
import styles from "./Composer.module.css";
|
||||
|
||||
export function configPickerOptions(option: AgentConfigOption, pinned: readonly string[] = []): SelectOption[] {
|
||||
export function configPickerOptions(
|
||||
option: AgentConfigOption,
|
||||
pinned: readonly string[] = [],
|
||||
/** Without each model's description: the model popup lists names only. */
|
||||
descriptions = true,
|
||||
): SelectOption[] {
|
||||
if (option.category !== "model") {
|
||||
return option.values.map((v) => ({ value: v.value, label: v.name, detail: v.description ?? undefined }));
|
||||
}
|
||||
@@ -26,7 +29,9 @@ export function configPickerOptions(option: AgentConfigOption, pinned: readonly
|
||||
const path = slash >= 0 ? v.value.slice(slash + 1) : "";
|
||||
const label = path ? path.slice(path.lastIndexOf("/") + 1) : v.name || v.value;
|
||||
const mult = v.usageMultiplier && !v.description?.startsWith(v.usageMultiplier) ? v.usageMultiplier : undefined;
|
||||
const parts = [path || undefined, mult, v.description ?? undefined].filter((p): p is string => !!p);
|
||||
const parts = [path || undefined, mult, (descriptions && v.description) || undefined].filter(
|
||||
(p): p is string => !!p,
|
||||
);
|
||||
const detail = parts.length > 0 ? parts.join(" · ") : undefined;
|
||||
return { provider, opt: { value: v.value, label, detail, keywords: provider } };
|
||||
};
|
||||
@@ -104,14 +109,16 @@ export function ConfigPickers({
|
||||
const effort = config.find((o) => o.category === "thought_level" && o.values.length > 0);
|
||||
const modelConfigs = modelConfigOptions(config);
|
||||
const hasCostMeta = model?.values.some((v) => !!v.costCategory || !!v.usageMultiplier || !!v.pricing) ?? false;
|
||||
const combinedModel = model && (modelRefresh || effort || modelConfigs.length > 0 || hasCostMeta);
|
||||
const combinedModel = model && (modelRefresh || modelConfigs.length > 0 || hasCostMeta);
|
||||
const tuckedModelConfig = new Set(modelConfigs.map((o) => o.id));
|
||||
const mode = options.find((o) => o.category === "mode");
|
||||
const allowAll = mode && options.find((o) => switchValues(o));
|
||||
// Effort sits right after the model, as its own one-click picker.
|
||||
const inline = options.filter(
|
||||
(o) => o !== effort && o !== allowAll && !(combinedModel && tuckedModelConfig.has(o.id)),
|
||||
);
|
||||
// The compact menu holds everything but the model button (effort + model parameters).
|
||||
if (effort) inline.splice(model ? inline.indexOf(model) + 1 : 0, 0, effort);
|
||||
// The compact menu holds everything but the model and effort buttons (and the model's own parameters).
|
||||
const secondary = options.filter(
|
||||
(o) => o.category !== "model" && o !== effort && !(combinedModel && tuckedModelConfig.has(o.id)),
|
||||
);
|
||||
@@ -120,13 +127,14 @@ export function ConfigPickers({
|
||||
return (
|
||||
<>
|
||||
{inline.map((o) => (
|
||||
<span key={o.id} className={clsx(styles.configPicker, o.category !== "model" && styles.inlineSetting)}>
|
||||
<span
|
||||
key={o.id}
|
||||
className={clsx(styles.configPicker, o.category !== "model" && o !== effort && styles.inlineSetting)}
|
||||
>
|
||||
{o === model && combinedModel ? (
|
||||
<ModelEffortPicker
|
||||
<ModelPicker
|
||||
model={o}
|
||||
modelValue={valueOf(o)}
|
||||
effort={effort}
|
||||
effortValue={effort ? valueOf(effort) : null}
|
||||
modelConfigs={modelConfigs}
|
||||
valueOf={valueOf}
|
||||
onChange={onChange}
|
||||
@@ -224,24 +232,17 @@ function ConfigPicker({
|
||||
onChange={(v) => onChange(option.id, v)}
|
||||
renderValue={
|
||||
option.category === "thought_level" && !framed
|
||||
? (current) => (
|
||||
<span className={styles.pickerValue}>
|
||||
<span className={styles.pickerName}>{option.name}</span>
|
||||
{current?.label ?? tx("Default")}
|
||||
</span>
|
||||
)
|
||||
? (current) => <span className={styles.pickerValue}>{current?.label ?? tx("Default")}</span>
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
/** Two-page model & per-model configuration picker (searchable list + detail page). */
|
||||
function ModelEffortPicker({
|
||||
/** The model button: a searchable model list, with context size and the model's own settings above it. */
|
||||
function ModelPicker({
|
||||
model,
|
||||
modelValue,
|
||||
effort,
|
||||
effortValue,
|
||||
modelConfigs,
|
||||
valueOf,
|
||||
onChange,
|
||||
@@ -249,8 +250,6 @@ function ModelEffortPicker({
|
||||
}: {
|
||||
model: AgentConfigOption;
|
||||
modelValue: string | null;
|
||||
effort?: AgentConfigOption;
|
||||
effortValue: string | null;
|
||||
modelConfigs: AgentConfigOption[];
|
||||
valueOf: (o: AgentConfigOption) => string | null;
|
||||
onChange: (option: string, value: string) => void;
|
||||
@@ -258,65 +257,26 @@ function ModelEffortPicker({
|
||||
}) {
|
||||
const tx = useTx();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [page, setPage] = useState<"list" | "detail">("list");
|
||||
const pinnedModels = useAgents((s) => s.pinnedModels);
|
||||
const anchor = useRef<HTMLButtonElement>(null);
|
||||
const selectedModel = selected(model, modelValue);
|
||||
const unavailable = modelRefresh && modelValue !== null && !selectedModel;
|
||||
const modelName = unavailable ? tx`${modelValue} (unavailable)` : (selectedModel?.name ?? tx("Default"));
|
||||
const effortName = effort ? (selected(effort, effortValue)?.name ?? tx("Default")) : null;
|
||||
|
||||
const contextOption = modelConfigs.find((o) => isContextOption(o.id) && o.values.length > 0);
|
||||
const contextValue = contextOption ? valueOf(contextOption) : null;
|
||||
const contextLabel = contextOption ? (selected(contextOption, contextValue)?.name ?? null) : null;
|
||||
const otherModelConfigs = modelConfigs.filter((o) => o !== contextOption);
|
||||
|
||||
const chipBadges = [effortName, contextLabel].filter((x): x is string => !!x);
|
||||
const chipBadgeText = chipBadges.join(" · ");
|
||||
|
||||
const otherSummary = otherModelConfigs
|
||||
.map((o) => {
|
||||
const summary = [
|
||||
contextLabel ? `${tx("Context Size")}: ${contextLabel}` : null,
|
||||
...otherModelConfigs.map((o) => {
|
||||
const current = selected(o, valueOf(o));
|
||||
return current ? `${tx(o.name)}: ${current.name}` : null;
|
||||
})
|
||||
.filter(Boolean)
|
||||
.join(" · ");
|
||||
const summary = [
|
||||
effortName ? `${tx(effort!.name)}: ${effortName}` : null,
|
||||
contextLabel ? `${tx("Context Size")}: ${contextLabel}` : null,
|
||||
otherSummary,
|
||||
}),
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(" · ");
|
||||
|
||||
const canConfigureActive = !!(
|
||||
effort ||
|
||||
contextOption ||
|
||||
otherModelConfigs.length > 0 ||
|
||||
selectedModel?.costCategory ||
|
||||
selectedModel?.usageMultiplier ||
|
||||
selectedModel?.pricing
|
||||
);
|
||||
|
||||
const closePopup = () => {
|
||||
setOpen(false);
|
||||
setPage("list");
|
||||
};
|
||||
|
||||
const openDetailFor = (targetModelValue: string) => {
|
||||
if (targetModelValue !== modelValue) {
|
||||
onChange(model.id, targetModelValue);
|
||||
}
|
||||
setPage("detail");
|
||||
};
|
||||
|
||||
const sizerCandidates =
|
||||
effort && !contextLabel
|
||||
? [...new Set([chipBadgeText, ...effort.values.map((v) => v.name)])]
|
||||
: chipBadgeText
|
||||
? [chipBadgeText]
|
||||
: [];
|
||||
|
||||
return (
|
||||
<>
|
||||
<button
|
||||
@@ -327,115 +287,91 @@ function ModelEffortPicker({
|
||||
aria-haspopup="dialog"
|
||||
aria-expanded={open}
|
||||
title={`${tx(model.name)}: ${modelName}${summary ? ` · ${summary}` : ""}`}
|
||||
onClick={() => {
|
||||
setOpen((prev) => {
|
||||
if (prev) setPage("list");
|
||||
return !prev;
|
||||
});
|
||||
}}
|
||||
onClick={() => setOpen((v) => !v)}
|
||||
>
|
||||
<span className={styles.chipValue}>{modelName}</span>
|
||||
{chipBadgeText && (
|
||||
<span className={styles.chipDetail}>
|
||||
{sizerCandidates.map((text) => (
|
||||
<span
|
||||
key={text}
|
||||
className={text === chipBadgeText ? undefined : styles.chipSizer}
|
||||
aria-hidden={text !== chipBadgeText}
|
||||
>
|
||||
{text}
|
||||
</span>
|
||||
))}
|
||||
</span>
|
||||
)}
|
||||
{contextLabel && <span className={styles.chipDetail}>{contextLabel}</span>}
|
||||
<Icon name="chevron-down" size={14} className={styles.chipChevron} />
|
||||
</button>
|
||||
<Popup
|
||||
open={open}
|
||||
anchor={anchor}
|
||||
onClose={closePopup}
|
||||
aria-label={tx("Model & effort settings")}
|
||||
onClose={() => setOpen(false)}
|
||||
aria-label={tx("Model")}
|
||||
className={styles.modelEffortPopup}
|
||||
>
|
||||
{page === "detail" && selectedModel ? (
|
||||
<ModelDetailView
|
||||
modelEntry={selectedModel}
|
||||
effort={effort}
|
||||
effortValue={effortValue}
|
||||
contextOption={contextOption}
|
||||
contextValue={contextValue}
|
||||
otherModelConfigs={otherModelConfigs}
|
||||
valueOf={valueOf}
|
||||
pinned={pinnedModels.includes(selectedModel.value)}
|
||||
onBack={() => setPage("list")}
|
||||
onTogglePin={() => togglePinnedModel(selectedModel.value)}
|
||||
onChange={onChange}
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
{unavailable && (
|
||||
<p className={styles.catalogError} role="alert">
|
||||
<T>Choose another model before starting.</T>
|
||||
</p>
|
||||
)}
|
||||
{canConfigureActive && selectedModel && (
|
||||
<button
|
||||
type="button"
|
||||
className={styles.activeModelBar}
|
||||
aria-label={tx("Configure model")}
|
||||
onClick={() => setPage("detail")}
|
||||
>
|
||||
<span className={styles.activeModelName}>{modelName}</span>
|
||||
<CostBadge category={selectedModel.costCategory} />
|
||||
{chipBadgeText && <span className={styles.activeModelMeta}>{chipBadgeText}</span>}
|
||||
<span className={styles.activeModelGear}>
|
||||
<Icon name="sliders" size={13} />
|
||||
<Icon name="chevron-right" size={12} />
|
||||
{unavailable && (
|
||||
<p className={styles.catalogError} role="alert">
|
||||
<T>Choose another model before starting.</T>
|
||||
</p>
|
||||
)}
|
||||
{(contextOption || otherModelConfigs.length > 0) && (
|
||||
<div className={styles.quickSettings}>
|
||||
{contextOption && (
|
||||
<div className={styles.quickRow}>
|
||||
<span className={styles.quickLabel}>
|
||||
<T>Context Size</T>
|
||||
</span>
|
||||
</button>
|
||||
<SegmentedControl
|
||||
ariaLabel={tx("Context Size")}
|
||||
options={contextOption.values.map((v) => ({
|
||||
value: v.value,
|
||||
label: v.name,
|
||||
description: v.description ?? undefined,
|
||||
}))}
|
||||
value={contextValue ?? contextOption.values[0]!.value}
|
||||
onChange={(v) => onChange(contextOption.id, v)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{otherModelConfigs.map((o) => (
|
||||
<div key={o.id} className={styles.modeFooter}>
|
||||
<span title={o.description ?? undefined}>{tx(o.name)}</span>
|
||||
<div key={o.id} className={styles.quickRow}>
|
||||
<span className={styles.quickLabel} title={o.description ?? undefined}>
|
||||
{tx(o.name)}
|
||||
</span>
|
||||
<ConfigPicker option={o} value={valueOf(o)} onChange={onChange} framed />
|
||||
</div>
|
||||
))}
|
||||
{model.values.length > 0 || !modelRefresh ? (
|
||||
<SelectListbox
|
||||
aria-label={tx(model.name)}
|
||||
value={modelValue}
|
||||
options={configPickerOptions(model, pinnedModels)}
|
||||
searchable
|
||||
listClassName={styles.modelList}
|
||||
onChoose={(v) => onChange(model.id, v)}
|
||||
renderAction={(opt) => {
|
||||
const raw = model.values.find((v) => v.value === opt.value);
|
||||
if (!raw) return null;
|
||||
const showRowBadge = !!raw.costCategory && !raw.description;
|
||||
return (
|
||||
<>
|
||||
{showRowBadge && <CostBadge category={raw.costCategory} />}
|
||||
<button
|
||||
type="button"
|
||||
className={styles.modelRowConfigure}
|
||||
aria-label={rawTx`Configure ${opt.label}`}
|
||||
title={rawTx`Configure ${opt.label}`}
|
||||
onClick={() => openDetailFor(opt.value)}
|
||||
>
|
||||
<Icon name="sliders" size={12} />
|
||||
</button>
|
||||
</>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<p className={styles.catalogNote} role="status">
|
||||
{modelRefresh?.refreshing ? <T>Loading models…</T> : <T>No models reported by this agent.</T>}
|
||||
</p>
|
||||
)}
|
||||
{modelRefresh && <ModelRefreshFooter key={modelRefresh.retryAtMs} {...modelRefresh} />}
|
||||
</>
|
||||
</div>
|
||||
)}
|
||||
{model.values.length > 0 || !modelRefresh ? (
|
||||
<SelectListbox
|
||||
aria-label={tx(model.name)}
|
||||
value={modelValue}
|
||||
options={configPickerOptions(model, pinnedModels, false)}
|
||||
searchable
|
||||
listClassName={styles.modelList}
|
||||
onChoose={(v) => {
|
||||
onChange(model.id, v);
|
||||
setOpen(false);
|
||||
}}
|
||||
renderAction={(opt) => {
|
||||
const raw = model.values.find((v) => v.value === opt.value);
|
||||
if (!raw) return null;
|
||||
const pinned = pinnedModels.includes(raw.value);
|
||||
return (
|
||||
<>
|
||||
<CostBadge category={raw.costCategory} />
|
||||
<button
|
||||
type="button"
|
||||
className={clsx(styles.modelRowConfigure, pinned && styles.pinnedButton)}
|
||||
aria-label={pinned ? tx("Unpin model") : tx("Pin model")}
|
||||
aria-pressed={pinned}
|
||||
title={pinned ? tx("Unpin model") : tx("Pin model")}
|
||||
onClick={() => togglePinnedModel(raw.value)}
|
||||
>
|
||||
<Icon name="pin" size={12} />
|
||||
</button>
|
||||
</>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<p className={styles.catalogNote} role="status">
|
||||
{modelRefresh?.refreshing ? <T>Loading models…</T> : <T>No models reported by this agent.</T>}
|
||||
</p>
|
||||
)}
|
||||
{modelRefresh && <ModelRefreshFooter key={modelRefresh.retryAtMs} {...modelRefresh} />}
|
||||
</Popup>
|
||||
</>
|
||||
);
|
||||
@@ -493,258 +429,6 @@ function CostBadge({ category }: { category: string | null | undefined }) {
|
||||
);
|
||||
}
|
||||
|
||||
/** Page 2: per-model configuration view (segmented Effort, optional Context Size, Reset, Pin, and cost info). */
|
||||
function ModelDetailView({
|
||||
modelEntry,
|
||||
effort,
|
||||
effortValue,
|
||||
contextOption,
|
||||
contextValue,
|
||||
otherModelConfigs,
|
||||
valueOf,
|
||||
pinned,
|
||||
onBack,
|
||||
onTogglePin,
|
||||
onChange,
|
||||
}: {
|
||||
modelEntry: AgentConfigOption["values"][number];
|
||||
effort?: AgentConfigOption;
|
||||
effortValue: string | null;
|
||||
contextOption?: AgentConfigOption;
|
||||
contextValue: string | null;
|
||||
otherModelConfigs: AgentConfigOption[];
|
||||
valueOf: (o: AgentConfigOption) => string | null;
|
||||
pinned: boolean;
|
||||
onBack: () => void;
|
||||
onTogglePin: () => void;
|
||||
onChange: (option: string, value: string) => void;
|
||||
}) {
|
||||
const tx = useTx();
|
||||
const [pricingOpen, setPricingOpen] = useState(true);
|
||||
|
||||
const defaultEffort = effort ? (effort.defaultValue ?? effort.current) : null;
|
||||
const defaultContext = contextOption ? (contextOption.defaultValue ?? contextOption.current) : null;
|
||||
const effortAtDefault = !effort || !defaultEffort || effortValue === defaultEffort;
|
||||
const contextAtDefault = !contextOption || !defaultContext || contextValue === defaultContext;
|
||||
const othersAtDefault = otherModelConfigs.every((o) => {
|
||||
const def = o.defaultValue ?? o.current;
|
||||
return !def || valueOf(o) === def;
|
||||
});
|
||||
const atDefaults = effortAtDefault && contextAtDefault && othersAtDefault;
|
||||
|
||||
const handleReset = () => {
|
||||
if (effort && defaultEffort && effortValue !== defaultEffort) {
|
||||
onChange(effort.id, defaultEffort);
|
||||
}
|
||||
if (contextOption && defaultContext && contextValue !== defaultContext) {
|
||||
onChange(contextOption.id, defaultContext);
|
||||
}
|
||||
for (const o of otherModelConfigs) {
|
||||
const def = o.defaultValue ?? o.current;
|
||||
if (def && valueOf(o) !== def) {
|
||||
onChange(o.id, def);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const compactEffort = (effort?.values.length ?? 0) >= 5;
|
||||
const hasCostCard = !!(modelEntry.costCategory || modelEntry.usageMultiplier);
|
||||
|
||||
return (
|
||||
<div className={styles.modelDetail}>
|
||||
<div className={styles.modelDetailHeader}>
|
||||
<IconButton
|
||||
icon="arrow-left"
|
||||
size="small"
|
||||
aria-label={tx("Back to models")}
|
||||
title={tx("Back to models")}
|
||||
onClick={onBack}
|
||||
/>
|
||||
<span className={styles.modelDetailTitle} title={modelEntry.name}>
|
||||
{modelEntry.name}
|
||||
</span>
|
||||
<div className={styles.modelDetailActions}>
|
||||
<IconButton
|
||||
icon="undo"
|
||||
size="small"
|
||||
disabled={atDefaults}
|
||||
aria-label={tx("Reset to defaults")}
|
||||
title={tx("Reset to defaults")}
|
||||
onClick={handleReset}
|
||||
/>
|
||||
<IconButton
|
||||
icon="pin"
|
||||
size="small"
|
||||
aria-label={pinned ? tx("Unpin model") : tx("Pin model")}
|
||||
title={pinned ? tx("Unpin model") : tx("Pin model")}
|
||||
aria-pressed={pinned}
|
||||
className={clsx(pinned && styles.pinnedButton)}
|
||||
onClick={onTogglePin}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{effort && effort.values.length > 0 && (
|
||||
<div className={styles.detailSection}>
|
||||
<div className={styles.detailSectionLabel}>
|
||||
<T>Effort Level</T>
|
||||
</div>
|
||||
<SegmentedControl
|
||||
ariaLabel={tx(effort.name)}
|
||||
options={effort.values.map((v) => ({
|
||||
value: v.value,
|
||||
label: compactEffort && v.value === "xhigh" ? tx("XHigh") : v.name,
|
||||
description: v.description ?? undefined,
|
||||
}))}
|
||||
value={effortValue ?? effort.values[0]!.value}
|
||||
onChange={(v) => onChange(effort.id, v)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{contextOption && contextOption.values.length > 0 && (
|
||||
<div className={styles.detailSection}>
|
||||
<div className={styles.detailSectionLabel}>
|
||||
<T>Context Size</T>
|
||||
</div>
|
||||
<SegmentedControl
|
||||
ariaLabel={tx("Context Size")}
|
||||
options={contextOption.values.map((v) => ({
|
||||
value: v.value,
|
||||
label: v.name,
|
||||
description: v.description ?? undefined,
|
||||
}))}
|
||||
value={contextValue ?? contextOption.values[0]!.value}
|
||||
onChange={(v) => onChange(contextOption.id, v)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{otherModelConfigs.map((o) => (
|
||||
<div key={o.id} className={styles.detailRow}>
|
||||
<span className={styles.detailSectionLabel} title={o.description ?? undefined}>
|
||||
{tx(o.name)}
|
||||
</span>
|
||||
<ConfigPicker option={o} value={valueOf(o)} onChange={onChange} framed />
|
||||
</div>
|
||||
))}
|
||||
|
||||
{modelEntry.pricing ? (
|
||||
<PricingDetailsCard
|
||||
pricing={modelEntry.pricing}
|
||||
activeTier={contextValue}
|
||||
open={pricingOpen}
|
||||
onToggle={() => setPricingOpen((v) => !v)}
|
||||
/>
|
||||
) : (
|
||||
hasCostCard && (
|
||||
<div className={styles.costCard}>
|
||||
<div className={styles.costCardHeader}>
|
||||
<span className={styles.costCardTitle}>
|
||||
<T>Pricing details</T>
|
||||
</span>
|
||||
<CostBadge category={modelEntry.costCategory} />
|
||||
</div>
|
||||
{modelEntry.usageMultiplier && (
|
||||
<div className={styles.costCardRow}>
|
||||
<span>
|
||||
<T>Multiplier</T>
|
||||
</span>
|
||||
<span className={styles.costCardValue}>{modelEntry.usageMultiplier}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Collapsible per-tier token pricing breakdown card (`Credits per 1M tokens`). */
|
||||
function PricingDetailsCard({
|
||||
pricing,
|
||||
activeTier,
|
||||
open,
|
||||
onToggle,
|
||||
}: {
|
||||
pricing: AgentModelPricing;
|
||||
activeTier: string | null;
|
||||
open: boolean;
|
||||
onToggle: () => void;
|
||||
}) {
|
||||
const tiers = pricing.tiers ?? {};
|
||||
const tierData =
|
||||
(activeTier ? tiers[activeTier] : undefined) ?? tiers["default"] ?? tiers["long_context"] ?? undefined;
|
||||
const hasRates = tierData && (tierData.input != null || tierData.output != null);
|
||||
if (!hasRates && pricing.multiplier == null && !pricing.costTier) return null;
|
||||
|
||||
return (
|
||||
<div className={styles.pricingCard}>
|
||||
<button type="button" className={styles.pricingHeader} aria-expanded={open} onClick={onToggle}>
|
||||
<Icon name={open ? "chevron-down" : "chevron-right"} size={12} className={styles.pricingChevron} />
|
||||
<span className={styles.pricingTitle}>
|
||||
<T>Pricing details</T>
|
||||
</span>
|
||||
{pricing.costTier ? (
|
||||
<CostBadge category={pricing.costTier} />
|
||||
) : (
|
||||
pricing.multiplier != null && (
|
||||
<span className={styles.costBadge}>{`${formatCreditRate(pricing.multiplier)}x`}</span>
|
||||
)
|
||||
)}
|
||||
</button>
|
||||
{open && (
|
||||
<div className={styles.pricingBody}>
|
||||
{hasRates && tierData ? (
|
||||
<>
|
||||
<div className={styles.pricingSubhead}>
|
||||
<T>Credits per 1M tokens</T>
|
||||
</div>
|
||||
<div className={styles.costCardRow}>
|
||||
<span>
|
||||
<T>Input</T>
|
||||
</span>
|
||||
<span className={styles.costCardValue}>{formatCreditRate(tierData.input)}</span>
|
||||
</div>
|
||||
<div className={styles.costCardRow}>
|
||||
<span>
|
||||
<T>Output</T>
|
||||
</span>
|
||||
<span className={styles.costCardValue}>{formatCreditRate(tierData.output)}</span>
|
||||
</div>
|
||||
{tierData.cacheRead != null && (
|
||||
<div className={styles.costCardRow}>
|
||||
<span>
|
||||
<T>Cache Read</T>
|
||||
</span>
|
||||
<span className={styles.costCardValue}>{formatCreditRate(tierData.cacheRead)}</span>
|
||||
</div>
|
||||
)}
|
||||
{tierData.cacheWrite != null && (
|
||||
<div className={styles.costCardRow}>
|
||||
<span>
|
||||
<T>Cache Write</T>
|
||||
</span>
|
||||
<span className={styles.costCardValue}>{formatCreditRate(tierData.cacheWrite)}</span>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
pricing.multiplier != null && (
|
||||
<div className={styles.costCardRow}>
|
||||
<span>
|
||||
<T>Multiplier</T>
|
||||
</span>
|
||||
<span className={styles.costCardValue}>{`${formatCreditRate(pricing.multiplier)}x`}</span>
|
||||
</div>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Accessible segmented pill selector (`role="radiogroup"`) with Left/Right arrow navigation. */
|
||||
function SegmentedControl({
|
||||
ariaLabel,
|
||||
|
||||
@@ -14,8 +14,8 @@
|
||||
color: var(--fg);
|
||||
}
|
||||
.inner {
|
||||
/* The same width as a running session's composer and conversation. */
|
||||
width: min(var(--agent-conversation-width), 100%);
|
||||
/* A compact block in the middle of the page: narrower than a session's conversation. */
|
||||
width: min(680px, 100%);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-2);
|
||||
@@ -24,31 +24,58 @@
|
||||
width: 100%;
|
||||
}
|
||||
.heading {
|
||||
margin: 0 0 10px;
|
||||
font-size: calc(18px + var(--agent-font-zoom, 0px));
|
||||
font-weight: 600;
|
||||
margin: 0 0 14px;
|
||||
font-size: calc(22px + var(--agent-font-zoom, 0px));
|
||||
font-weight: 500;
|
||||
letter-spacing: -0.01em;
|
||||
text-align: center;
|
||||
color: var(--fg-strong);
|
||||
text-wrap: balance;
|
||||
}
|
||||
|
||||
/* Under the box: the project and where the agent works. */
|
||||
/* A box to write in, not a search bar: room for a few lines before it grows. */
|
||||
.composer :global(.cm-content) {
|
||||
min-height: calc(4.5em + 12px);
|
||||
}
|
||||
|
||||
/* Under the box: one quiet group, the project, checkout and branch side by side. */
|
||||
.where {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
/* The chips' own padding spaces them. */
|
||||
gap: var(--space-0-5);
|
||||
padding: 0 2px;
|
||||
gap: var(--space-1);
|
||||
min-width: 0;
|
||||
padding: 0 6px;
|
||||
color: var(--fg-subtle);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
/* The current branch, read-only: same height and colour as the pickers beside it. */
|
||||
.branch {
|
||||
.where > button {
|
||||
flex: 0 1 auto;
|
||||
min-width: 0;
|
||||
color: inherit;
|
||||
font-size: inherit;
|
||||
}
|
||||
/* The row's own gaps space "on" and "from"; the note's padding is for the lines below. */
|
||||
.where .note {
|
||||
padding: 0;
|
||||
.project {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
min-width: 0;
|
||||
height: var(--h-control);
|
||||
padding: 0 4px;
|
||||
}
|
||||
.label {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.projectPicker {
|
||||
max-width: 40%;
|
||||
}
|
||||
|
||||
/* The agent shows as its icon only. */
|
||||
.agentPicker {
|
||||
display: flex;
|
||||
flex: none;
|
||||
}
|
||||
|
||||
.note,
|
||||
@@ -68,31 +95,20 @@
|
||||
justify-content: flex-end;
|
||||
padding: 16px 12px 12px;
|
||||
}
|
||||
.docked .inner {
|
||||
gap: var(--space-2);
|
||||
.dockedIntro {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 100%;
|
||||
min-height: 0;
|
||||
padding-bottom: 8vh;
|
||||
}
|
||||
.docked .where {
|
||||
flex-wrap: nowrap;
|
||||
min-width: 0;
|
||||
}
|
||||
.docked .projectPicker,
|
||||
.docked .projectChip {
|
||||
flex: 0 1 auto;
|
||||
min-width: 0;
|
||||
max-width: 30%;
|
||||
}
|
||||
.docked .branch,
|
||||
.docked .basePicker {
|
||||
order: 1;
|
||||
flex: 0 1 auto;
|
||||
min-width: 0;
|
||||
}
|
||||
.docked .isolation {
|
||||
order: 2;
|
||||
flex: 0 1 auto;
|
||||
min-width: 0;
|
||||
max-width: 45%;
|
||||
margin-left: auto;
|
||||
.docked .heading {
|
||||
margin: 0;
|
||||
font-size: calc(15px + var(--agent-font-zoom, 0px));
|
||||
font-weight: 500;
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
|
||||
.notes {
|
||||
|
||||
@@ -77,6 +77,8 @@ beforeEach(() => {
|
||||
updateComposer(HOME, { text: "Check the project" });
|
||||
});
|
||||
|
||||
const effortButton = () => screen.getByRole("button", { name: "Reasoning" });
|
||||
|
||||
async function chooseModel(model: string) {
|
||||
fireEvent.click(screen.getByRole("button", { name: "Model" }));
|
||||
fireEvent.click(screen.getByRole("option", { name: model }));
|
||||
@@ -85,19 +87,16 @@ async function chooseModel(model: string) {
|
||||
|
||||
it("switches model-specific levels and restores each draft effort before starting", async () => {
|
||||
render(<HomeEditor />);
|
||||
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("bighigh");
|
||||
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("big");
|
||||
expect(effortButton()).toHaveTextContent("high");
|
||||
await chooseModel("small");
|
||||
fireEvent.click(screen.getByRole("button", { name: "Model" }));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Configure model" }));
|
||||
const group = screen.getByRole("radiogroup", { name: "Reasoning" });
|
||||
expect(group).toBeVisible();
|
||||
expect(screen.getByRole("radio", { name: "minimal" })).toHaveAttribute("aria-checked", "true");
|
||||
fireEvent.click(screen.getByRole("radio", { name: "medium" }));
|
||||
fireEvent.keyDown(document, { key: "Escape" });
|
||||
expect(effortButton()).toHaveTextContent("minimal");
|
||||
fireEvent.click(effortButton());
|
||||
fireEvent.click(screen.getByRole("option", { name: "medium" }));
|
||||
await chooseModel("big");
|
||||
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("bighigh");
|
||||
expect(effortButton()).toHaveTextContent("high");
|
||||
await chooseModel("small");
|
||||
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("smallmedium");
|
||||
expect(effortButton()).toHaveTextContent("medium");
|
||||
fireEvent.click(screen.getByRole("button", { name: "Start" }));
|
||||
await waitFor(() => expect(backend.create).toHaveBeenCalled());
|
||||
expect(backend.create.mock.calls[0]![0].config).toEqual([
|
||||
@@ -125,9 +124,11 @@ it("uses GitHub Copilot's own defaults and preserves per-model context tier and
|
||||
};
|
||||
useAgents.setState({ providers: [copilot], draft: savedDraft({ provider: "copilot", config: {} }) });
|
||||
render(<HomeEditor />);
|
||||
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("gemini-4-carbonmedium · default");
|
||||
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("gemini-4-carbondefault");
|
||||
expect(effortButton()).toHaveTextContent("medium");
|
||||
await chooseModel("gpt-5.6-sol");
|
||||
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("gpt-5.6-solmedium · default");
|
||||
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("gpt-5.6-soldefault");
|
||||
expect(effortButton()).toHaveTextContent("medium");
|
||||
fireEvent.click(screen.getByRole("button", { name: "Start" }));
|
||||
await waitFor(() => expect(backend.create).toHaveBeenCalled());
|
||||
expect(backend.create.mock.calls[0]![0].config).toEqual([
|
||||
@@ -161,7 +162,7 @@ it("ignores old provider-wide effort choices and refreshes unsupported per-model
|
||||
draft: savedDraft({ provider: "fake", config: { effort: "low" }, thoughtLevels: { big: { effort: "removed" } } }),
|
||||
});
|
||||
render(<HomeEditor />);
|
||||
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("bighigh");
|
||||
expect(effortButton()).toHaveTextContent("high");
|
||||
fireEvent.click(screen.getByRole("button", { name: "Start" }));
|
||||
await waitFor(() => expect(backend.create).toHaveBeenCalled());
|
||||
expect(backend.create.mock.calls[0]![0].config).toContainEqual({ id: "effort", value: "high" });
|
||||
@@ -208,10 +209,10 @@ it("refreshes the displayed agent version after a CLI upgrade when the window re
|
||||
return ok({ provider, name: "omp", version: cached, protocol: "ACP v1", error: null });
|
||||
});
|
||||
render(<HomeEditor />);
|
||||
await screen.findByText("omp · 18.20.0 · ACP v1");
|
||||
await waitFor(() => expect(agentTooltip()).toMatch(/ 18\.20\.0$/));
|
||||
installed = "18.20.2";
|
||||
fireEvent(window, new Event("focus"));
|
||||
await screen.findByText("omp · 18.20.2 · ACP v1");
|
||||
await waitFor(() => expect(agentTooltip()).toMatch(/ 18\.20\.2$/));
|
||||
});
|
||||
|
||||
it("does not reuse a previous page's cached agent version when opened again", async () => {
|
||||
@@ -219,5 +220,10 @@ it("does not reuse a previous page's cached agent version when opened again", as
|
||||
ok({ provider, name: "omp", version: refresh ? "18.20.2" : "18.20.0", protocol: "ACP v1", error: null }),
|
||||
);
|
||||
render(<HomeEditor />);
|
||||
await screen.findByText("omp · 18.20.2 · ACP v1");
|
||||
await waitFor(() => expect(agentTooltip()).toMatch(/ 18\.20\.2$/));
|
||||
});
|
||||
|
||||
/** The agent picker shows its icon; the name and version are in its tooltip. */
|
||||
function agentTooltip() {
|
||||
return screen.getByRole("button", { name: "Agent" }).parentElement?.getAttribute("data-tooltip");
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
/** New Task page: one prompt box with the agent and its settings; where it works under it. */
|
||||
/** New Task page: one prompt box with the agent and its settings; where it works in a quiet line under it. */
|
||||
import clsx from "clsx";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import type { AgentProbe, Branch } from "@/bindings";
|
||||
@@ -6,7 +6,7 @@ import { executeAction } from "@/platform/actions";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { useTx, useTxTemplate } from "@/platform/i18n";
|
||||
import { basename, useProject } from "@/platform/project";
|
||||
import { Chip, Select, T, type SelectOption } from "@/ui";
|
||||
import { Icon, Select, T, tooltipAttrs, type SelectOption } from "@/ui";
|
||||
import { defaultTaskProject } from "./project";
|
||||
import { maybeEditorService, useEditorShown, type EditorInput } from "@/workbench/contributions";
|
||||
import { Composer } from "./Composer";
|
||||
@@ -122,6 +122,10 @@ export function HomeEditor({ docked = false, input }: { docked?: boolean; input?
|
||||
!starting &&
|
||||
(!project?.workspace || repoState?.root === root);
|
||||
|
||||
const openMcp = () => setMcpOpenRequest((n) => n + 1);
|
||||
// The agent shows as its icon; its name and version are in the tooltip.
|
||||
const agentTitle = [provider?.name ?? tx("Agent"), probe?.version].filter(Boolean).join(" ");
|
||||
|
||||
const start = () => {
|
||||
if (!canStart) return;
|
||||
setStarting(true);
|
||||
@@ -137,93 +141,25 @@ export function HomeEditor({ docked = false, input }: { docked?: boolean; input?
|
||||
className={clsx(styles.home, docked && styles.docked, fitWindowWidth && styles.fitWidth)}
|
||||
style={zoomStyle}
|
||||
>
|
||||
{/* In the tool window the box sits at the bottom, under the question centred in the space above. */}
|
||||
{docked && (
|
||||
<div className={styles.dockedIntro}>
|
||||
<h1 className={styles.heading}>
|
||||
<T>What should the agent do?</T>
|
||||
</h1>
|
||||
</div>
|
||||
)}
|
||||
<div className={styles.inner}>
|
||||
{!docked && (
|
||||
<h1 className={styles.heading}>
|
||||
<T>What should the agent do?</T>
|
||||
</h1>
|
||||
)}
|
||||
{/* Above the box, like the running session's state line. */}
|
||||
<div className={styles.where}>
|
||||
{members.length > 1 ? (
|
||||
<Select
|
||||
variant="chip"
|
||||
aria-label={tx("Project")}
|
||||
className={styles.projectPicker}
|
||||
value={root}
|
||||
options={members.map((path) => ({
|
||||
value: path,
|
||||
label: basename(path),
|
||||
detail: path,
|
||||
icon: "folder",
|
||||
}))}
|
||||
onChange={(path) => {
|
||||
setSelected(path);
|
||||
updateDraft({ base: null });
|
||||
}}
|
||||
/>
|
||||
) : projectLabel ? (
|
||||
<Chip icon="folder" title={root} className={styles.projectChip}>
|
||||
{projectLabel}
|
||||
</Chip>
|
||||
) : null}
|
||||
{isGit && (
|
||||
<Select
|
||||
variant="chip"
|
||||
aria-label="Isolation"
|
||||
className={styles.isolation}
|
||||
value={isolation}
|
||||
options={[
|
||||
{ value: "worktree", label: tx("New worktree"), icon: "branch", detail: tx("away from your changes") },
|
||||
{
|
||||
value: "local",
|
||||
label: tx("Local checkout"),
|
||||
icon: "folder",
|
||||
detail: tx("edits your files directly"),
|
||||
},
|
||||
]}
|
||||
onChange={(isolation) => updateDraft({ isolation, isolationChosen: true })}
|
||||
/>
|
||||
)}
|
||||
{/* A folder that isn't a repository has no branch: the one Git found below it isn't where the agent runs. */}
|
||||
{isolation === "local" && isGit && current && (
|
||||
<>
|
||||
{!docked && (
|
||||
<span className={styles.note}>
|
||||
<T>on</T>
|
||||
</span>
|
||||
)}
|
||||
<Chip icon="branch" title={current} className={styles.branch}>
|
||||
{current}
|
||||
</Chip>
|
||||
</>
|
||||
)}
|
||||
{isolation === "worktree" && branches.length > 0 && (
|
||||
<>
|
||||
{!docked && (
|
||||
<span className={styles.note}>
|
||||
<T>from</T>
|
||||
</span>
|
||||
)}
|
||||
<Select
|
||||
variant="chip"
|
||||
aria-label="Base branch"
|
||||
className={styles.basePicker}
|
||||
value={base}
|
||||
options={branches.map((b) => ({ value: b.name, label: b.name, icon: "branch" }))}
|
||||
onChange={(b) => updateDraft({ base: b === current ? null : b })}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<Composer
|
||||
id={HOME}
|
||||
className={docked ? undefined : styles.composer}
|
||||
autoFocus
|
||||
placeholder={
|
||||
docked
|
||||
? "Describe a task…"
|
||||
: "Describe a task for the agent. @ references a file or folder, / runs a command"
|
||||
}
|
||||
placeholder={docked ? "Describe a task…" : "Describe a task. @ for files, / for commands"}
|
||||
root={root}
|
||||
projectRoot={root}
|
||||
commands={agentCommands}
|
||||
@@ -231,19 +167,23 @@ export function HomeEditor({ docked = false, input }: { docked?: boolean; input?
|
||||
config={config}
|
||||
onConfig={setDraftOption}
|
||||
onSubmit={start}
|
||||
onOpenMcp={() => setMcpOpenRequest((n) => n + 1)}
|
||||
onOpenMcp={openMcp}
|
||||
disabled={!canStart}
|
||||
addMenu={provider ? [{ id: "mcp", label: "MCP Servers…", icon: "plugin", run: openMcp }] : undefined}
|
||||
toolbar={
|
||||
<>
|
||||
<Select
|
||||
variant="ghost"
|
||||
aria-label="Agent"
|
||||
value={provider?.id ?? null}
|
||||
options={providerOptions}
|
||||
onChange={(id) =>
|
||||
id === ADD_AGENT ? void executeAction("agents.addAgent") : updateDraft({ provider: id, config: {} })
|
||||
}
|
||||
/>
|
||||
<span className={styles.agentPicker} {...tooltipAttrs(agentTitle, undefined, true)}>
|
||||
<Select
|
||||
variant="ghost"
|
||||
aria-label="Agent"
|
||||
value={provider?.id ?? null}
|
||||
options={providerOptions}
|
||||
renderValue={(o) => (o?.icon ? <Icon name={o.icon} size={14} /> : <T>Agent</T>)}
|
||||
onChange={(id) =>
|
||||
id === ADD_AGENT ? void executeAction("agents.addAgent") : updateDraft({ provider: id, config: {} })
|
||||
}
|
||||
/>
|
||||
</span>
|
||||
<ConfigPickers
|
||||
key={provider?.id}
|
||||
config={config}
|
||||
@@ -265,6 +205,7 @@ export function HomeEditor({ docked = false, input }: { docked?: boolean; input?
|
||||
overrides={draft.mcpOverrides}
|
||||
onChange={setDraftMcpOverrides}
|
||||
openRequest={mcpOpenRequest}
|
||||
hideTrigger
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
@@ -278,6 +219,71 @@ export function HomeEditor({ docked = false, input }: { docked?: boolean; input?
|
||||
/>
|
||||
}
|
||||
/>
|
||||
{/* Under the box: where the agent works. Project and checkout on the left, the branch on the right. */}
|
||||
<div className={styles.where}>
|
||||
{members.length > 1 ? (
|
||||
<Select
|
||||
variant="ghost"
|
||||
aria-label={tx("Project")}
|
||||
className={styles.projectPicker}
|
||||
value={root}
|
||||
options={members.map((path) => ({
|
||||
value: path,
|
||||
label: basename(path),
|
||||
detail: path,
|
||||
icon: "folder",
|
||||
}))}
|
||||
onChange={(path) => {
|
||||
setSelected(path);
|
||||
updateDraft({ base: null });
|
||||
}}
|
||||
/>
|
||||
) : projectLabel ? (
|
||||
<span className={styles.project} title={root}>
|
||||
<Icon name="folder" size={14} />
|
||||
<span className={styles.label}>{projectLabel}</span>
|
||||
</span>
|
||||
) : null}
|
||||
{isGit && (
|
||||
<Select
|
||||
variant="ghost"
|
||||
aria-label="Isolation"
|
||||
value={isolation}
|
||||
options={[
|
||||
{
|
||||
value: "local",
|
||||
label: tx("Local checkout"),
|
||||
icon: "folder",
|
||||
detail: tx("edits your files directly"),
|
||||
},
|
||||
{
|
||||
value: "worktree",
|
||||
label: tx("New worktree"),
|
||||
icon: "branch",
|
||||
detail: tx("away from your changes"),
|
||||
},
|
||||
]}
|
||||
renderValue={(o) => (o?.value === "worktree" ? tx("Worktree") : tx("Local"))}
|
||||
onChange={(isolation) => updateDraft({ isolation, isolationChosen: true })}
|
||||
/>
|
||||
)}
|
||||
{/* A folder that isn't a repository has no branch: the one Git found below it isn't where the agent runs. */}
|
||||
{isolation === "local" && isGit && current && (
|
||||
<span className={styles.project} title={current}>
|
||||
<Icon name="branch" size={14} />
|
||||
<span className={styles.label}>{current}</span>
|
||||
</span>
|
||||
)}
|
||||
{isolation === "worktree" && branches.length > 0 && (
|
||||
<Select
|
||||
variant="ghost"
|
||||
aria-label="Base branch"
|
||||
value={base}
|
||||
options={branches.map((b) => ({ value: b.name, label: b.name, icon: "branch" }))}
|
||||
onChange={(b) => updateDraft({ base: b === current ? null : b })}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
{/* Notes under the box don't take part in centring, so the box stays put as they come and go. */}
|
||||
<div className={styles.notes}>
|
||||
{effortAnnouncement && (
|
||||
@@ -290,11 +296,9 @@ export function HomeEditor({ docked = false, input }: { docked?: boolean; input?
|
||||
<T>Choose another model before starting.</T>
|
||||
</p>
|
||||
)}
|
||||
{probe && (!docked || probe.error) && (
|
||||
<p className={probe.error ? styles.warning : styles.note}>
|
||||
{probe.error
|
||||
? txTemplate(`${provider?.name ?? probe.provider} didn't start: ${probe.error}`)
|
||||
: [probe.name, probe.version, probe.protocol].filter(Boolean).join(" · ")}
|
||||
{probe?.error && (
|
||||
<p className={styles.warning}>
|
||||
{txTemplate(`${provider?.name ?? probe.provider} didn't start: ${probe.error}`)}
|
||||
</p>
|
||||
)}
|
||||
{(error || (provider && !provider.installed)) && (
|
||||
|
||||
@@ -211,3 +211,12 @@
|
||||
color: var(--fg-muted);
|
||||
font-size: var(--fs-tiny);
|
||||
}
|
||||
|
||||
/* The composer is the nearest positioned box: its bottom-right corner. */
|
||||
.hiddenAnchor {
|
||||
position: absolute;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
width: 0;
|
||||
height: 0;
|
||||
}
|
||||
@@ -34,6 +34,8 @@ export interface McpPickerProps {
|
||||
busy?: boolean;
|
||||
/** Bumped when `/mcp` is invoked from the composer to open this popover. */
|
||||
openRequest?: number;
|
||||
/** No button of its own: opened only through `openRequest`, above the composer. */
|
||||
hideTrigger?: boolean;
|
||||
/** Optional overrides for unit tests. */
|
||||
backend?: McpBackend;
|
||||
testData?: {
|
||||
@@ -50,6 +52,7 @@ export function McpPicker({
|
||||
disabled = false,
|
||||
busy = false,
|
||||
openRequest = 0,
|
||||
hideTrigger = false,
|
||||
backend = defaultMcpBackend,
|
||||
testData,
|
||||
}: McpPickerProps) {
|
||||
@@ -67,7 +70,10 @@ export function McpPicker({
|
||||
const [seenOpenRequest, setSeenOpenRequest] = useState(openRequest);
|
||||
const [query, setQuery] = useState("");
|
||||
const [importingKey, setImportingKey] = useState<string | null>(null);
|
||||
const anchor = useRef<HTMLButtonElement>(null);
|
||||
const anchor = useRef<HTMLElement | null>(null);
|
||||
const setAnchor = (el: HTMLElement | null) => {
|
||||
anchor.current = el;
|
||||
};
|
||||
|
||||
if (openRequest !== seenOpenRequest) {
|
||||
setSeenOpenRequest(openRequest);
|
||||
@@ -134,38 +140,43 @@ export function McpPicker({
|
||||
|
||||
return (
|
||||
<>
|
||||
<button
|
||||
ref={anchor}
|
||||
type="button"
|
||||
disabled={disabled}
|
||||
className={styles.trigger}
|
||||
title={
|
||||
resolved.overrideCount > 0
|
||||
? formatMessage(tx("MCP servers ({active}/{total} active · {overrides} session overrides)"), {
|
||||
active: resolved.activeCount,
|
||||
total: resolved.totalCount,
|
||||
overrides: resolved.overrideCount,
|
||||
})
|
||||
: formatMessage(tx("MCP servers ({active}/{total} active)"), {
|
||||
active: resolved.activeCount,
|
||||
total: resolved.totalCount,
|
||||
})
|
||||
}
|
||||
aria-label={tx("MCP servers")}
|
||||
aria-haspopup="dialog"
|
||||
aria-expanded={open}
|
||||
onClick={toggleOpen}
|
||||
>
|
||||
<Icon name="plugin" size={13} />
|
||||
<span className={styles.triggerLabel}>MCP</span>
|
||||
<span className={styles.triggerCount}>{countLabel}</span>
|
||||
{resolved.overrideCount > 0 && <span className={styles.overrideDot} aria-hidden />}
|
||||
</button>
|
||||
{hideTrigger ? (
|
||||
// Pinned to the composer's bottom-right corner: the popover opens under the box, like its other pickers.
|
||||
<span ref={setAnchor} className={styles.hiddenAnchor} aria-hidden />
|
||||
) : (
|
||||
<button
|
||||
ref={setAnchor}
|
||||
type="button"
|
||||
disabled={disabled}
|
||||
className={styles.trigger}
|
||||
title={
|
||||
resolved.overrideCount > 0
|
||||
? formatMessage(tx("MCP servers ({active}/{total} active · {overrides} session overrides)"), {
|
||||
active: resolved.activeCount,
|
||||
total: resolved.totalCount,
|
||||
overrides: resolved.overrideCount,
|
||||
})
|
||||
: formatMessage(tx("MCP servers ({active}/{total} active)"), {
|
||||
active: resolved.activeCount,
|
||||
total: resolved.totalCount,
|
||||
})
|
||||
}
|
||||
aria-label={tx("MCP servers")}
|
||||
aria-haspopup="dialog"
|
||||
aria-expanded={open}
|
||||
onClick={toggleOpen}
|
||||
>
|
||||
<Icon name="plugin" size={13} />
|
||||
<span className={styles.triggerLabel}>MCP</span>
|
||||
<span className={styles.triggerCount}>{countLabel}</span>
|
||||
{resolved.overrideCount > 0 && <span className={styles.overrideDot} aria-hidden />}
|
||||
</button>
|
||||
)}
|
||||
|
||||
<Popup
|
||||
open={open}
|
||||
anchor={anchor}
|
||||
placement="top-start"
|
||||
placement={hideTrigger ? "bottom-end" : "top-start"}
|
||||
offset={6}
|
||||
onClose={() => {
|
||||
setOpen(false);
|
||||
|
||||
@@ -83,55 +83,38 @@
|
||||
max-width: none;
|
||||
}
|
||||
|
||||
.providerIcon {
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
|
||||
/* The task's state and its terminal and changes, just above the composer. */
|
||||
/* Under the composer: where the task works on the left; changes, meters and terminal on the right. */
|
||||
.statusBar {
|
||||
display: flex;
|
||||
/* What doesn't fit moves to the next line whole, instead of every fact shrinking to a letter. */
|
||||
flex-wrap: wrap;
|
||||
/* The changes chip sits above the line; the facts stay on that line's baseline. */
|
||||
align-items: flex-end;
|
||||
gap: var(--space-0-5) var(--space-1-5);
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
min-width: 0;
|
||||
padding: 0 2px;
|
||||
height: 24px;
|
||||
padding: 0 6px;
|
||||
overflow: hidden;
|
||||
color: var(--fg-subtle);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
/* The facts on the bar's line are as tall as its chips, so their text shares one centre line. */
|
||||
.agent {
|
||||
display: inline-flex;
|
||||
flex: 0 1 auto;
|
||||
max-width: 100%;
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
height: 22px;
|
||||
min-width: 0;
|
||||
color: var(--fg-secondary);
|
||||
}
|
||||
.agentName {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
/* Where the task works, as the new-task composer shows it. */
|
||||
.where {
|
||||
display: inline-flex;
|
||||
flex: 0 1 auto;
|
||||
max-width: 100%;
|
||||
align-items: center;
|
||||
/* The chips' own padding spaces them. */
|
||||
gap: var(--space-0-5);
|
||||
gap: var(--space-2);
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
.note {
|
||||
flex: none;
|
||||
color: var(--fg-subtle);
|
||||
.fact {
|
||||
display: inline-flex;
|
||||
flex: 0 1 auto;
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
min-width: 0;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.factText {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.state {
|
||||
display: inline-flex;
|
||||
@@ -145,16 +128,15 @@
|
||||
.statusEnd {
|
||||
display: inline-flex;
|
||||
flex: 1 1 auto;
|
||||
flex-wrap: wrap;
|
||||
justify-content: flex-end;
|
||||
align-items: center;
|
||||
gap: var(--space-0-5) var(--space-2);
|
||||
gap: var(--space-2);
|
||||
min-width: 0;
|
||||
}
|
||||
/* Shrinks before the terminal buttons do: in a narrow docked session the meters clip, not the controls. */
|
||||
.statusMeters {
|
||||
display: inline-flex;
|
||||
flex: 0 1 auto;
|
||||
margin-left: auto;
|
||||
align-items: center;
|
||||
height: 22px;
|
||||
gap: var(--space-2);
|
||||
@@ -177,16 +159,18 @@
|
||||
min-width: 0;
|
||||
}
|
||||
.statusChip {
|
||||
composes: surface from "../../ui/Chip.module.css";
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
height: 22px;
|
||||
max-width: 100%;
|
||||
min-width: 0;
|
||||
padding: 0 8px;
|
||||
padding: 0 6px;
|
||||
overflow: hidden;
|
||||
border: none;
|
||||
color: var(--fg-secondary);
|
||||
border-radius: var(--radius-control);
|
||||
background: transparent;
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
font-size: var(--fs-small);
|
||||
font-variant-numeric: tabular-nums;
|
||||
@@ -397,12 +381,10 @@
|
||||
--session-card-width: 96%;
|
||||
}
|
||||
}
|
||||
/* A narrow docked session: rather than cut every fact to a letter or two, the bar keeps the
|
||||
agent's icon and its state; where it works is in the task's tooltip and Changes. */
|
||||
/* A narrow docked session: where it works gives way first, the changes and meters stay readable. */
|
||||
@container (max-width: 420px) {
|
||||
.where,
|
||||
.agentName {
|
||||
display: none;
|
||||
.where {
|
||||
flex-shrink: 2;
|
||||
}
|
||||
.processBody,
|
||||
.turnBody {
|
||||
|
||||
@@ -38,7 +38,6 @@ import { confirm } from "@/workbench/messages";
|
||||
import {
|
||||
Button,
|
||||
Checkbox,
|
||||
Chip,
|
||||
EmptyState,
|
||||
Icon,
|
||||
IconButton,
|
||||
@@ -417,41 +416,34 @@ function SessionStatus({
|
||||
showContextMenu(e, taskMenu([task]));
|
||||
}}
|
||||
>
|
||||
<span className={styles.agent} title={`${providerName(task.provider)} · ${task.cwd}`}>
|
||||
<Icon name={providerIcon(task.provider)} size={13} className={styles.providerIcon} />
|
||||
<span className={styles.agentName}>
|
||||
{providerName(task.provider)}
|
||||
{/* The composer's model picker shows the model when the agent offers one. */}
|
||||
{task.model && !pickedModel ? ` · ${task.model}` : ""}
|
||||
</span>
|
||||
</span>
|
||||
{/* The same three facts as the new-task composer: project, checkout, branch. */}
|
||||
<span className={styles.where}>
|
||||
{projectName && (
|
||||
<Chip icon="folder" title={projectRoot ?? undefined}>
|
||||
{projectName}
|
||||
</Chip>
|
||||
{/* Where the task works, in one quiet line like the new-task page: project (in a workspace), branch, worktree. */}
|
||||
<span className={styles.where} title={task.cwd}>
|
||||
{project?.workspace && projectName && (
|
||||
<span className={styles.fact}>
|
||||
<Icon name="folder" size={13} />
|
||||
<span className={styles.factText}>{projectName}</span>
|
||||
</span>
|
||||
)}
|
||||
<Chip icon={local ? "folder" : "branch"}>
|
||||
<T>{local ? "Local checkout" : "New worktree"}</T>
|
||||
</Chip>
|
||||
{branch && (
|
||||
<>
|
||||
{local && (
|
||||
<span className={styles.note}>
|
||||
<T>on</T>
|
||||
</span>
|
||||
)}
|
||||
<Chip icon="branch" title={branch}>
|
||||
{branch}
|
||||
</Chip>
|
||||
</>
|
||||
<span className={styles.fact}>
|
||||
<Icon name="branch" size={13} />
|
||||
<span className={styles.factText}>{branch}</span>
|
||||
</span>
|
||||
)}
|
||||
{!local && (
|
||||
<span className={styles.fact}>
|
||||
<T>Worktree</T>
|
||||
</span>
|
||||
)}
|
||||
{task.model && !pickedModel && <span className={styles.fact}>{task.model}</span>}
|
||||
</span>
|
||||
<span className={styles.state}>
|
||||
<T>{statusLabel(task.status)}</T>
|
||||
{task.status === "limited" && task.resetsMs != null && ` · ${tx`resets ${formatSentAt(task.resetsMs)}`}`}
|
||||
</span>
|
||||
{/* Ready is the usual state: only the others are worth a word. */}
|
||||
{task.status !== "ready" && (
|
||||
<span className={styles.state}>
|
||||
<T>{statusLabel(task.status)}</T>
|
||||
{task.status === "limited" && task.resetsMs != null && ` · ${tx`resets ${formatSentAt(task.resetsMs)}`}`}
|
||||
</span>
|
||||
)}
|
||||
<span className={styles.state} role="status" aria-live="polite" aria-atomic="true">
|
||||
{effortAnnouncement ? tx("Effort: {level}").replace("{level}", effortAnnouncement) : ""}
|
||||
</span>
|
||||
@@ -539,7 +531,7 @@ function Usage({ usage }: { usage: AgentUsage }) {
|
||||
<span className={styles.usageBar} aria-hidden>
|
||||
<span style={{ width: `${label.percent}%` }} />
|
||||
</span>
|
||||
{label.short}
|
||||
{`${label.percent}%`}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -2906,20 +2898,11 @@ function SessionComposer({
|
||||
body: String(e),
|
||||
}),
|
||||
);
|
||||
const openMcp = () => setMcpOpenRequest((n) => n + 1);
|
||||
const shown = useEditorShown();
|
||||
const effortAnnouncement = useEffortFocus(focusRoot, shown && task.status !== "archived", task.config, setOption);
|
||||
return (
|
||||
<div className={styles.composerArea}>
|
||||
<SessionStatus
|
||||
task={task}
|
||||
entries={entries}
|
||||
head={head}
|
||||
changes={changes}
|
||||
commits={commits}
|
||||
changesOpen={changesOpen}
|
||||
onToggleChanges={onToggleChanges}
|
||||
effortAnnouncement={effortAnnouncement}
|
||||
/>
|
||||
{task.status === "archived" && (
|
||||
<div className={styles.banner}>
|
||||
<span className={styles.bannerText}>
|
||||
@@ -2958,8 +2941,11 @@ function SessionComposer({
|
||||
config={task.config}
|
||||
onConfig={setOption}
|
||||
onSubmit={send}
|
||||
onOpenMcp={() => setMcpOpenRequest((n) => n + 1)}
|
||||
onOpenMcp={openMcp}
|
||||
disabled={task.status === "archived"}
|
||||
addMenu={[
|
||||
{ id: "mcp", label: "MCP Servers…", icon: "plugin", disabled: task.status === "archived", run: openMcp },
|
||||
]}
|
||||
toolbar={
|
||||
<>
|
||||
<ConfigPickers config={task.config} onChange={setOption} />
|
||||
@@ -2969,6 +2955,7 @@ function SessionComposer({
|
||||
disabled={task.status === "archived"}
|
||||
busy={busy}
|
||||
openRequest={mcpOpenRequest}
|
||||
hideTrigger
|
||||
onChange={(next) =>
|
||||
void setTaskMcpOverrides(task.id, next).catch((e: unknown) =>
|
||||
notifications().notify({
|
||||
@@ -2994,6 +2981,16 @@ function SessionComposer({
|
||||
</>
|
||||
}
|
||||
/>
|
||||
<SessionStatus
|
||||
task={task}
|
||||
entries={entries}
|
||||
head={head}
|
||||
changes={changes}
|
||||
commits={commits}
|
||||
changesOpen={changesOpen}
|
||||
onToggleChanges={onToggleChanges}
|
||||
effortAnnouncement={effortAnnouncement}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -318,7 +318,7 @@ describe("Composer editing", () => {
|
||||
});
|
||||
|
||||
describe("Composer current file", () => {
|
||||
it("offers the focused editor's file until the draft references it", () => {
|
||||
it("offers the focused editor's file, and adds it with the selection to requests when chosen", () => {
|
||||
const view = {} as TextEditorHandle["view"];
|
||||
act(() => setIdeContext(false));
|
||||
act(() =>
|
||||
@@ -329,10 +329,10 @@ describe("Composer current file", () => {
|
||||
const offer = screen.getByRole("button", { name: /main\.ts/ });
|
||||
expect(offer).toHaveTextContent("Current File");
|
||||
fireEvent.click(offer);
|
||||
expect(composerDraft(ID).text).toBe("@src/main.ts ");
|
||||
expect(toPrompt(composerDraft(ID)).files).toEqual(["/p/src/main.ts"]);
|
||||
expect(useAgents.getState().ideContext).toBe(true);
|
||||
expect(composerDraft(ID).text).toBe("");
|
||||
expect(screen.queryByRole("button", { name: /main\.ts/ })).toBeNull();
|
||||
expect(document.querySelector("[data-ref-path]")).toHaveAttribute("data-ref-path", "/p/src/main.ts");
|
||||
expect(screen.getByTitle("src/main.ts is added to your request")).toHaveTextContent("Current File");
|
||||
} finally {
|
||||
act(() => useEditorRegistry.setState({ active: null }));
|
||||
}
|
||||
@@ -348,8 +348,6 @@ describe("Composer IDE context", () => {
|
||||
);
|
||||
try {
|
||||
renderComposer();
|
||||
const toggle = screen.getByRole("button", { name: /IDE Context Enabled/ });
|
||||
expect(toggle).toHaveAttribute("aria-pressed", "true");
|
||||
expect(screen.queryByRole("button", { name: /main\.ts/ })).toBeNull();
|
||||
expect(screen.getByTitle("src/main.ts is added to your request")).toHaveTextContent("Current File");
|
||||
|
||||
@@ -369,9 +367,9 @@ describe("Composer IDE context", () => {
|
||||
// A draft that already references the file is sent as written.
|
||||
expect(await send("see @src/main.ts:1")).toEqual({ text: "see @src/main.ts:1", files: [], images: [] });
|
||||
|
||||
fireEvent.click(toggle);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Don't Add the Current File" }));
|
||||
expect(useAgents.getState().ideContext).toBe(false);
|
||||
expect(screen.getByRole("button", { name: /IDE Context Disabled/ })).toHaveAttribute("aria-pressed", "false");
|
||||
expect(screen.getByRole("button", { name: /main\.ts/ })).toHaveTextContent("Current File");
|
||||
expect(await send("explain")).toEqual({ text: "explain", files: [], images: [] });
|
||||
} finally {
|
||||
act(() => useEditorRegistry.setState({ active: null }));
|
||||
|
||||
@@ -385,14 +385,6 @@ export const isContextOption = (id: string) => /^(context_tier|contextTier)$/.te
|
||||
export const isPerModelOption = (o: AgentConfigOption) =>
|
||||
o.category === "thought_level" || o.category === "context_tier" || isContextOption(o.id);
|
||||
|
||||
/** Formats a per-1M-token credit rate cleanly (`200`, `1000`, `0`, `12.5`). */
|
||||
export function formatCreditRate(rate: number | null | undefined): string {
|
||||
if (rate == null || !Number.isFinite(rate)) return "0";
|
||||
if (rate === 0) return "0";
|
||||
if (rate < 0.01) return rate.toExponential(2);
|
||||
return Number(rate.toFixed(4)).toString();
|
||||
}
|
||||
|
||||
const matchesCategory = (o: AgentConfigOption, category: string) =>
|
||||
o.category === category ||
|
||||
(category === "model_config" &&
|
||||
|
||||
@@ -152,6 +152,7 @@ it("keeps cached choices usable while refreshing and shares the completion/coold
|
||||
expect(screen.getByRole("button", { name: "Start" })).toBeEnabled();
|
||||
await waitFor(() => expect(useAgents.getState().modelRequests.size).toBe(0));
|
||||
emit(catalog("first", { retryAtMs: Date.now() + 30_000 }));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Model" }));
|
||||
expect(screen.getByRole("button", { name: /Refresh in \d+s/ })).toBeDisabled();
|
||||
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("small");
|
||||
fireEvent.click(screen.getByRole("button", { name: "Start" }));
|
||||
@@ -213,11 +214,12 @@ it("retains cached model and effort choices after a command failure and retries
|
||||
draft: savedDraft({ provider: "first", config: { model: "big" }, thoughtLevels: { big: { effort: "low" } } }),
|
||||
});
|
||||
render(<HomeEditor />);
|
||||
expect(screen.getByRole("button", { name: "Reasoning" })).toHaveTextContent("low");
|
||||
fireEvent.click(screen.getByRole("button", { name: "Model" }));
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent("connection lost");
|
||||
expect(screen.getByRole("button", { name: "Configure model" })).toHaveTextContent("biglow");
|
||||
fireEvent.click(screen.getByRole("option", { name: "small" }));
|
||||
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("small");
|
||||
fireEvent.click(screen.getByRole("button", { name: "Model" }));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Refresh models" }));
|
||||
await waitFor(() => expect(screen.queryByRole("alert")).not.toBeInTheDocument());
|
||||
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("small");
|
||||
@@ -238,11 +240,11 @@ it("preserves a valid remembered model and effort when discovery changes the def
|
||||
);
|
||||
render(<HomeEditor />);
|
||||
await waitFor(() => expect(useAgents.getState().modelRequests.size).toBe(0));
|
||||
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("biglow");
|
||||
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("big");
|
||||
expect(screen.getByRole("button", { name: "Reasoning" })).toHaveTextContent("low");
|
||||
fireEvent.click(screen.getByRole("button", { name: "Model" }));
|
||||
expect(screen.getByRole("option", { name: "new" })).toBeVisible();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Configure model" }));
|
||||
expect(screen.getByRole("radio", { name: "low" })).toHaveAttribute("aria-checked", "true");
|
||||
fireEvent.keyDown(document, { key: "Escape" });
|
||||
fireEvent.click(screen.getByRole("button", { name: "Start" }));
|
||||
await waitFor(() => expect(backend.create).toHaveBeenCalled());
|
||||
expect(backend.create.mock.calls[0]![0].config).toEqual([
|
||||
|
||||
@@ -53,6 +53,23 @@ it("shows a request as a command only when it carries one, whatever its title",
|
||||
});
|
||||
|
||||
describe("permission choices", () => {
|
||||
it("names Codex project trust explicitly instead of a generic Always Allow", () => {
|
||||
expect(
|
||||
permissionDetails({
|
||||
...entry,
|
||||
command: null,
|
||||
title: "Trust /project in Codex?",
|
||||
options: [{ id: "codex-trust-project", kind: "allow_always", name: "Trust Project in Codex" }],
|
||||
}),
|
||||
).toEqual({ title: "Trust Project in Codex", command: undefined, detail: "Trust /project in Codex?" });
|
||||
expect(
|
||||
permissionOption({ id: "codex-trust-project", kind: "allow_always", name: "Trust Project in Codex" }, false)
|
||||
.label,
|
||||
).toBe("Trust Project in Codex");
|
||||
expect(
|
||||
permissionOption({ id: "codex-keep-untrusted", kind: "reject_once", name: "Keep Untrusted" }, false).label,
|
||||
).toBe("Keep Untrusted");
|
||||
});
|
||||
it.each([
|
||||
["allow_once", "yes", "Allow Once", "primary"],
|
||||
["allow_always", "policy", "Always Allow", "secondary"],
|
||||
|
||||
@@ -7,6 +7,9 @@ export type PermissionEntry = Extract<AgentEntry, { type: "permission" }>;
|
||||
export const asksInCard = (entry: PermissionEntry) => !!entry.questions?.length || !!entry.form;
|
||||
|
||||
export function permissionDetails(entry: PermissionEntry, provider = "Codex") {
|
||||
if (entry.options.some((option) => option.id === "codex-trust-project")) {
|
||||
return { title: tx("Trust Project in Codex"), command: undefined, detail: entry.title };
|
||||
}
|
||||
// The backend names the command from the request's structured input; the title is the
|
||||
// agent's own words and never makes a request a command.
|
||||
const command = entry.command ?? undefined;
|
||||
@@ -21,7 +24,9 @@ export function permissionDetails(entry: PermissionEntry, provider = "Codex") {
|
||||
export function permissionOption(option: AgentPermissionOption, command: boolean) {
|
||||
const stop = option.id === "cancel" || /decline and stop/i.test(option.name);
|
||||
let label = option.name;
|
||||
if (stop) label = tx("Decline and Stop");
|
||||
if (option.id === "codex-trust-project") label = tx("Trust Project in Codex");
|
||||
else if (option.id === "codex-keep-untrusted") label = tx("Keep Untrusted");
|
||||
else if (stop) label = tx("Decline and Stop");
|
||||
else if (option.kind === "allow_always") {
|
||||
label = /for (this |the )?session/i.test(option.name) ? tx("Allow for This Session") : tx("Always Allow");
|
||||
} else if (option.kind === "reject_always") label = tx("Always Decline");
|
||||
|
||||
@@ -2016,7 +2016,9 @@ describe("meters in the task header", () => {
|
||||
render(<SessionEditor input={input("A")} />);
|
||||
await screen.findByText("Answer A");
|
||||
const usage = screen.getByLabelText(/^Context /);
|
||||
expect(usage).toHaveTextContent("24k/200k (12%)");
|
||||
// The bar and percent show; the counts are in its label and tooltip.
|
||||
expect(usage).toHaveTextContent("12%");
|
||||
expect(usage).toHaveAccessibleName(/24k\/200k \(12%\)/);
|
||||
expect(usage.querySelector(`.${styles.usageBar} span`)).toHaveStyle({
|
||||
width: "12%",
|
||||
});
|
||||
|
||||
@@ -281,3 +281,32 @@ it("confirmLeave asks about running processes before closing", async () => {
|
||||
expect(asked[0]?.title).toContain("app");
|
||||
expect(asked[0]?.body).toContain("app");
|
||||
});
|
||||
|
||||
it("counts untitled buffers only when leaving for Welcome, and stays when one isn't saved", async () => {
|
||||
const service = await import("@/workbench/contributions");
|
||||
const { confirmLeave } = await import("../closeGuard");
|
||||
let untitled = [7];
|
||||
const spy = vi.spyOn(service, "maybeEditorService").mockReturnValue({
|
||||
dirtyDocumentIds: () => [7],
|
||||
untitledDirtyDocumentIds: () => untitled,
|
||||
saveAll: vi.fn(async () => {}),
|
||||
} as never);
|
||||
try {
|
||||
// Another project in place keeps the buffer: nothing to ask.
|
||||
const kept = deps([]);
|
||||
await expect(confirmLeave(kept.d, "openidea", true)).resolves.toBe(true);
|
||||
expect(kept.asked).toHaveLength(0);
|
||||
// Close Project asks; Save with the Save As cancelled keeps the project open, quietly.
|
||||
const left = deps([{ button: "save", checked: false }]);
|
||||
await expect(confirmLeave(left.d, "openidea", false)).resolves.toBe(false);
|
||||
expect(left.asked[0]?.body).toContain("1");
|
||||
expect(left.d.saveAll).toHaveBeenCalled();
|
||||
// Saved: the project closes.
|
||||
untitled = [];
|
||||
const saved = deps([{ button: "save", checked: false }]);
|
||||
left.d.saveAll = vi.fn(async () => {});
|
||||
await expect(confirmLeave(saved.d, "openidea", false)).resolves.toBe(true);
|
||||
} finally {
|
||||
spy.mockRestore();
|
||||
}
|
||||
});
|
||||
@@ -115,6 +115,23 @@ describe("native window close", () => {
|
||||
expect(forget).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("stays open when an untitled buffer's Save As is cancelled", async () => {
|
||||
vi.mocked(ipc.commands.windowCloseContext).mockResolvedValue({ quitting: false, windows: 2 });
|
||||
vi.mocked(services.maybeEditorService).mockReturnValue({
|
||||
forgetSavedTabs: forget,
|
||||
keepSavedTabs: keep,
|
||||
dirtyDocumentIds: () => [],
|
||||
untitledDirtyDocumentIds: () => ["untitled:1"],
|
||||
cancelClose: vi.fn(),
|
||||
} as never);
|
||||
deps.prepareClose = async () => ({ dirty: 1, discard: vi.fn(), commit: vi.fn(), cancel: vi.fn() });
|
||||
deps.ask = async () => ({ button: "save", checked: false });
|
||||
const prevented = await close({});
|
||||
expect(deps.saveAll).toHaveBeenCalledOnce();
|
||||
expect(prevented).toHaveBeenCalledOnce();
|
||||
expect(ipc.commands.windowGroupCancelClose).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("restores saved tabs if returning to Welcome fails", async () => {
|
||||
vi.mocked(ipc.commands.closeProject).mockRejectedValue(new Error("close failed"));
|
||||
const prevented = await close({ closeTabsWithWindow: true });
|
||||
|
||||
@@ -148,6 +148,8 @@ describe("openProjectInWindow", () => {
|
||||
expect(wslResolve).toHaveBeenCalledWith(share);
|
||||
expect(connectRemote).toHaveBeenCalledWith(target, linuxPath);
|
||||
expect(openProject).not.toHaveBeenCalled();
|
||||
// The remote window doesn't keep untitled buffers, so the guard counts them.
|
||||
expect(confirmLeaveProject).toHaveBeenCalledWith(false);
|
||||
});
|
||||
|
||||
it("asks for a new window when this one already has a project", async () => {
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
* `general.closeWithoutWelcome` is on, in which case it closes. When
|
||||
* `general.closeTabsWithWindow` is on, that close drops the saved editor tabs.
|
||||
*/
|
||||
import { commands, isTauri, onIdeEvent, type Settings } from "@/platform/ipc";
|
||||
import { IpcError, commands, isCancelled, isTauri, onIdeEvent, type Settings } from "@/platform/ipc";
|
||||
import { t } from "@/platform/i18n";
|
||||
import { closeProject, provideLeaveProjectGuard, useProject } from "@/platform/project";
|
||||
import { workflowSettings } from "@/platform/workflowSettings";
|
||||
@@ -171,6 +171,7 @@ const defaultDeps: CloseDeps = {
|
||||
while ((await liveProcesses()).length > 0) await new Promise((r) => setTimeout(r, 100));
|
||||
},
|
||||
onSaveFailed: (e) =>
|
||||
!isCancelled(e) &&
|
||||
notifications().notify({
|
||||
level: "error",
|
||||
title: t("app.unsaved.saveFailed"),
|
||||
@@ -224,7 +225,7 @@ async function onCloseRequested(deps: CloseDeps): Promise<boolean> {
|
||||
const s = useProject.getState();
|
||||
// The last project or LightEdit window can return to Welcome. Otherwise it closes.
|
||||
if (returnsToWelcome(ctx.quitting, ctx.windows, !!(s.project || s.lightEdit), s.settings)) {
|
||||
if (await confirmLeave(deps)) {
|
||||
if (await confirmLeave(deps, undefined, false)) {
|
||||
forgot = forgetTabs();
|
||||
try {
|
||||
await closeProject();
|
||||
@@ -249,7 +250,7 @@ async function onCloseRequested(deps: CloseDeps): Promise<boolean> {
|
||||
dirty: dirtyCount(),
|
||||
project: s.project?.displayName || s.project?.name || null,
|
||||
},
|
||||
deps,
|
||||
savingUntitled(deps),
|
||||
);
|
||||
if (!ok) {
|
||||
await (ctx.quitting ? commands.appCancelQuit() : commands.windowGroupCancelClose());
|
||||
@@ -269,6 +270,18 @@ async function onCloseRequested(deps: CloseDeps): Promise<boolean> {
|
||||
}
|
||||
}
|
||||
|
||||
/** Save asks for each untitled buffer's path; one left unsaved (Save As cancelled) keeps the window open. */
|
||||
function savingUntitled(deps: CloseDeps): CloseDeps {
|
||||
return {
|
||||
...deps,
|
||||
saveAll: async () => {
|
||||
await deps.saveAll();
|
||||
if (maybeEditorService()?.untitledDirtyDocumentIds?.().length)
|
||||
throw new IpcError({ kind: "cancelled", message: "Untitled files were not saved" });
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Unsaved changes before this window opens another project in place or closes it. `project` names
|
||||
* the project in the prompt when this window doesn't hold it (a comparison window).
|
||||
@@ -276,16 +289,19 @@ async function onCloseRequested(deps: CloseDeps): Promise<boolean> {
|
||||
export async function confirmLeave(
|
||||
deps: CloseDeps = defaultDeps,
|
||||
project = (useProject.getState().project?.displayName || useProject.getState().project?.name) ?? null,
|
||||
keepUntitled = true,
|
||||
): Promise<boolean> {
|
||||
if (!(await closeDocumentWindows())) return false;
|
||||
const confirmTerminate = workflowSettings().run.confirmTerminate;
|
||||
// Untitled buffers follow the window across projects: they are neither
|
||||
// counted nor saved by this guard (the window keeps them open).
|
||||
const untitled = new Set(maybeEditorService()?.untitledDirtyDocumentIds?.() ?? []);
|
||||
// Untitled buffers follow the window into another project: they are neither counted nor
|
||||
// saved then (the window keeps them open). Closing to Welcome drops them, so they count.
|
||||
const untitled = new Set(keepUntitled ? (maybeEditorService()?.untitledDirtyDocumentIds?.() ?? []) : []);
|
||||
const saveDeps: CloseDeps =
|
||||
untitled.size > 0
|
||||
? { ...deps, saveAll: () => Promise.resolve(maybeEditorService()?.saveAll({ skipUntitled: true })) }
|
||||
: deps;
|
||||
: keepUntitled
|
||||
? deps
|
||||
: savingUntitled(deps);
|
||||
return decideClose(
|
||||
{
|
||||
quitting: false,
|
||||
@@ -331,7 +347,7 @@ export function installCloseGuard(deps: CloseDeps = defaultDeps): () => void {
|
||||
useProject.subscribe((s, prev) => {
|
||||
if (s.project?.root !== prev.project?.root || s.lightEdit !== prev.lightEdit) dirtyDocs.clear();
|
||||
}),
|
||||
provideLeaveProjectGuard(() => confirmLeave(deps)),
|
||||
provideLeaveProjectGuard((keepUntitled) => confirmLeave(deps, undefined, keepUntitled)),
|
||||
];
|
||||
let unlisten: (() => void) | undefined;
|
||||
let disposed = false;
|
||||
|
||||
@@ -55,10 +55,10 @@ function openFailed(path: string, e: unknown) {
|
||||
/** Opens project `path` in this window; true once it is this window's project. */
|
||||
async function openHere(path: string): Promise<boolean> {
|
||||
if (!isRemoteWindow() && useProject.getState().project?.root === path) return true;
|
||||
if (!(await confirmLeaveProject())) return false;
|
||||
// A folder of a WSL distro runs there, not as a network folder; the window then drops untitled buffers.
|
||||
const wsl = await commands.wslResolve(path).catch(() => null);
|
||||
if (!(await confirmLeaveProject(!wsl))) return false;
|
||||
try {
|
||||
// A folder of a WSL distro runs there, not as a network folder.
|
||||
const wsl = await commands.wslResolve(path).catch(() => null);
|
||||
if (wsl) await connectRemote(wsl.target, wsl.path);
|
||||
else await openProject(path);
|
||||
return true;
|
||||
|
||||
@@ -57,6 +57,7 @@ export function exportMenu(data: ExportData, source: string, format?: ExportForm
|
||||
export function ExtractorSelect({ value, onChange }: { value: ExportFormat; onChange: (f: ExportFormat) => void }) {
|
||||
return (
|
||||
<Select
|
||||
variant="ghost"
|
||||
aria-label="Data extractor"
|
||||
value={value}
|
||||
options={EXPORT_FORMATS.map((f) => ({ value: f.id, label: f.label }))}
|
||||
|
||||
@@ -47,7 +47,6 @@
|
||||
.headerName {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
font-weight: 600;
|
||||
}
|
||||
.headerIcon {
|
||||
flex: none;
|
||||
@@ -58,6 +57,7 @@
|
||||
margin-left: auto;
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
|
||||
.cellNumber {
|
||||
justify-content: flex-end;
|
||||
}
|
||||
@@ -1364,7 +1364,7 @@
|
||||
gap: var(--space-0-5);
|
||||
padding: 2px 4px;
|
||||
border: 1px solid var(--border-popup, var(--border));
|
||||
border-radius: var(--radius-small);
|
||||
border-radius: var(--radius-popup);
|
||||
background: var(--bg-popup, var(--bg-elev));
|
||||
color: var(--fg-secondary);
|
||||
font-size: var(--fs-small);
|
||||
|
||||
@@ -18,20 +18,7 @@ import clsx from "clsx";
|
||||
import { call, commands, type DbPlanNode, type DbQueryResult } from "@/platform/ipc";
|
||||
import { shortcutLabel } from "@/platform/keymap";
|
||||
import { setContext } from "@/platform/context";
|
||||
import {
|
||||
Button,
|
||||
EmptyState,
|
||||
Icon,
|
||||
IconButton,
|
||||
Select,
|
||||
Spinner,
|
||||
Tabs,
|
||||
Tree,
|
||||
showContextMenu,
|
||||
T,
|
||||
tooltipAttrs,
|
||||
Toolbar,
|
||||
} from "@/ui";
|
||||
import { EmptyState, Icon, IconButton, Select, Spinner, Tabs, Tree, showContextMenu, T, Toolbar } from "@/ui";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
import { ToolWindowContentTabs } from "@/workbench/toolwindows/ToolWindows";
|
||||
import { ChartView } from "./ChartView";
|
||||
@@ -65,7 +52,6 @@ import {
|
||||
pageable,
|
||||
pinResult,
|
||||
rerunResult,
|
||||
targetLabel,
|
||||
useDatabase,
|
||||
withConnection,
|
||||
type OutputLine,
|
||||
@@ -173,6 +159,25 @@ function Pager({ tab }: { tab: ResultTab }) {
|
||||
const { first, last } = w;
|
||||
const total = w.total === null ? `${w.last + 1}+` : String(w.total);
|
||||
const sizes = PAGE_SIZES.includes(pageSize) ? PAGE_SIZES : [...PAGE_SIZES, pageSize].sort((a, b) => a - b);
|
||||
const sizeSelect = (label?: string) => (
|
||||
<Select
|
||||
variant="ghost"
|
||||
aria-label="Page size"
|
||||
value={String(pageSize)}
|
||||
options={sizes.map((v) => ({ value: String(v), label: String(v) }))}
|
||||
renderValue={label ? () => label : undefined}
|
||||
onChange={(v) => go(0, Number(v))}
|
||||
disabled={!canPage}
|
||||
/>
|
||||
);
|
||||
// Everything fits on one page: only the row count, which still sets the page size.
|
||||
const count = w.total;
|
||||
if (!canPrevious && !canNext && count !== null)
|
||||
return (
|
||||
<Toolbar className={styles.resultPager} aria-label="Result pages" title={outcomeSummary(tab.outcome)}>
|
||||
{sizeSelect(tx`${count} rows`)}
|
||||
</Toolbar>
|
||||
);
|
||||
return (
|
||||
<Toolbar className={styles.resultPager} aria-label="Result pages" title={outcomeSummary(tab.outcome)}>
|
||||
<IconButton
|
||||
@@ -216,13 +221,7 @@ function Pager({ tab }: { tab: ResultTab }) {
|
||||
disabled={!canLast}
|
||||
onClick={() => void goLast()}
|
||||
/>
|
||||
<Select
|
||||
aria-label="Page size"
|
||||
value={String(pageSize)}
|
||||
options={sizes.map((v) => ({ value: String(v), label: String(v) }))}
|
||||
onChange={(v) => go(0, Number(v))}
|
||||
disabled={!canPage}
|
||||
/>
|
||||
{sizeSelect()}
|
||||
</Toolbar>
|
||||
);
|
||||
}
|
||||
@@ -536,30 +535,24 @@ export function Result({ tab, onClose }: { tab: ResultTab; onClose?: () => void
|
||||
disabled={busy}
|
||||
onClick={addRow}
|
||||
/>
|
||||
<Button
|
||||
size="small"
|
||||
variant="primary"
|
||||
disabled={!dirty || busy}
|
||||
onClick={() => void submit()}
|
||||
{...tooltipAttrs("Submit", shortcutLabel("db.submitChanges"))}
|
||||
>
|
||||
<T>Submit</T>
|
||||
</Button>
|
||||
<Button
|
||||
size="small"
|
||||
<IconButton
|
||||
icon="revert"
|
||||
title="Revert"
|
||||
shortcut={shortcutLabel("db.revertChanges")}
|
||||
disabled={!dirty || busy}
|
||||
onClick={() => setEdits(() => emptyEdits())}
|
||||
{...tooltipAttrs("Revert", shortcutLabel("db.revertChanges"))}
|
||||
>
|
||||
<T>Revert</T>
|
||||
</Button>
|
||||
/>
|
||||
<IconButton
|
||||
icon="arrow-up"
|
||||
title="Submit"
|
||||
shortcut={shortcutLabel("db.submitChanges")}
|
||||
disabled={!dirty || busy}
|
||||
onClick={() => void submit()}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
{tab.busy && <Spinner size={12} />}
|
||||
<span className={styles.spacer} />
|
||||
<span className={styles.resultSource} title={tab.outcome.statement.text}>
|
||||
{targetLabel(tab.sourceId)}
|
||||
</span>
|
||||
<ExtractorSelect value={extractor} onChange={setExtractor} />
|
||||
<IconButton
|
||||
icon="export"
|
||||
@@ -680,10 +673,6 @@ function PlanResult({ tab }: { tab: ResultTab }) {
|
||||
<IconButton icon="refresh" title="Explain Again" disabled={tab.busy} onClick={() => void rerunResult(tab.id)} />
|
||||
<PinButton tab={tab} />
|
||||
{tab.busy && <Spinner size={12} />}
|
||||
<span className={styles.spacer} />
|
||||
<span className={styles.resultSource} title={tab.outcome.statement.text}>
|
||||
{targetLabel(tab.sourceId)}
|
||||
</span>
|
||||
</Toolbar>
|
||||
<div className={clsx(styles.fill, styles.planView)}>
|
||||
<div className={styles.planTree}>
|
||||
|
||||
@@ -571,6 +571,7 @@ function ConsoleBar({ path, view }: { path: string; view: EditorView }) {
|
||||
/>
|
||||
<span className={styles.toolbarSeparator} />
|
||||
<Select
|
||||
variant="ghost"
|
||||
aria-label="Row limit"
|
||||
value={String(maxRows)}
|
||||
options={ROW_LIMITS.map((v) => ({ value: v, label: tx`${Number(v).toLocaleString("en")} rows` }))}
|
||||
@@ -580,6 +581,7 @@ function ConsoleBar({ path, view }: { path: string; view: EditorView }) {
|
||||
<>
|
||||
<span className={styles.toolbarSeparator} />
|
||||
<Select
|
||||
variant="ghost"
|
||||
aria-label="Transaction mode"
|
||||
value={manual ? "manual" : "auto"}
|
||||
options={[
|
||||
@@ -611,6 +613,7 @@ function ConsoleBar({ path, view }: { path: string; view: EditorView }) {
|
||||
{bound && sourceById(boundId)?.driver === "snowflake" && <SnowflakeSession target={bound} idle={!running} />}
|
||||
{switchable && (
|
||||
<Select
|
||||
variant="ghost"
|
||||
aria-label={sqlServer ? "Database" : "Schema"}
|
||||
value={schema || null}
|
||||
placeholder="<schema>"
|
||||
@@ -621,6 +624,7 @@ function ConsoleBar({ path, view }: { path: string; view: EditorView }) {
|
||||
/>
|
||||
)}
|
||||
<Select
|
||||
variant="ghost"
|
||||
aria-label="Data source"
|
||||
value={bound ?? null}
|
||||
placeholder={sources.length ? "<data source>" : "None configured"}
|
||||
@@ -674,6 +678,7 @@ function SnowflakeSession({ target, idle }: { target: string; idle: boolean }) {
|
||||
return (
|
||||
<>
|
||||
<Select
|
||||
variant="ghost"
|
||||
aria-label="Warehouse"
|
||||
value={state.warehouse || null}
|
||||
placeholder="<warehouse>"
|
||||
@@ -683,6 +688,7 @@ function SnowflakeSession({ target, idle }: { target: string; idle: boolean }) {
|
||||
disabled={!idle}
|
||||
/>
|
||||
<Select
|
||||
variant="ghost"
|
||||
aria-label="Role"
|
||||
value={state.role || null}
|
||||
placeholder="<role>"
|
||||
|
||||
@@ -7,7 +7,7 @@ import { RangeSet, StateEffect, StateField, type EditorState, type Extension } f
|
||||
import { EditorView, GutterMarker, ViewPlugin, gutter, showPanel, type Panel, type ViewUpdate } from "@codemirror/view";
|
||||
import { useEffect } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import type { EditorDocContext } from "@/editor/api";
|
||||
import { mapLineStart, type EditorDocContext } from "@/editor/api";
|
||||
import { shortcutLabel } from "@/platform/keymap";
|
||||
import { isVirtualUri } from "@/platform/virtualDocs";
|
||||
import type { HttpRequestBlock } from "@/platform/ipc";
|
||||
@@ -40,7 +40,7 @@ export const requestsField = StateField.define<Placed[]>({
|
||||
for (const e of tr.effects) if (e.is(setRequests)) return e.value;
|
||||
if (!tr.docChanged || !value.length) return value;
|
||||
return value.map((r) => {
|
||||
const pos = tr.state.doc.lineAt(tr.changes.mapPos(r.pos, -1)).from;
|
||||
const pos = mapLineStart(tr, r.pos);
|
||||
return { ...r, pos, line: tr.state.doc.lineAt(pos).number - 1 };
|
||||
});
|
||||
},
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { CompletionContext, CompletionResult } from "@codemirror/autocomplete";
|
||||
import { EditorState, RangeSet, StateEffect, StateField, type Extension } from "@codemirror/state";
|
||||
import { EditorView, GutterMarker, ViewPlugin } from "@codemirror/view";
|
||||
import { iconAreaSource, type EditorDocContext } from "@/editor/api";
|
||||
import { iconAreaSource, mapLineStart, type EditorDocContext } from "@/editor/api";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { useProject } from "@/platform/project";
|
||||
@@ -78,7 +78,9 @@ const marks = StateField.define<Mark[]>({
|
||||
create: () => [],
|
||||
update: (value, tr) => {
|
||||
for (const e of tr.effects) if (e.is(setMarks)) return e.value;
|
||||
return tr.docChanged ? [] : value;
|
||||
// Kept on their text until the refresh, so the icon area keeps its width while typing.
|
||||
if (!tr.docChanged || !value.length) return value;
|
||||
return value.map((m) => ({ ...m, pos: mapLineStart(tr, m.pos) }));
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
Loaded 100 of 153 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача