mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-22 09:39:27 -10:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e091561937 |
No files matched your search
@@ -194,14 +194,14 @@ impl AgentCatalogs {
|
||||
(shared.paths.models_file.clone(), shared.paths.project_root.clone(), provider.to_owned())
|
||||
}
|
||||
|
||||
/// The catalog saved for this project, for before this run looked anything up.
|
||||
fn saved(shared: &Shared, provider: &str) -> CatalogData {
|
||||
fn fallback(shared: &Shared, provider: &str) -> CatalogData {
|
||||
let cache = shared.known.lock();
|
||||
cache
|
||||
.get(provider)
|
||||
.and_then(|known| known.catalogs.get(&shared.root_key()))
|
||||
.map(|saved| saved.catalog.clone())
|
||||
.unwrap_or_default()
|
||||
let Some(known) = cache.get(provider) else { return CatalogData::default() };
|
||||
known.catalogs.get(&shared.root_key()).map(|saved| saved.catalog.clone()).unwrap_or_else(|| CatalogData {
|
||||
config: known.config.clone(),
|
||||
thought_levels: known.thought_levels.clone(),
|
||||
refreshed_at_ms: None,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn cached(&self, shared: &Shared, provider: &str) -> CatalogData {
|
||||
@@ -210,14 +210,32 @@ impl AgentCatalogs {
|
||||
.entries
|
||||
.get(&Self::key(shared, provider))
|
||||
.and_then(|e| e.catalog.clone())
|
||||
.unwrap_or_else(|| Self::saved(shared, provider))
|
||||
.unwrap_or_else(|| Self::fallback(shared, provider))
|
||||
}
|
||||
|
||||
/// The entry a chat may switch to: exactly what the picker offers from the cached catalog,
|
||||
/// however long ago it was read. Refreshing keeps that catalog current; a listed model is
|
||||
/// never refused because the catalog aged.
|
||||
pub(super) fn listed_model(&self, shared: &Shared, provider: &str, model: &str) -> Option<crate::AgentConfigValue> {
|
||||
self.cached(shared, provider).model_option()?.values.iter().find(|value| value.value == model).cloned()
|
||||
/// Availability for an explicit session switch must come from a recent discovery for this
|
||||
/// launch, not from the display fallback or a different project's session report.
|
||||
pub(super) fn fresh_model(
|
||||
&self,
|
||||
shared: &Shared,
|
||||
spec: &provider::ProviderSpec,
|
||||
model: &str,
|
||||
) -> Option<crate::AgentConfigValue> {
|
||||
let context = LaunchContext::new(spec.clone(), &shared.paths.project_root);
|
||||
let select = |catalog: &CatalogData| {
|
||||
let age = self.epoch_ms() - catalog.refreshed_at_ms?;
|
||||
if !(0.0..FRESH_FOR.as_millis() as f64).contains(&age) {
|
||||
return None;
|
||||
}
|
||||
catalog.model_option()?.values.iter().find(|value| value.value == model).cloned()
|
||||
};
|
||||
let state = self.state.lock();
|
||||
if let Some(entry) = state.entries.get(&Self::key(shared, &spec.id)) {
|
||||
return select(entry.catalog.as_ref().filter(|_| entry.context == context)?);
|
||||
}
|
||||
let cache = shared.known.lock();
|
||||
let saved = cache.get(&spec.id)?.catalogs.get(&shared.root_key())?;
|
||||
(saved.fingerprint == context.fingerprint()).then(|| select(&saved.catalog)).flatten()
|
||||
}
|
||||
|
||||
pub(crate) fn levels(&self, shared: &Shared, provider: &str, model: &str) -> Option<Vec<AgentConfigOption>> {
|
||||
@@ -228,7 +246,14 @@ impl AgentCatalogs {
|
||||
}
|
||||
drop(state);
|
||||
let cache = shared.known.lock();
|
||||
cache.get(provider)?.catalogs.get(&shared.root_key())?.catalog.thought_levels.get(model).cloned()
|
||||
let known = cache.get(provider)?;
|
||||
known
|
||||
.catalogs
|
||||
.get(&shared.root_key())
|
||||
.map(|saved| &saved.catalog.thought_levels)
|
||||
.unwrap_or(&known.thought_levels)
|
||||
.get(model)
|
||||
.cloned()
|
||||
}
|
||||
|
||||
pub(super) async fn load_levels(
|
||||
@@ -272,7 +297,7 @@ impl AgentCatalogs {
|
||||
}
|
||||
|
||||
fn snapshot(&self, shared: &Shared, provider: &str, entry: &Entry) -> AgentModelCatalog {
|
||||
let catalog = entry.catalog.clone().unwrap_or_default();
|
||||
let catalog = entry.catalog.clone().unwrap_or_else(|| Self::fallback(shared, provider));
|
||||
let model_failure = entry.requested_model.as_ref().and_then(|model| entry.model_failures.get(model));
|
||||
let unknown_model = entry
|
||||
.requested_model
|
||||
@@ -357,11 +382,12 @@ impl AgentCatalogs {
|
||||
},
|
||||
);
|
||||
}
|
||||
let fallback =
|
||||
state.entries.get(&key).filter(|entry| entry.catalog.is_none()).map(|_| Self::fallback(shared, &spec.id));
|
||||
state.generation += 1;
|
||||
let generation = state.generation;
|
||||
let entry = state.entries.get_mut(&key).expect("catalog entry");
|
||||
let empty = CatalogData::default();
|
||||
let catalog = entry.catalog.as_ref().unwrap_or(&empty);
|
||||
let catalog = entry.catalog.as_ref().or(fallback.as_ref()).expect("cached catalog");
|
||||
let fresh = entry.successful.is_some_and(|at| now.duration_since(at) < FRESH_FOR);
|
||||
let target = model
|
||||
.filter(|model| {
|
||||
@@ -470,7 +496,7 @@ impl AgentCatalogs {
|
||||
entry.flight_model = None;
|
||||
let success = match result {
|
||||
Ok(found) => {
|
||||
let previous = entry.catalog.take().unwrap_or_default();
|
||||
let previous = entry.catalog.take().unwrap_or_else(|| Self::fallback(shared, &key.2));
|
||||
let mut cache = shared.known.lock();
|
||||
let known = cache.entry(key.2.clone()).or_default();
|
||||
let mut catalog = CatalogData {
|
||||
@@ -484,9 +510,13 @@ impl AgentCatalogs {
|
||||
catalog.thought_levels.insert(model, levels);
|
||||
}
|
||||
}
|
||||
known.config = catalog.config.clone();
|
||||
known.thought_levels = catalog.thought_levels.clone();
|
||||
if let Some(commands) = found.commands {
|
||||
known.commands.insert(shared.root_key(), commands);
|
||||
}
|
||||
known.authoritative = true;
|
||||
known.refreshed_at_ms = catalog.refreshed_at_ms;
|
||||
known.catalogs.insert(
|
||||
shared.root_key(),
|
||||
SavedCatalog { fingerprint: entry.context.fingerprint(), catalog: catalog.clone() },
|
||||
|
||||
@@ -230,9 +230,11 @@ async fn successful_refresh_replaces_models_and_efforts_and_old_sessions_cannot_
|
||||
let manager = make_manager(tmp.path(), catalogs.clone(), &harness);
|
||||
let mut events = events(&manager);
|
||||
let old = config::options_of(&response(&["old", "retained"], &["low", "high"]));
|
||||
manager.shared.remember(PROVIDER, Some(&old), None, Some("old"));
|
||||
let cached = manager.refresh_models(PROVIDER, false, None).unwrap();
|
||||
assert!(cached.refreshing);
|
||||
assert!(model_values(&cached).is_empty(), "nothing is offered before the first discovery");
|
||||
assert_eq!(model_values(&cached), ["old", "retained"]);
|
||||
assert!(cached.refreshed_at_ms.is_none(), "session reports are not fresh discovery");
|
||||
let pending = harness.next().await;
|
||||
assert_eq!(pending.params["mcpServers"], json!([]));
|
||||
pending.reply.send(Ok(response(&["retained", "new"], &["medium"]))).unwrap();
|
||||
@@ -256,10 +258,7 @@ async fn successful_refresh_replaces_models_and_efforts_and_old_sessions_cannot_
|
||||
assert_eq!(provider.config, fresh.config);
|
||||
restored.shared.remember(PROVIDER, Some(&old), None, Some("old"));
|
||||
assert_eq!(restored.shared.known_config(PROVIDER), fresh.config);
|
||||
assert_eq!(
|
||||
restored.shared.paths.catalogs.cached(&restored.shared, PROVIDER).refreshed_at_ms,
|
||||
fresh.refreshed_at_ms
|
||||
);
|
||||
assert_eq!(restored.shared.known.lock()[PROVIDER].refreshed_at_ms, fresh.refreshed_at_ms);
|
||||
assert!(!tmp.path().join("store").exists(), "refresh never creates tasks");
|
||||
}
|
||||
|
||||
@@ -309,11 +308,6 @@ async fn discovered_model_reloads_the_same_session_on_the_next_message() {
|
||||
switch_chat_model(ChatSwitch::Resume).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn discovered_model_from_an_aged_catalog_can_still_be_selected() {
|
||||
switch_chat_model(ChatSwitch::Aged).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn discovered_model_leaves_the_original_session_intact_after_resume_failure() {
|
||||
switch_chat_model(ChatSwitch::ResumeFails).await;
|
||||
@@ -362,7 +356,6 @@ async fn discovered_model_lookup_does_not_overwrite_a_newer_selection() {
|
||||
#[derive(Clone, Copy)]
|
||||
enum ChatSwitch {
|
||||
Live,
|
||||
Aged,
|
||||
Resume,
|
||||
ResumeFails,
|
||||
Unavailable,
|
||||
@@ -383,8 +376,7 @@ async fn switch_chat_model(scenario: ChatSwitch) {
|
||||
let mut harness = Harness::with_initialize(json!({
|
||||
"protocolVersion": 1, "agentCapabilities": { "loadSession": true }
|
||||
}));
|
||||
let catalogs = Arc::new(AgentCatalogs::default());
|
||||
let mut manager = make_manager(tmp.path(), catalogs.clone(), &harness);
|
||||
let mut manager = make_manager(tmp.path(), Arc::default(), &harness);
|
||||
let task = manager
|
||||
.create(NewAgentTask {
|
||||
prompt: AgentPrompt { text: "first".into(), ..Default::default() },
|
||||
@@ -451,11 +443,7 @@ async fn switch_chat_model(scenario: ChatSwitch) {
|
||||
}
|
||||
assert_eq!(manager.task(&task.id).unwrap().state.lock().task.config, before_config);
|
||||
|
||||
let live = matches!(scenario, ChatSwitch::Live | ChatSwitch::Aged);
|
||||
if matches!(scenario, ChatSwitch::Aged) {
|
||||
// The catalog stays what the picker offers however long ago it was read.
|
||||
advance(&catalogs, 20 * 60);
|
||||
}
|
||||
let live = matches!(scenario, ChatSwitch::Live);
|
||||
let resumed_launch = if missing_settings { 3 } else { 2 };
|
||||
let load_fails = matches!(scenario, ChatSwitch::ResumeFails);
|
||||
let unavailable = matches!(scenario, ChatSwitch::Unavailable);
|
||||
@@ -696,7 +684,7 @@ async fn next_chat_request(
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_cache_from_before_project_catalogs_offers_nothing_until_discovery_succeeds() {
|
||||
async fn legacy_cache_loads_without_claiming_authoritative_freshness() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
configure(tmp.path(), "one");
|
||||
let options = config::options_of(&response(&["legacy"], &["low"]));
|
||||
@@ -712,11 +700,12 @@ async fn a_cache_from_before_project_catalogs_offers_nothing_until_discovery_suc
|
||||
let manager = make_manager(tmp.path(), Arc::default(), &harness);
|
||||
let mut events = events(&manager);
|
||||
let cached = manager.refresh_models(PROVIDER, false, None).unwrap();
|
||||
assert!(model_values(&cached).is_empty());
|
||||
assert_eq!(model_values(&cached), ["legacy"]);
|
||||
assert!(cached.refreshing && cached.refreshed_at_ms.is_none());
|
||||
harness.next().await.reply.send(Ok(response(&["current"], &["low"]))).unwrap();
|
||||
let found = completed(&mut events).await;
|
||||
assert_eq!(model_values(&found), ["current"]);
|
||||
harness.next().await.reply.send(Err("Sign in required".into())).unwrap();
|
||||
let failed = completed(&mut events).await;
|
||||
assert_eq!(failed.config, cached.config);
|
||||
assert!(failed.error.as_deref().unwrap().contains("Sign in required"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
+60
-193
@@ -23,7 +23,7 @@ mod provider;
|
||||
pub mod registry;
|
||||
pub mod security;
|
||||
mod shell;
|
||||
pub mod skills;
|
||||
mod skills;
|
||||
mod timeline;
|
||||
mod worktree;
|
||||
|
||||
@@ -131,19 +131,6 @@ pub type McpServersFn = dyn Fn() -> Vec<McpServer> + Send + Sync;
|
||||
/// Returns the executable of the running built-in MCP server, if any.
|
||||
pub type McpExecutableFn = dyn Fn() -> Option<PathBuf> + Send + Sync;
|
||||
|
||||
/// The `[agents.skills.<name>]` policies a session resolves against: the user's (global
|
||||
/// `settings.toml`), the workspace's (`.openidea/settings.toml`), and whether the workspace
|
||||
/// is trusted (an untrusted one can only turn skills off).
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct SkillsPolicy {
|
||||
pub user: BTreeMap<String, AgentSkillPolicy>,
|
||||
pub workspace: BTreeMap<String, AgentSkillPolicy>,
|
||||
pub workspace_trusted: bool,
|
||||
}
|
||||
|
||||
/// Returns the skill policies for this project.
|
||||
pub type SkillsPolicyFn = dyn Fn() -> SkillsPolicy + Send + Sync;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
struct CopilotBinaryKey {
|
||||
command: String,
|
||||
@@ -169,18 +156,27 @@ struct Shared {
|
||||
idle_release_ms: AtomicU64,
|
||||
mcp_servers_hook: RwLock<Option<Arc<McpServersFn>>>,
|
||||
mcp_executable_hook: RwLock<Option<Arc<McpExecutableFn>>>,
|
||||
skills_policy_hook: RwLock<Option<Arc<SkillsPolicyFn>>>,
|
||||
/// Monotonic id for [`AgentEvent::Attention`] episodes.
|
||||
attention_seq: AtomicU64,
|
||||
}
|
||||
|
||||
/// What an agent offered, for the New Task page.
|
||||
/// What an agent offered in its last session, for the New Task page.
|
||||
#[derive(Clone, Default, Serialize, Deserialize)]
|
||||
struct Known {
|
||||
#[serde(default)]
|
||||
config: Vec<AgentConfigOption>,
|
||||
/// Thinking levels reported for each model value, including its last choice.
|
||||
#[serde(default, rename = "thoughtLevels")]
|
||||
thought_levels: BTreeMap<String, Vec<AgentConfigOption>>,
|
||||
/// By project root: skills and custom commands differ per project.
|
||||
#[serde(default, rename = "projectCommands")]
|
||||
commands: HashMap<String, Vec<AgentCommand>>,
|
||||
/// Model catalogs by project root, valid for the launch context they were read with.
|
||||
/// Successful discovery, unlike a session report, owns availability.
|
||||
#[serde(default)]
|
||||
authoritative: bool,
|
||||
#[serde(default, rename = "refreshedAtMs")]
|
||||
refreshed_at_ms: Option<f64>,
|
||||
/// Authoritative availability and freshness are scoped to project and launch context.
|
||||
#[serde(default, rename = "projectCatalogs")]
|
||||
catalogs: HashMap<String, catalogs::SavedCatalog>,
|
||||
}
|
||||
@@ -298,8 +294,7 @@ impl Shared {
|
||||
self.paths.project_root.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
/// Keeps the commands a session offered and the effort levels it reported for `model`, the
|
||||
/// only model whose levels it describes.
|
||||
/// Cache levels only when `model` confirms which model the session reported them for.
|
||||
fn remember(
|
||||
&self,
|
||||
provider: &str,
|
||||
@@ -308,22 +303,43 @@ impl Shared {
|
||||
model: Option<&str>,
|
||||
) {
|
||||
let acp = self.spec(provider).is_some_and(|spec| spec.driver == provider::Driver::Acp);
|
||||
let mut cache = self.known.lock();
|
||||
let known = cache.entry(provider.to_owned()).or_default();
|
||||
let mut changed = false;
|
||||
if let Some(commands) = commands.filter(|c| !c.is_empty()) {
|
||||
let mut cache = self.known.lock();
|
||||
let known = cache.entry(provider.to_owned()).or_default();
|
||||
if known.commands.get(&self.root_key()).map(Vec::as_slice) != Some(commands) {
|
||||
known.commands.insert(self.root_key(), commands.to_vec());
|
||||
self.persist_known(&cache);
|
||||
// Running tasks retain their own reported settings. Once discovery has
|
||||
// succeeded, a session's older list/defaults cannot change New Task choices.
|
||||
if !known.authoritative
|
||||
&& let Some(config) = config.filter(|c| !c.is_empty())
|
||||
{
|
||||
if let Some(model) = model {
|
||||
let levels: Vec<_> = config.iter().filter(|o| config::is_per_model_option(o)).cloned().collect();
|
||||
if known.thought_levels.get(model) != Some(&levels) {
|
||||
known.thought_levels.insert(model.to_owned(), levels);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if known.config != config {
|
||||
known.config = config.to_vec();
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
// Discovery reads one model's options; a session on another model reports that model's.
|
||||
if acp && let Some((model, config)) = model.zip(config) {
|
||||
let learned = model.filter(|_| acp && known.authoritative).zip(config).map(|(model, config)| {
|
||||
let levels: Vec<_> = config.iter().filter(|o| config::is_per_model_option(o)).cloned().collect();
|
||||
if !levels.is_empty() {
|
||||
self.paths.catalogs.learn_levels(self, provider, model, levels);
|
||||
}
|
||||
(model, levels)
|
||||
});
|
||||
if let Some(commands) = commands.filter(|c| !c.is_empty())
|
||||
&& known.commands.get(&self.root_key()).map(Vec::as_slice) != Some(commands)
|
||||
{
|
||||
known.commands.insert(self.root_key(), commands.to_vec());
|
||||
changed = true;
|
||||
}
|
||||
if changed {
|
||||
self.persist_known(&cache);
|
||||
}
|
||||
drop(cache);
|
||||
if let Some((model, levels)) = learned.filter(|(_, levels)| !levels.is_empty()) {
|
||||
self.paths.catalogs.learn_levels(self, provider, model, levels);
|
||||
}
|
||||
if changed {
|
||||
self.emit(AgentEvent::Providers);
|
||||
@@ -512,8 +528,6 @@ struct Task {
|
||||
idle_epoch: AtomicU64,
|
||||
/// Turned on when per-session MCP overrides changed while a turn was busy; dropped once idle.
|
||||
mcp_reload_pending: AtomicBool,
|
||||
/// Turned on when per-session skill overrides changed while a turn was busy; dropped once idle.
|
||||
skills_reload_pending: AtomicBool,
|
||||
/// Settings already sent this session (`(option, value)`), so a refusal is not retried.
|
||||
config_sent: Mutex<HashSet<(String, String)>>,
|
||||
dirty: Mutex<BTreeSet<(Session, usize)>>,
|
||||
@@ -561,7 +575,6 @@ impl AgentManager {
|
||||
idle_release_ms: AtomicU64::new(IDLE_RELEASE.as_millis() as u64),
|
||||
mcp_servers_hook: RwLock::new(None),
|
||||
mcp_executable_hook: RwLock::new(None),
|
||||
skills_policy_hook: RwLock::new(None),
|
||||
attention_seq: AtomicU64::new(0),
|
||||
});
|
||||
shared.paths.catalogs.subscribe(&shared);
|
||||
@@ -711,15 +724,10 @@ impl AgentManager {
|
||||
*self.shared.mcp_executable_hook.write() = Some(Arc::from(hook));
|
||||
}
|
||||
|
||||
/// Provides the user and workspace skill policies and the workspace's trust.
|
||||
pub fn set_skills_policy_hook(&self, hook: Box<SkillsPolicyFn>) {
|
||||
*self.shared.skills_policy_hook.write() = Some(Arc::from(hook));
|
||||
}
|
||||
|
||||
/// The slash commands to complete for `provider`, in `task`'s directory or (without one)
|
||||
/// in the project: what the agent offered last time there, unadvertised builtins,
|
||||
/// for Claude Code the skills and custom commands on disk it has not listed (for
|
||||
/// Hermes, its profile's skills), and the skills hub's active skills for every agent.
|
||||
/// and, for Claude Code, skills and custom commands on disk it has not listed (for Hermes,
|
||||
/// its profile's skills).
|
||||
pub async fn commands(&self, provider: &str, task: Option<&str>) -> IdeResult<Vec<AgentCommand>> {
|
||||
let (provider, offered, cwd) = match task {
|
||||
Some(id) => {
|
||||
@@ -762,44 +770,11 @@ impl AgentManager {
|
||||
.await?;
|
||||
return Ok(skills::merge(offered, found));
|
||||
}
|
||||
if provider == "claude" || provider == "claude-acp" {
|
||||
let claude_cwd = cwd.clone();
|
||||
let found = blocking(move || Ok(skills::discover(&claude_cwd, home.as_deref()))).await?;
|
||||
offered = skills::merge(offered, found);
|
||||
if provider != "claude" && provider != "claude-acp" {
|
||||
return Ok(offered);
|
||||
}
|
||||
// The hub's active skills complete on every agent; its `off` ones drop out here,
|
||||
// which is all the enforcement an ACP agent gets.
|
||||
let holder = self.task_for_commands(&provider, task);
|
||||
let states = match holder {
|
||||
Some(holder) => holder.skill_states().await,
|
||||
None => {
|
||||
let (policy, root) = {
|
||||
let shared = &self.shared;
|
||||
let policy = shared.skills_policy_hook.read().as_ref().map(|hook| hook()).unwrap_or_default();
|
||||
(policy, shared.paths.project_root.clone())
|
||||
};
|
||||
let home = self.shared.paths.home_dir.clone();
|
||||
blocking(move || {
|
||||
Ok(skills::resolve(
|
||||
skills::discover_skills(&root, home.as_deref()),
|
||||
None,
|
||||
&policy.workspace,
|
||||
&policy.user,
|
||||
policy.workspace_trusted,
|
||||
))
|
||||
})
|
||||
.await
|
||||
.unwrap_or_default()
|
||||
}
|
||||
};
|
||||
Ok(skills::menu_commands(offered, &states))
|
||||
}
|
||||
|
||||
/// The task to resolve skills for, when the commands are for one and its provider matches.
|
||||
fn task_for_commands(&self, provider: &str, task: Option<&str>) -> Option<Arc<Task>> {
|
||||
let task = self.task(task?).ok()?;
|
||||
let matches = task.state.lock().task.provider == provider;
|
||||
matches.then_some(task)
|
||||
let found = blocking(move || Ok(skills::discover(&cwd, home.as_deref()))).await?;
|
||||
Ok(skills::merge(offered, found))
|
||||
}
|
||||
|
||||
fn task(&self, id: &str) -> IdeResult<Arc<Task>> {
|
||||
@@ -883,7 +858,6 @@ impl AgentManager {
|
||||
retry: None,
|
||||
background: Box::default(),
|
||||
mcp_overrides: BTreeMap::new(),
|
||||
skill_overrides: BTreeMap::new(),
|
||||
stats: Box::default(),
|
||||
};
|
||||
let file = TaskFile {
|
||||
@@ -1002,7 +976,6 @@ impl AgentManager {
|
||||
retry: None,
|
||||
background: Box::default(),
|
||||
mcp_overrides: req.mcp_overrides,
|
||||
skill_overrides: req.skill_overrides,
|
||||
stats: Box::default(),
|
||||
};
|
||||
let file = TaskFile {
|
||||
@@ -1346,14 +1319,13 @@ impl AgentManager {
|
||||
(s.task.cwd.0.clone(), s.task.provider.clone(), s.task.mcp_overrides.clone())
|
||||
};
|
||||
let mcp_servers = source.shared.mcp_servers_for_session(&provider_id, &live.init, &mcp_overrides);
|
||||
let skills_delivery = source.stage_skills(stage_key(live.driver), &cwd).await;
|
||||
let cwd_s = dunce::canonicalize(&cwd).unwrap_or(cwd).to_string_lossy().into_owned();
|
||||
let reply: Value = live
|
||||
.peer
|
||||
.request(
|
||||
"session/fork",
|
||||
{
|
||||
let mut params = session_params(&cwd_s, &mcp_servers, skills_delivery.as_ref());
|
||||
let mut params = session_params(&cwd_s, &mcp_servers);
|
||||
params["sessionId"] = json!(live.session);
|
||||
params
|
||||
},
|
||||
@@ -1754,7 +1726,6 @@ impl AgentManager {
|
||||
*task.deleted.lock() = true;
|
||||
let _ = std::fs::remove_file(self.shared.paths.store_dir.join(format!("{id}.json")));
|
||||
let _ = std::fs::remove_dir_all(task.turn_dir());
|
||||
skills::remove_farm(&self.shared.paths.store_dir, id);
|
||||
let saved = task.state.lock().saved.clone();
|
||||
if let Some(saved) = saved
|
||||
&& !self.tasks.read().values().any(|t| t.state.lock().saved.as_ref() == Some(&saved))
|
||||
@@ -2016,38 +1987,6 @@ impl AgentManager {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Sets the session's skill modes; like MCP overrides, a change reaches the agent when
|
||||
/// its idle session is recycled and the next turn starts fresh.
|
||||
pub fn set_skill_overrides(&self, id: &str, overrides: BTreeMap<String, AgentSkillMode>) -> IdeResult<AgentTask> {
|
||||
let task = self.task(id)?;
|
||||
let cleaned: BTreeMap<String, AgentSkillMode> = overrides
|
||||
.into_iter()
|
||||
.filter_map(|(k, v)| (!k.trim().is_empty()).then(|| (k.trim().to_owned(), v)))
|
||||
.collect();
|
||||
let (changed, busy, has_bg, out) = {
|
||||
let mut s = task.state.lock();
|
||||
if s.task.status == AgentStatus::Archived {
|
||||
return Err(IdeError::invalid("the task is archived"));
|
||||
}
|
||||
let changed = s.task.skill_overrides != cleaned;
|
||||
if changed {
|
||||
s.task.skill_overrides = cleaned;
|
||||
s.task.updated_ms = now_ms();
|
||||
}
|
||||
(changed, s.busy, !s.background_tasks.is_empty(), s.task.clone())
|
||||
};
|
||||
if changed {
|
||||
task.persist();
|
||||
task.emit_task();
|
||||
if busy || has_bg || !task.permissions.lock().is_empty() {
|
||||
task.skills_reload_pending.store(true, Ordering::Release);
|
||||
} else {
|
||||
task.recycle_resumable_session();
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Recycles idle resumable live sessions (or schedules reload after the running turn) when
|
||||
/// global, workspace, or built-in IDE MCP server settings change.
|
||||
pub fn notify_mcp_servers_changed(&self) {
|
||||
@@ -2080,55 +2019,6 @@ impl AgentManager {
|
||||
}
|
||||
|
||||
impl Task {
|
||||
/// The skills offered in this project: every discovery resolved against the policies
|
||||
/// and the task's overrides.
|
||||
async fn skill_states(&self) -> Vec<AgentSkillState> {
|
||||
let (policy, overrides, home, root) = {
|
||||
let shared = &self.shared;
|
||||
let policy = shared.skills_policy_hook.read().as_ref().map(|hook| hook()).unwrap_or_default();
|
||||
let overrides = self.state.lock().task.skill_overrides.clone();
|
||||
(policy, overrides, shared.paths.home_dir.clone(), shared.paths.project_root.clone())
|
||||
};
|
||||
blocking(move || {
|
||||
Ok(skills::resolve(
|
||||
skills::discover_skills(&root, home.as_deref()),
|
||||
Some(&overrides),
|
||||
&policy.workspace,
|
||||
&policy.user,
|
||||
policy.workspace_trusted,
|
||||
))
|
||||
})
|
||||
.await
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Stages the session's skills into the task's farm and reports what its CLI takes.
|
||||
/// Nothing staged for an ACP agent (its `/` menu is filtered instead), and a failed
|
||||
/// stage (locked files, full disk) runs the session without the farm.
|
||||
async fn stage_skills(&self, provider: &str, cwd: &Path) -> Option<skills::Delivery> {
|
||||
let states = self.skill_states().await;
|
||||
let (farm, home, out_cwd) = {
|
||||
(
|
||||
skills::farm_dir(&self.shared.paths.store_dir, &self.id),
|
||||
self.shared.paths.home_dir.clone(),
|
||||
cwd.to_path_buf(),
|
||||
)
|
||||
};
|
||||
let provider = provider.to_owned();
|
||||
match blocking(move || {
|
||||
skills::stage(&farm, &provider, &states, &out_cwd, home.as_deref())
|
||||
.map_err(|e| IdeError::internal(e.to_string()))
|
||||
})
|
||||
.await
|
||||
{
|
||||
Ok(delivery) => Some(delivery),
|
||||
Err(e) => {
|
||||
tracing::warn!("agent task {}: staging its skills failed: {e}", self.id);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn restore(file: TaskFile, shared: Arc<Shared>) -> Arc<Self> {
|
||||
let mut task = file.task;
|
||||
config::add_client_options(&task.provider, &mut task.config);
|
||||
@@ -2185,7 +2075,6 @@ impl Task {
|
||||
turns: AtomicU64::new(0),
|
||||
idle_epoch: AtomicU64::new(0),
|
||||
mcp_reload_pending: AtomicBool::new(false),
|
||||
skills_reload_pending: AtomicBool::new(false),
|
||||
config_sent: Mutex::new(HashSet::new()),
|
||||
dirty: Mutex::new(BTreeSet::new()),
|
||||
streamed: Mutex::new(HashMap::new()),
|
||||
@@ -2477,8 +2366,7 @@ impl Task {
|
||||
if stop != "cancelled" {
|
||||
self.emit_attention(AgentAttentionReason::Finished);
|
||||
}
|
||||
if (self.mcp_reload_pending.swap(false, Ordering::AcqRel)
|
||||
|| self.skills_reload_pending.swap(false, Ordering::AcqRel))
|
||||
if self.mcp_reload_pending.swap(false, Ordering::AcqRel)
|
||||
&& self.state.lock().background_tasks.is_empty()
|
||||
{
|
||||
self.recycle_resumable_session();
|
||||
@@ -2507,7 +2395,8 @@ impl Task {
|
||||
|
||||
async fn switch_discovered_model(&self, target: AgentConfigOption, value: String) -> IdeResult<()> {
|
||||
let provider = self.state.lock().task.provider.clone();
|
||||
let candidate = self.shared.paths.catalogs.listed_model(&self.shared, &provider, &value).ok_or_else(|| {
|
||||
let spec = self.shared.spec(&provider).ok_or_else(|| IdeError::not_found("no such agent"))?;
|
||||
let candidate = self.shared.paths.catalogs.fresh_model(&self.shared, &spec, &value).ok_or_else(|| {
|
||||
IdeError::invalid(format!("{} has no value {value} in the current model catalog", target.name))
|
||||
})?;
|
||||
let selection = {
|
||||
@@ -2995,7 +2884,6 @@ impl Task {
|
||||
let (capabilities, embedded) = capabilities_of(&init);
|
||||
let mcp_overrides = self.state.lock().task.mcp_overrides.clone();
|
||||
let mcp_servers = self.shared.mcp_servers_for_session(provider_id, &init, &mcp_overrides);
|
||||
let skills_delivery = self.stage_skills(stage_key(spec.driver), cwd).await;
|
||||
// Agents that compare canonical paths fail in a symlinked directory (macOS `/tmp`).
|
||||
let cwd_s = dunce::canonicalize(cwd).unwrap_or_else(|_| cwd.to_path_buf()).to_string_lossy().into_owned();
|
||||
|
||||
@@ -3010,7 +2898,7 @@ impl Task {
|
||||
}
|
||||
if let (Some(id), true, false) = (saved, can_load, start_fresh) {
|
||||
self.replaying.store(true, Ordering::Release);
|
||||
let mut params = session_params(&cwd_s, &mcp_servers, skills_delivery.as_ref());
|
||||
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;
|
||||
@@ -3050,7 +2938,7 @@ impl Task {
|
||||
let (session_id, result) = match session {
|
||||
Some(s) => s,
|
||||
None => {
|
||||
let params = session_params(&cwd_s, &mcp_servers, skills_delivery.as_ref());
|
||||
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 },
|
||||
@@ -4026,34 +3914,13 @@ struct McpForSession {
|
||||
off: Vec<String>,
|
||||
}
|
||||
|
||||
/// The driver a session's staged skills are staged for (`skills::stage` matches on it):
|
||||
/// the native CLIs take the farm, everything else (an ACP agent) gets the `/` menu filter.
|
||||
fn stage_key(driver: provider::Driver) -> &'static str {
|
||||
match driver {
|
||||
provider::Driver::Claude => "claude",
|
||||
provider::Driver::Codex => "codex",
|
||||
provider::Driver::Copilot => "copilot",
|
||||
provider::Driver::Acp => "acp",
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 — plus the
|
||||
/// session's staged skills for the drivers that take them.
|
||||
fn session_params(cwd: &str, mcp: &McpForSession, skills: Option<&skills::Delivery>) -> Value {
|
||||
/// 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 });
|
||||
let mut meta = json!({});
|
||||
if !mcp.off.is_empty() {
|
||||
meta["mcpServersOff"] = json!(mcp.off);
|
||||
}
|
||||
if let Some(skills) = skills
|
||||
&& let Ok(v) = serde_json::to_value(skills)
|
||||
{
|
||||
meta["skills"] = v;
|
||||
}
|
||||
if !meta.is_null() && meta.as_object().is_some_and(|m| !m.is_empty()) {
|
||||
params["_meta"] = json!({ "openidea": meta });
|
||||
params["_meta"] = json!({ "openidea": { "mcpServersOff": mcp.off } });
|
||||
}
|
||||
params
|
||||
}
|
||||
|
||||
@@ -110,9 +110,6 @@ pub struct AgentTask {
|
||||
/// Per-session MCP server enable/disable overrides (`server_name` -> `enabled`), including `"openidea"`.
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub mcp_overrides: BTreeMap<String, bool>,
|
||||
/// Per-session skill modes (`skill name` -> mode), on top of the settings' policies.
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub skill_overrides: BTreeMap<String, AgentSkillMode>,
|
||||
/// Token counts of the last turn and context compressions, when the agent reports them.
|
||||
// Boxed so that `AgentEvent::Task` stays within clippy's `large_enum_variant` bound on Windows.
|
||||
#[serde(default)]
|
||||
@@ -690,9 +687,6 @@ pub struct NewAgentTask {
|
||||
/// Per-session MCP server enable/disable overrides (`server_name` -> `enabled`).
|
||||
#[serde(default)]
|
||||
pub mcp_overrides: BTreeMap<String, bool>,
|
||||
/// Per-session skill modes (`skill name` -> mode).
|
||||
#[serde(default)]
|
||||
pub skill_overrides: BTreeMap<String, AgentSkillMode>,
|
||||
/// Creates the task without sending `prompt` (it only names the task): the composer's
|
||||
/// `!` command runs in it first.
|
||||
#[serde(default)]
|
||||
@@ -711,8 +705,6 @@ pub struct AgentChange {
|
||||
pub removed: u32,
|
||||
/// Path before a rename; the left side of its diff reads this path.
|
||||
pub old_path: Option<String>,
|
||||
/// The repository the file is in, when the task's project holds nested repositories.
|
||||
pub repo: Option<IpcPath>,
|
||||
}
|
||||
|
||||
/// A commit made while the task ran, with the files it changed against its first parent.
|
||||
@@ -887,84 +879,6 @@ fn default_true() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
pub use ide_core::settings::{AgentSkillMode, AgentSkillPolicy};
|
||||
|
||||
/// Which CLI's own folders a skill was discovered in (Settings › Agents › Skills groups by it).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AgentSkillSource {
|
||||
/// The project's `.agents/skills` and `.openidea/skills`.
|
||||
#[default]
|
||||
Workspace,
|
||||
/// The user's `~/.agents/skills` (what `npx skills add` fills).
|
||||
User,
|
||||
/// The project's `.claude/skills`.
|
||||
ClaudeWorkspace,
|
||||
/// `~/.claude/skills`.
|
||||
ClaudeUser,
|
||||
/// The project's `.github/skills` (Copilot's repository skills).
|
||||
GithubWorkspace,
|
||||
/// `~/.copilot/skills` and `~/.copilot/installed-plugins/*`.
|
||||
CopilotUser,
|
||||
/// The project's `.codex/skills`.
|
||||
CodexWorkspace,
|
||||
/// `~/.codex/skills`.
|
||||
CodexUser,
|
||||
/// The project's `.cursor/skills`.
|
||||
CursorWorkspace,
|
||||
/// `~/.cursor/skills`.
|
||||
CursorUser,
|
||||
}
|
||||
|
||||
impl AgentSkillSource {
|
||||
/// Whether skills of this source are only read, never delivered by OpenIDEA: the CLI
|
||||
/// discovers them itself, so "off" holds only where the CLI supports a native disable.
|
||||
pub fn discovered(&self) -> bool {
|
||||
!matches!(self, Self::Workspace | Self::User)
|
||||
}
|
||||
}
|
||||
|
||||
/// One discovered skill: a folder with a `SKILL.md`.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentSkill {
|
||||
/// The frontmatter `name`, else the folder's name.
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
/// Canonical folder holding `SKILL.md` (symlinks resolved, so duplicates collapse).
|
||||
pub path: IpcPath,
|
||||
pub source: AgentSkillSource,
|
||||
/// The `SKILL.md` passes validation (`name` matches its folder, `description` present).
|
||||
pub valid: bool,
|
||||
/// What validation found (`name` mismatch, missing or over-long description…).
|
||||
pub warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// A skill as Settings › Agents › Skills shows it: discovery plus the effective mode and
|
||||
/// which layer decided it.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentSkillState {
|
||||
pub skill: AgentSkill,
|
||||
pub mode: AgentSkillMode,
|
||||
/// What set `mode`: a session override, the workspace, the user's settings, workspace
|
||||
/// trust, or nothing (the default `auto`).
|
||||
pub origin: AgentSkillOrigin,
|
||||
}
|
||||
|
||||
/// Which layer decided a skill's [`AgentSkillState::mode`].
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AgentSkillOrigin {
|
||||
#[default]
|
||||
None,
|
||||
Session,
|
||||
Workspace,
|
||||
User,
|
||||
/// An untrusted workspace's skills and policies may only turn skills off.
|
||||
Trust,
|
||||
}
|
||||
|
||||
/// An external MCP configuration file discovered on disk (user CLI config or workspace file).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
|
||||
@@ -172,10 +172,6 @@ struct Session {
|
||||
mcp_config: Option<tempfile::TempPath>,
|
||||
/// MCP servers switched off for this session (`--disallowedTools`), its own config's too.
|
||||
mcp_off: Vec<String>,
|
||||
/// The staged skills folder passed as `--add-dir` (its `.claude/skills` holds the copies).
|
||||
skills_add_dir: Option<PathBuf>,
|
||||
/// The staged skills' `--settings` JSON (`skillOverrides` for the native ones too).
|
||||
skills_settings: Option<String>,
|
||||
shim: Weak<Shim>,
|
||||
st: Mutex<State>,
|
||||
/// Serializes (re)starting the process.
|
||||
@@ -360,13 +356,10 @@ impl Shim {
|
||||
None
|
||||
}
|
||||
});
|
||||
let skills = params.pointer("/_meta/openidea/skills");
|
||||
let session = Arc::new(Session {
|
||||
id: id.to_owned(),
|
||||
mcp_config,
|
||||
mcp_off,
|
||||
skills_add_dir: skills.and_then(|s| s.get("claudeAddDir")).and_then(Value::as_str).map(PathBuf::from),
|
||||
skills_settings: skills.and_then(|s| s.get("claudeSettings")).and_then(Value::as_str).map(str::to_owned),
|
||||
shim: Arc::downgrade(self),
|
||||
st: Mutex::new(State {
|
||||
proc: None,
|
||||
@@ -680,14 +673,6 @@ impl Session {
|
||||
if !self.mcp_off.is_empty() {
|
||||
args.extend(["--disallowedTools".to_owned(), self.mcp_off.join(",")]);
|
||||
}
|
||||
// The staged skills: `.claude/skills` of the added directory is discovered like the
|
||||
// project's own, and the settings hold the modes of the skills it sees natively too.
|
||||
if let Some(dir) = &self.skills_add_dir {
|
||||
args.extend(["--add-dir".to_owned(), dir.to_string_lossy().into_owned()]);
|
||||
}
|
||||
if let Some(settings) = &self.skills_settings {
|
||||
args.extend(["--settings".to_owned(), settings.clone()]);
|
||||
}
|
||||
args.extend(start.args());
|
||||
let launch =
|
||||
Launch { program: shim.config.program.clone(), args, cwd: self.cwd.clone(), env: shim.config.env.clone() };
|
||||
|
||||
@@ -334,31 +334,6 @@ fn str_param<'a>(params: &'a Value, key: &str) -> Result<&'a str, ResponseError>
|
||||
params.get(key).and_then(Value::as_str).ok_or_else(|| invalid(format!("missing {key}")))
|
||||
}
|
||||
|
||||
/// Fills a `thread/start`/`thread/resume`/`thread/fork` request's `config` with the session's
|
||||
/// MCP servers and its staged skills: the off ones, by path (`skills.config` entries with
|
||||
/// `enabled = false`, which the CLI honors for the copies it discovers natively too).
|
||||
fn apply_thread_config(params: &Value, request: &mut Value) {
|
||||
let mut config = translate::mcp_config(params).unwrap_or_else(|| json!({}));
|
||||
let off: Vec<Value> = params
|
||||
.pointer("/_meta/openidea/skills/codexOff")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|entry| {
|
||||
let path = entry.get(1)?.as_str()?;
|
||||
Some(json!({ "path": path, "enabled": false }))
|
||||
})
|
||||
.collect();
|
||||
if !off.is_empty()
|
||||
&& let Some(map) = config.as_object_mut()
|
||||
{
|
||||
map.insert("skills".into(), json!({ "config": off }));
|
||||
}
|
||||
if !config.as_object().is_some_and(|m| m.is_empty()) {
|
||||
request["config"] = config;
|
||||
}
|
||||
}
|
||||
|
||||
impl CodexShim {
|
||||
fn codex(&self) -> &Peer {
|
||||
self.codex.get().expect("attached before any message")
|
||||
@@ -439,31 +414,6 @@ impl CodexShim {
|
||||
}
|
||||
}
|
||||
|
||||
/// Hands the session's staged skills to the app-server: the farm's `codex` tree joins
|
||||
/// its discovery roots. Best-effort: a CLI version without `skills/extraRoots/set`
|
||||
/// (the method arrived later than some pinned installs) runs without the farm, as
|
||||
/// before.
|
||||
async fn apply_skill_roots(&self, session: &str, params: &Value) {
|
||||
let roots = params
|
||||
.pointer("/_meta/openidea/skills/codexExtraRoots")
|
||||
.and_then(Value::as_array)
|
||||
.map(|a| a.iter().filter_map(Value::as_str).collect::<Vec<_>>())
|
||||
.unwrap_or_default();
|
||||
if roots.is_empty() {
|
||||
return;
|
||||
}
|
||||
let set = tokio::time::timeout(
|
||||
Duration::from_secs(5),
|
||||
self.call("skills/extraRoots/set", json!({ "extraRoots": roots })),
|
||||
)
|
||||
.await;
|
||||
match set {
|
||||
Ok(Ok(_)) => {}
|
||||
Ok(Err(e)) => tracing::info!("codex session {session}: could not set the extra skill roots: {}", e.message),
|
||||
Err(e) => tracing::info!("codex session {session}: could not set the extra skill roots: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Registers a thread codex opened for a session of its own; returns its `configOptions`.
|
||||
fn open_thread(&self, result: &Value, models: &[ModelInfo], settings: Option<Settings>) -> (String, Value) {
|
||||
let thread = result.get("thread").unwrap_or(&Value::Null);
|
||||
@@ -484,13 +434,14 @@ impl CodexShim {
|
||||
let models = self.models().await?;
|
||||
self.prepare_project_trust(params).await;
|
||||
let mut request = json!({ "cwd": params.get("cwd") });
|
||||
apply_thread_config(params, &mut request);
|
||||
if let Some(config) = translate::mcp_config(params) {
|
||||
request["config"] = config;
|
||||
}
|
||||
let result = self.call("thread/start", request).await?;
|
||||
let (id, options) = self.open_thread(&result, &models, None);
|
||||
if id.is_empty() {
|
||||
return Err(error(codes::INTERNAL_ERROR, "codex started no thread"));
|
||||
}
|
||||
self.apply_skill_roots(&id, params).await;
|
||||
self.publish_skills(&id).await;
|
||||
Ok(json!({ "sessionId": id, "configOptions": options }))
|
||||
}
|
||||
@@ -501,7 +452,9 @@ impl CodexShim {
|
||||
let models = self.models().await?;
|
||||
self.prepare_project_trust(params).await;
|
||||
let mut request = json!({ "threadId": id, "cwd": params.get("cwd") });
|
||||
apply_thread_config(params, &mut request);
|
||||
if let Some(config) = translate::mcp_config(params) {
|
||||
request["config"] = config;
|
||||
}
|
||||
let result = self.call("thread/resume", request).await?;
|
||||
let (_, options) = self.open_thread(&result, &models, None);
|
||||
let cwd = self.state.lock().threads.get(id).and_then(|t| t.cwd.clone());
|
||||
@@ -509,7 +462,6 @@ impl CodexShim {
|
||||
for update in translate::history(thread, cwd.as_deref()) {
|
||||
self.emit(id, update);
|
||||
}
|
||||
self.apply_skill_roots(id, params).await;
|
||||
self.publish_skills(id).await;
|
||||
Ok(json!({ "configOptions": options }))
|
||||
}
|
||||
@@ -520,7 +472,9 @@ impl CodexShim {
|
||||
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") });
|
||||
apply_thread_config(params, &mut request);
|
||||
if let Some(config) = translate::mcp_config(params) {
|
||||
request["config"] = config;
|
||||
}
|
||||
if let Some(s) = &settings {
|
||||
request["model"] = json!(s.model_slug(&models));
|
||||
request["approvalPolicy"] = json!(s.mode.approval_policy());
|
||||
@@ -528,7 +482,6 @@ impl CodexShim {
|
||||
}
|
||||
let result = self.call("thread/fork", request).await?;
|
||||
let (id, options) = self.open_thread(&result, &models, settings);
|
||||
self.apply_skill_roots(&id, params).await;
|
||||
self.publish_skills(&id).await;
|
||||
Ok(json!({ "sessionId": id, "configOptions": options }))
|
||||
}
|
||||
|
||||
@@ -372,24 +372,6 @@ fn error(code: i64, message: impl Into<String>) -> ResponseError {
|
||||
ResponseError { code, message: message.into(), data: None }
|
||||
}
|
||||
|
||||
/// Adds the session's staged skills to a `session.create`/`session.resume` request:
|
||||
/// `skillDirectories` (the farm's `copilot` tree) and `disabledSkills` (the off and
|
||||
/// slash-only ones; Copilot invokes skills with the model only, so a slash-only skill has
|
||||
/// no other switch here).
|
||||
fn apply_skills(params: &Value, req: &mut Value) {
|
||||
let skills = params.pointer("/_meta/openidea/skills");
|
||||
if let Some(dirs) = skills.and_then(|s| s.get("copilotSkillDirectories")).and_then(Value::as_array)
|
||||
&& !dirs.is_empty()
|
||||
{
|
||||
req["skillDirectories"] = json!(dirs.iter().filter_map(Value::as_str).collect::<Vec<_>>());
|
||||
}
|
||||
if let Some(disabled) = skills.and_then(|s| s.get("copilotDisabledSkills")).and_then(Value::as_array)
|
||||
&& !disabled.is_empty()
|
||||
{
|
||||
req["disabledSkills"] = json!(disabled.iter().filter_map(Value::as_str).collect::<Vec<_>>());
|
||||
}
|
||||
}
|
||||
|
||||
fn invalid(message: impl Into<String>) -> ResponseError {
|
||||
error(codes::INVALID_PARAMS, message)
|
||||
}
|
||||
@@ -514,7 +496,6 @@ impl CopilotShim {
|
||||
if let Some(disabled) = translate::wire_disabled_mcp_servers(params) {
|
||||
req["disabledMcpServers"] = disabled;
|
||||
}
|
||||
apply_skills(params, &mut req);
|
||||
|
||||
let created = self.call("session.create", req).await?;
|
||||
let session_id = created
|
||||
@@ -565,7 +546,6 @@ impl CopilotShim {
|
||||
if let Some(disabled) = translate::wire_disabled_mcp_servers(params) {
|
||||
req["disabledMcpServers"] = disabled;
|
||||
}
|
||||
apply_skills(params, &mut req);
|
||||
|
||||
let resumed = self.call("session.resume", req).await?;
|
||||
if let Ok(current) = self.call("session.model.getCurrent", json!({ "sessionId": session_id })).await {
|
||||
|
||||
@@ -1,17 +1,11 @@
|
||||
//! Slash commands and skills on disk. Claude Code's own discovery (`.claude/skills` and
|
||||
//! `.claude/commands` of the working directory tree and `~/.claude`, and a Hermes profile's
|
||||
//! `skills`) for completion before (or without) a session, plus the multi-level skills hub
|
||||
//! of #3897: every CLI's skill folders discovered once, deduplicated by canonical path,
|
||||
//! resolved against the `[agents.skills.<name>]` policies of the global and workspace
|
||||
//! settings, and staged into a per-session folder the CLIs each receive their own way.
|
||||
//! Claude Code's slash commands on disk, for completion before (or without) a session:
|
||||
//! skills (`.claude/skills/<dir>/SKILL.md`) and custom commands (`.claude/commands/**/*.md`)
|
||||
//! of the working directory and every directory above it, then the user's `~/.claude`; and
|
||||
//! the skills of a Hermes profile (`<profile>/skills`).
|
||||
|
||||
use crate::{
|
||||
AgentCommand, AgentCommandSource, AgentSkill, AgentSkillMode, AgentSkillOrigin, AgentSkillPolicy, AgentSkillSource,
|
||||
AgentSkillState,
|
||||
};
|
||||
use ide_core::output_encoding::strip_ansi;
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
use crate::{AgentCommand, AgentCommandSource};
|
||||
use std::collections::HashSet;
|
||||
use std::path::Path;
|
||||
|
||||
const MAX_DESCRIPTION: usize = 200;
|
||||
/// Command directories nest this deep at most (`a/b/c.md` → `a:b:c`).
|
||||
@@ -206,370 +200,6 @@ fn truncate(s: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
// ─── The skills hub (#3897): discovery, policy, delivery ────────────────────────────
|
||||
|
||||
/// A skill's `name` must be this and lowercase letters, digits and hyphens only.
|
||||
fn valid_name(name: &str) -> bool {
|
||||
(1..=64).contains(&name.len()) && name.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
|
||||
}
|
||||
|
||||
/// A `SKILL.md`'s description is at most this many characters.
|
||||
const MAX_SKILL_DESCRIPTION: usize = 1024;
|
||||
|
||||
/// The workspace folders skills are discovered in, by the source they report.
|
||||
const WORKSPACE_ROOTS: &[(&str, AgentSkillSource)] = &[
|
||||
(".agents/skills", AgentSkillSource::Workspace),
|
||||
(".openidea/skills", AgentSkillSource::Workspace),
|
||||
(".claude/skills", AgentSkillSource::ClaudeWorkspace),
|
||||
(".github/skills", AgentSkillSource::GithubWorkspace),
|
||||
(".codex/skills", AgentSkillSource::CodexWorkspace),
|
||||
(".cursor/skills", AgentSkillSource::CursorWorkspace),
|
||||
];
|
||||
|
||||
/// The home folders skills are discovered in, by the source they report.
|
||||
const HOME_ROOTS: &[(&str, AgentSkillSource)] = &[
|
||||
(".agents/skills", AgentSkillSource::User),
|
||||
(".claude/skills", AgentSkillSource::ClaudeUser),
|
||||
(".copilot/skills", AgentSkillSource::CopilotUser),
|
||||
(".codex/skills", AgentSkillSource::CodexUser),
|
||||
(".cursor/skills", AgentSkillSource::CursorUser),
|
||||
];
|
||||
|
||||
/// Every skill found under `workspace` (a project, scanned even for a worktree task, whose
|
||||
/// checkout lacks untracked skills) and `home`, in source precedence order, symlinked
|
||||
/// duplicates collapsed by canonical path: the first of a path wins, and so does the first
|
||||
/// of a name (the higher source), so a session never sees one skill twice.
|
||||
pub fn discover_skills(workspace: &Path, home: Option<&Path>) -> Vec<AgentSkill> {
|
||||
let mut out: Vec<AgentSkill> = Vec::new();
|
||||
let mut seen_paths: HashSet<PathBuf> = HashSet::new();
|
||||
let mut seen_names: HashSet<String> = HashSet::new();
|
||||
let mut roots: Vec<(PathBuf, AgentSkillSource)> = Vec::new();
|
||||
roots.extend(WORKSPACE_ROOTS.iter().map(|(rel, source)| (workspace.join(rel), *source)));
|
||||
let mut plugin_roots = Vec::new();
|
||||
if let Some(home) = home {
|
||||
roots.extend(HOME_ROOTS.iter().map(|(rel, source)| (home.join(rel), *source)));
|
||||
// `copilot install` unpacks plugins under `installed-plugins/<plugin>/`, whose skills
|
||||
// sit in a `skills` folder (or directly in the plugin folder).
|
||||
let plugins = home.join(".copilot/installed-plugins");
|
||||
if let Ok(plugins) = plugins.read_dir() {
|
||||
for plugin in plugins.flatten() {
|
||||
if plugin.path().is_dir() {
|
||||
plugin_roots.push((plugin.path().join("skills"), AgentSkillSource::CopilotUser));
|
||||
plugin_roots.push((plugin.path(), AgentSkillSource::CopilotUser));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
roots.extend(plugin_roots);
|
||||
for (root, source) in roots {
|
||||
for skill in skills_of(&root, source) {
|
||||
let path = dunce::canonicalize(&skill.path.0).unwrap_or_else(|_| skill.path.0.clone());
|
||||
if !seen_paths.insert(path.clone()) || !seen_names.insert(skill.name.clone()) {
|
||||
continue;
|
||||
}
|
||||
out.push(AgentSkill { path: path.into(), ..skill });
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The skills of one root: `<name>/SKILL.md` folders, validated.
|
||||
fn skills_of(root: &Path, source: AgentSkillSource) -> Vec<AgentSkill> {
|
||||
let mut out: Vec<AgentSkill> = Vec::new();
|
||||
let Ok(entries) = std::fs::read_dir(root) else { return out };
|
||||
for entry in entries.flatten() {
|
||||
let dir = entry.path();
|
||||
let Some(folder) = dir.file_name().and_then(|n| n.to_str()).map(str::to_owned) else { continue };
|
||||
if !dir.is_dir() || folder.starts_with('.') {
|
||||
continue;
|
||||
}
|
||||
let Ok(text) = std::fs::read_to_string(dir.join("SKILL.md")) else { continue };
|
||||
let meta = Frontmatter::parse(&text);
|
||||
let name = meta.get("name").filter(|n| !n.is_empty()).map(str::to_owned).unwrap_or_else(|| folder.clone());
|
||||
let mut warnings = Vec::new();
|
||||
if !valid_name(&name) {
|
||||
warnings.push(format!("`name: {name}` is not 1-64 lowercase letters, digits or hyphens"));
|
||||
}
|
||||
if name != folder {
|
||||
warnings.push(format!("`name: {name}` does not match the folder `{folder}`"));
|
||||
}
|
||||
let description = meta.get("description").unwrap_or_default();
|
||||
let description = strip_ansi(description).trim().to_owned();
|
||||
if description.is_empty() {
|
||||
warnings.push("no `description`: the model never sees when to use it".into());
|
||||
} else if description.chars().count() > MAX_SKILL_DESCRIPTION {
|
||||
warnings.push(format!("`description` is over {MAX_SKILL_DESCRIPTION} characters"));
|
||||
}
|
||||
out.push(AgentSkill {
|
||||
name,
|
||||
description: truncate(&description),
|
||||
path: dir.into(),
|
||||
source,
|
||||
valid: warnings.is_empty(),
|
||||
warnings,
|
||||
});
|
||||
}
|
||||
out.sort_by(|a, b| a.name.cmp(&b.name));
|
||||
out
|
||||
}
|
||||
|
||||
/// A skill's mode, as one policy layer of the settings has it.
|
||||
type Policies = BTreeMap<String, AgentSkillPolicy>;
|
||||
|
||||
/// Resolves every skill's mode: a session override, then the workspace's and the user's
|
||||
/// `[agents.skills.<name>]` policy, then the default `auto` — with an untrusted workspace
|
||||
/// able to turn skills off only: its own skills stay off (whatever the session chose), and
|
||||
/// its policies hold only when they turn a skill off.
|
||||
pub fn resolve(
|
||||
skills: Vec<AgentSkill>,
|
||||
session: Option<&BTreeMap<String, AgentSkillMode>>,
|
||||
workspace: &Policies,
|
||||
user: &Policies,
|
||||
workspace_trusted: bool,
|
||||
) -> Vec<AgentSkillState> {
|
||||
let mut out = Vec::new();
|
||||
for skill in skills {
|
||||
let workspace_skill = matches!(
|
||||
skill.source,
|
||||
AgentSkillSource::Workspace
|
||||
| AgentSkillSource::ClaudeWorkspace
|
||||
| AgentSkillSource::GithubWorkspace
|
||||
| AgentSkillSource::CodexWorkspace
|
||||
| AgentSkillSource::CursorWorkspace
|
||||
);
|
||||
let (mode, origin) = if workspace_skill && !workspace_trusted {
|
||||
// Workspace trust gates the workspace's own skills, whatever else says.
|
||||
(AgentSkillMode::Off, AgentSkillOrigin::Trust)
|
||||
} else if let Some(chosen) = session.and_then(|s| s.get(&skill.name)) {
|
||||
(*chosen, AgentSkillOrigin::Session)
|
||||
} else if let Some(policy) =
|
||||
workspace.get(&skill.name).filter(|p| workspace_trusted || p.mode == AgentSkillMode::Off)
|
||||
{
|
||||
(policy.mode, AgentSkillOrigin::Workspace)
|
||||
} else if let Some(policy) = user.get(&skill.name) {
|
||||
(policy.mode, AgentSkillOrigin::User)
|
||||
} else {
|
||||
(AgentSkillMode::Auto, AgentSkillOrigin::None)
|
||||
};
|
||||
out.push(AgentSkillState { skill, mode, origin });
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// What one CLI session receives for its active skills. Sent to the shims in
|
||||
/// `session/new`'s `_meta.openidea.skills`, so each driver applies its own fields.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct Delivery {
|
||||
/// Claude Code: the farm passed as `--add-dir` (its `.claude/skills` holds the staged copies).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub claude_add_dir: Option<PathBuf>,
|
||||
/// Claude Code: the `--settings` JSON with `skillOverrides` (the native skills too).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub claude_settings: Option<String>,
|
||||
/// Copilot: `skillDirectories` (the farm's `copilot` tree).
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub copilot_skill_directories: Vec<String>,
|
||||
/// Copilot: `disabledSkills`, spelled as the skills are.
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub copilot_disabled_skills: Vec<String>,
|
||||
/// Codex: `skills/extraRoots/set` roots (the farm's `codex` tree).
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub codex_extra_roots: Vec<String>,
|
||||
/// Codex: `skills.config` entries turning skills off by path.
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub codex_off: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
/// Stages the skills a session of `provider` runs with into `farm` — linking (copying on
|
||||
/// Windows, where directory symlinks need Developer Mode) every active skill folder into
|
||||
/// the CLI's tree — and reports what to hand the CLI. Skills the CLI discovers natively
|
||||
/// (its own folders of the working directory and the home) are not staged again: it already
|
||||
/// sees them, and seeing both would list one skill twice. Skills `off` are never staged;
|
||||
/// the CLI's native disable (where it has one) receives their names or paths. An ACP
|
||||
/// agent gets nothing here: its `/` menu is filtered instead.
|
||||
pub fn stage(
|
||||
farm: &Path,
|
||||
provider: &str,
|
||||
states: &[AgentSkillState],
|
||||
cwd: &Path,
|
||||
home: Option<&Path>,
|
||||
) -> std::io::Result<Delivery> {
|
||||
let mut out = Delivery::default();
|
||||
let cwd = dunce::canonicalize(cwd).unwrap_or_else(|_| cwd.to_path_buf());
|
||||
// Only the native drivers take the farm, each its own tree; `provider` is their key
|
||||
// (`claude`, `copilot`, `codex`), anything else (an ACP agent) gets the `/` menu filter.
|
||||
let (claude_tree, copilot_tree, codex_tree) = match provider {
|
||||
"claude" => (Some(farm.join(".claude/skills")), None, None),
|
||||
"copilot" => (None, Some(farm.join("copilot")), None),
|
||||
"codex" => (None, None, Some(farm.join("codex"))),
|
||||
_ => return Ok(out),
|
||||
};
|
||||
// Restage from scratch: a skill turned off or deleted since the last session must not
|
||||
// linger in the tree. Removing a tree removes its links, never the skills they point at.
|
||||
for tree in [&claude_tree, &copilot_tree, &codex_tree].into_iter().flatten() {
|
||||
match std::fs::remove_dir_all(tree) {
|
||||
Err(e) if e.kind() != std::io::ErrorKind::NotFound => return Err(e),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
for state in states {
|
||||
let name = state.skill.name.as_str();
|
||||
let path = state.skill.path.0.as_path();
|
||||
match state.mode {
|
||||
AgentSkillMode::Off => {
|
||||
out.codex_off.push((name.to_owned(), state.skill.path.to_string_lossy().into_owned()));
|
||||
}
|
||||
// Claude Code runs a slash-only skill on `/name`, so it has to see the folder;
|
||||
// Copilot and Codex have no such mode and get it disabled or left out.
|
||||
AgentSkillMode::SlashOnly => {
|
||||
if let Some(tree) = claude_tree.as_ref().filter(|_| !native_claude(&state.skill, &cwd, home)) {
|
||||
link_skill(&tree.join(name), path)?;
|
||||
}
|
||||
}
|
||||
AgentSkillMode::Auto => {
|
||||
if let Some(tree) = claude_tree.as_ref().filter(|_| !native_claude(&state.skill, &cwd, home)) {
|
||||
link_skill(&tree.join(name), path)?;
|
||||
}
|
||||
if let Some(tree) = copilot_tree.as_ref().filter(|_| !native_copilot(&state.skill, &cwd, home)) {
|
||||
link_skill(&tree.join(name), path)?;
|
||||
}
|
||||
if let Some(tree) = codex_tree.as_ref().filter(|_| !native_codex(&state.skill, &cwd, home)) {
|
||||
link_skill(&tree.join(name), path)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if claude_tree.as_ref().is_some_and(|t| t.exists()) {
|
||||
out.claude_add_dir = Some(farm.to_path_buf());
|
||||
}
|
||||
if let Some(tree) = copilot_tree.as_ref().filter(|t| t.exists()) {
|
||||
out.copilot_skill_directories.push(tree.to_string_lossy().into_owned());
|
||||
}
|
||||
if let Some(tree) = codex_tree.as_ref().filter(|t| t.exists()) {
|
||||
out.codex_extra_roots.push(tree.to_string_lossy().into_owned());
|
||||
}
|
||||
// Claude Code's `skillOverrides` and Copilot's `disabledSkills` take the names of the
|
||||
// off and slash-only skills — the native copies included.
|
||||
let off: Vec<&str> =
|
||||
states.iter().filter(|s| s.mode == AgentSkillMode::Off).map(|s| s.skill.name.as_str()).collect();
|
||||
let slash: Vec<&str> =
|
||||
states.iter().filter(|s| s.mode == AgentSkillMode::SlashOnly).map(|s| s.skill.name.as_str()).collect();
|
||||
if !off.is_empty() || !slash.is_empty() {
|
||||
let mut overrides = serde_json::Map::new();
|
||||
for (name, mode) in off.iter().map(|n| (*n, "off")).chain(slash.iter().map(|n| (*n, "user-invocable-only"))) {
|
||||
overrides.insert(name.to_owned(), serde_json::Value::String(mode.to_owned()));
|
||||
}
|
||||
out.claude_settings = Some(
|
||||
serde_json::to_string(&serde_json::json!({ "skillOverrides": overrides })).expect("settings serialize"),
|
||||
);
|
||||
out.copilot_disabled_skills = off.iter().chain(slash.iter()).map(|n| (*n).to_owned()).collect();
|
||||
out.copilot_disabled_skills.sort();
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Claude Code sees this skill without the farm: its own `.claude/skills` of the working
|
||||
/// directory (a worktree lacks the untracked originals) or the home.
|
||||
fn native_claude(skill: &AgentSkill, cwd: &Path, home: Option<&Path>) -> bool {
|
||||
match skill.source {
|
||||
AgentSkillSource::ClaudeWorkspace => is_under(skill.path.0.as_path(), cwd),
|
||||
AgentSkillSource::ClaudeUser => home.is_some_and(|h| is_under(skill.path.0.as_path(), &h.join(".claude"))),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Copilot reads the repository's `.github/skills` and the home's `.copilot` itself.
|
||||
fn native_copilot(skill: &AgentSkill, cwd: &Path, home: Option<&Path>) -> bool {
|
||||
match skill.source {
|
||||
AgentSkillSource::GithubWorkspace => is_under(skill.path.0.as_path(), cwd),
|
||||
AgentSkillSource::CopilotUser => home.is_some_and(|h| is_under(skill.path.0.as_path(), &h.join(".copilot"))),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Codex reads its own folders itself.
|
||||
fn native_codex(skill: &AgentSkill, cwd: &Path, home: Option<&Path>) -> bool {
|
||||
match skill.source {
|
||||
AgentSkillSource::CodexWorkspace => is_under(skill.path.0.as_path(), cwd),
|
||||
AgentSkillSource::CodexUser => home.is_some_and(|h| is_under(skill.path.0.as_path(), &h.join(".codex"))),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn is_under(path: &Path, root: &Path) -> bool {
|
||||
path.starts_with(root)
|
||||
}
|
||||
|
||||
/// Puts `name` into the farm tree: a directory symlink where they work, a copy otherwise
|
||||
/// (Windows needs Developer Mode for directory symlinks).
|
||||
fn link_skill(link: &Path, target: &Path) -> std::io::Result<()> {
|
||||
let _ = std::fs::remove_file(link);
|
||||
if let Some(parent) = link.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
#[cfg(unix)]
|
||||
{
|
||||
std::os::unix::fs::symlink(target, link)
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
copy_dir_all(target, link)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn copy_dir_all(from: &Path, to: &Path) -> std::io::Result<()> {
|
||||
std::fs::create_dir_all(to)?;
|
||||
for entry in std::fs::read_dir(from)?.flatten() {
|
||||
let path = entry.path();
|
||||
let dest = to.join(entry.file_name());
|
||||
if path.is_dir() {
|
||||
copy_dir_all(&path, &dest)?;
|
||||
} else {
|
||||
std::fs::copy(&path, &dest)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Removes a task's farm (task deleted or archived); missing is fine.
|
||||
pub fn remove_farm(store_dir: &Path, task: &str) {
|
||||
let farm = farm_dir(store_dir, task);
|
||||
match std::fs::remove_dir_all(&farm) {
|
||||
Ok(()) => {}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(e) => tracing::warn!("removing the session skills folder {}: {e}", farm.display()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a task's staged skills live.
|
||||
pub fn farm_dir(store_dir: &Path, task: &str) -> PathBuf {
|
||||
store_dir.join("session-skills").join(sanitized(task))
|
||||
}
|
||||
|
||||
/// A task id is a uuid, but never trust it with a path segment.
|
||||
fn sanitized(id: &str) -> String {
|
||||
id.chars().filter(|c| c.is_ascii_alphanumeric() || *c == '-').collect()
|
||||
}
|
||||
|
||||
/// The `/` menu's skills: the active ones as commands (the agent's own listing wins on a
|
||||
/// name clash). `Off` ones drop out everywhere; an ACP agent gets no other enforcement, so
|
||||
/// `slashOnly` ones stay listed — there is nothing to hold them back with.
|
||||
pub fn menu_commands(offered: Vec<AgentCommand>, states: &[AgentSkillState]) -> Vec<AgentCommand> {
|
||||
let extra = states
|
||||
.iter()
|
||||
.filter(|s| s.mode != AgentSkillMode::Off)
|
||||
.map(|s| AgentCommand {
|
||||
name: s.skill.name.clone(),
|
||||
description: s.skill.description.clone(),
|
||||
hint: None,
|
||||
source: AgentCommandSource::Skill,
|
||||
})
|
||||
.collect();
|
||||
merge(offered, extra)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -703,231 +333,4 @@ mod tests {
|
||||
assert_eq!(f.get("name"), Some("quoted"));
|
||||
assert_eq!(truncate(&"é".repeat(MAX_DESCRIPTION + 5)).chars().count(), MAX_DESCRIPTION + 1);
|
||||
}
|
||||
|
||||
fn skill(name: &str, source: AgentSkillSource, root: &Path) -> AgentSkill {
|
||||
AgentSkill {
|
||||
name: name.into(),
|
||||
description: format!("{name} does things"),
|
||||
path: root.join(name).into(),
|
||||
source,
|
||||
valid: true,
|
||||
warnings: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn policy(mode: AgentSkillMode) -> Option<AgentSkillPolicy> {
|
||||
Some(AgentSkillPolicy { mode })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hub_discovery_scans_every_root_and_collapses_symlinks() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let home = tmp.path().join("home");
|
||||
let repo = tmp.path().join("work/app");
|
||||
std::fs::create_dir_all(&repo).unwrap();
|
||||
write(&repo.join(".agents/skills/dep/SKILL.md"), "---\nname: dep\ndescription: From the standard root\n---\n");
|
||||
write(&repo.join(".openidea/skills/local/SKILL.md"), "---\nname: local\ndescription: OpenIDEA's own\n---\n");
|
||||
write(&repo.join(".claude/skills/claudey/SKILL.md"), "---\nname: claudey\ndescription: Claude's\n---\n");
|
||||
write(&repo.join(".github/skills/gh/SKILL.md"), "---\nname: gh\ndescription: Copilot's repo one\n---\n");
|
||||
write(
|
||||
&home.join(".agents/skills/shared/SKILL.md"),
|
||||
"---\nname: shared\ndescription: From npx skills add\n---\n",
|
||||
);
|
||||
write(&home.join(".codex/skills/codexy/SKILL.md"), "---\nname: codexy\ndescription: Codex's\n---\n");
|
||||
write(&home.join(".cursor/skills/cursory/SKILL.md"), "---\nname: cursory\ndescription: Cursor's\n---\n");
|
||||
// A symlink to `dep` in the home (the same canonical folder): collapsed.
|
||||
#[cfg(unix)]
|
||||
{
|
||||
std::fs::create_dir_all(home.join(".claude/skills")).unwrap();
|
||||
std::os::unix::fs::symlink(repo.join(".agents/skills/dep"), home.join(".claude/skills/dep")).unwrap();
|
||||
}
|
||||
// Hidden folders and files are not skills.
|
||||
write(&repo.join(".agents/skills/.stash/SKILL.md"), "---\nname: hidden\ndescription: x\n---\n");
|
||||
write(&repo.join(".agents/skills/loose.txt"), "not a folder");
|
||||
// Same name from a lower-precedence source: the workspace one wins.
|
||||
write(&home.join(".cursor/skills/local/SKILL.md"), "---\nname: local\ndescription: from cursor\n---\n");
|
||||
|
||||
let found = discover_skills(&repo, Some(&home));
|
||||
assert_eq!(
|
||||
found.iter().map(|s| (s.name.as_str(), s.source)).collect::<Vec<_>>(),
|
||||
[
|
||||
("dep", AgentSkillSource::Workspace),
|
||||
("local", AgentSkillSource::Workspace),
|
||||
("claudey", AgentSkillSource::ClaudeWorkspace),
|
||||
("gh", AgentSkillSource::GithubWorkspace),
|
||||
("shared", AgentSkillSource::User),
|
||||
("codexy", AgentSkillSource::CodexUser),
|
||||
("cursory", AgentSkillSource::CursorUser),
|
||||
],
|
||||
"symlinks collapse and the first of a name wins"
|
||||
);
|
||||
assert!(found.iter().all(|s| s.valid), "{:?}", found.iter().flat_map(|s| &s.warnings).collect::<Vec<_>>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hub_discovery_validates_and_reports() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let repo = tmp.path().join("app");
|
||||
std::fs::create_dir_all(&repo).unwrap();
|
||||
write(&repo.join(".agents/skills/bad-name/SKILL.md"), "---\nname: Bad_Name\ndescription: x\n---\n");
|
||||
write(&repo.join(".agents/skills/no-desc/SKILL.md"), "---\nname: no-desc\n---\n");
|
||||
write(
|
||||
&repo.join(".agents/skills/verbose/SKILL.md"),
|
||||
&format!("---\nname: verbose\ndescription: {}\n---\n", "x".repeat(MAX_SKILL_DESCRIPTION + 1)),
|
||||
);
|
||||
|
||||
let found = discover_skills(&repo, None);
|
||||
let by = |n: &str| found.iter().find(|s| s.name == n).unwrap();
|
||||
assert!(!by("Bad_Name").valid && !by("Bad_Name").warnings.is_empty());
|
||||
assert!(!by("no-desc").valid && by("no-desc").warnings.len() == 1);
|
||||
assert!(!by("verbose").valid);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hub_resolution_precedence_and_trust() {
|
||||
let root = PathBuf::from("/r");
|
||||
let ws = skill("tdd", AgentSkillSource::Workspace, &root);
|
||||
let user = skill("lint", AgentSkillSource::User, &root);
|
||||
let claude = skill("claudey", AgentSkillSource::ClaudeWorkspace, &root);
|
||||
let session = BTreeMap::from([("tdd".to_owned(), AgentSkillMode::Off)]);
|
||||
let workspace = BTreeMap::from([
|
||||
("tdd".to_owned(), policy(AgentSkillMode::SlashOnly).unwrap()),
|
||||
("lint".to_owned(), policy(AgentSkillMode::Off).unwrap()),
|
||||
]);
|
||||
let user_policies = BTreeMap::from([
|
||||
("lint".to_owned(), policy(AgentSkillMode::SlashOnly).unwrap()),
|
||||
("claudey".to_owned(), policy(AgentSkillMode::Auto).unwrap()),
|
||||
]);
|
||||
|
||||
// Session > workspace policy > user policy.
|
||||
let resolved = resolve(vec![ws.clone(), user.clone()], Some(&session), &workspace, &user_policies, true);
|
||||
assert_eq!((resolved[0].mode, resolved[0].origin), (AgentSkillMode::Off, AgentSkillOrigin::Session));
|
||||
assert_eq!((resolved[1].mode, resolved[1].origin), (AgentSkillMode::Off, AgentSkillOrigin::Workspace));
|
||||
|
||||
// Without a workspace policy the user's applies.
|
||||
let resolved = resolve(vec![user.clone()], None, &BTreeMap::new(), &user_policies, true);
|
||||
assert_eq!((resolved[0].mode, resolved[0].origin), (AgentSkillMode::SlashOnly, AgentSkillOrigin::User));
|
||||
|
||||
// Untrusted: the workspace's own skills stay off whatever the session chose, its
|
||||
// policies hold only when they turn a skill off, and user skills keep resolving.
|
||||
let resolved = resolve(vec![ws, user, claude], Some(&session), &workspace, &user_policies, false);
|
||||
assert_eq!((resolved[0].mode, resolved[0].origin), (AgentSkillMode::Off, AgentSkillOrigin::Trust));
|
||||
assert_eq!((resolved[1].mode, resolved[1].origin), (AgentSkillMode::Off, AgentSkillOrigin::Workspace));
|
||||
assert_eq!((resolved[2].mode, resolved[2].origin), (AgentSkillMode::Off, AgentSkillOrigin::Trust));
|
||||
}
|
||||
|
||||
fn listed(dir: &Path) -> Vec<String> {
|
||||
let mut names: Vec<String> =
|
||||
std::fs::read_dir(dir).unwrap().flatten().map(|e| e.file_name().to_string_lossy().into_owned()).collect();
|
||||
names.sort();
|
||||
names
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hub_staging_hands_each_cli_its_own_tree() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
// Discovery reports canonical paths (macOS's temp folder is a symlink).
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let home = root.join("home");
|
||||
let repo = root.join("app");
|
||||
std::fs::create_dir_all(&repo).unwrap();
|
||||
// The staged folders must exist: Windows copies them (symlinks need Developer Mode).
|
||||
for path in [
|
||||
repo.join(".agents/skills/tdd"),
|
||||
repo.join(".agents/skills/off"),
|
||||
repo.join(".github/skills/gh"),
|
||||
home.join(".agents/skills/lint"),
|
||||
home.join(".agents/skills/muted"),
|
||||
home.join(".codex/skills/codexy"),
|
||||
] {
|
||||
std::fs::create_dir_all(path).unwrap();
|
||||
}
|
||||
let states = resolve(
|
||||
vec![
|
||||
skill("tdd", AgentSkillSource::Workspace, &repo.join(".agents/skills")),
|
||||
skill("gh", AgentSkillSource::GithubWorkspace, &repo.join(".github/skills")),
|
||||
skill("lint", AgentSkillSource::User, &home.join(".agents/skills")),
|
||||
skill("codexy", AgentSkillSource::CodexUser, &home.join(".codex/skills")),
|
||||
skill("muted", AgentSkillSource::User, &home.join(".agents/skills")),
|
||||
skill("off", AgentSkillSource::Workspace, &repo.join(".agents/skills")),
|
||||
],
|
||||
None,
|
||||
&BTreeMap::from([("muted".to_owned(), policy(AgentSkillMode::SlashOnly).unwrap())]),
|
||||
&BTreeMap::from([("off".to_owned(), policy(AgentSkillMode::Off).unwrap())]),
|
||||
true,
|
||||
);
|
||||
|
||||
// Local (non-worktree) session: the project's GitHub skills are Copilot's own.
|
||||
let farm = farm_dir(&root.join("store"), "task-1");
|
||||
let delivery = stage(&farm, "claude", &states, &repo, Some(&home)).unwrap();
|
||||
assert_eq!(delivery.claude_add_dir.as_deref(), Some(farm.as_path()));
|
||||
let claude_tree = farm.join(".claude/skills");
|
||||
let staged = listed(&claude_tree);
|
||||
assert_eq!(
|
||||
staged,
|
||||
["codexy", "gh", "lint", "muted", "tdd"],
|
||||
"everything but the off one: none is native to Claude here, and slash-only needs the folder"
|
||||
);
|
||||
|
||||
let delivery = stage(&farm, "copilot", &states, &repo, Some(&home)).unwrap();
|
||||
assert_eq!(delivery.copilot_skill_directories, [farm.join("copilot").to_string_lossy().into_owned()]);
|
||||
assert_eq!(delivery.copilot_disabled_skills, ["muted", "off"]);
|
||||
let copilot_staged = listed(&farm.join("copilot"));
|
||||
assert_eq!(copilot_staged, ["codexy", "lint", "tdd"], "`gh` is native to a local Copilot session");
|
||||
assert_eq!(
|
||||
delivery.codex_off,
|
||||
[("off".to_owned(), repo.join(".agents/skills").join("off").to_string_lossy().into_owned())]
|
||||
);
|
||||
|
||||
// A worktree task: the repo's skills are untracked, so nothing is native any more.
|
||||
let worktree = root.join("wt");
|
||||
std::fs::create_dir_all(&worktree).unwrap();
|
||||
let _ = stage(&farm, "copilot", &states, &worktree, Some(&home)).unwrap();
|
||||
let copilot_staged = listed(&farm.join("copilot"));
|
||||
assert!(copilot_staged.contains(&"gh".to_string()));
|
||||
|
||||
// Slash-only reaches Claude as `user-invocable-only`, off as `off`.
|
||||
let delivery = stage(&farm, "claude", &states, &repo, Some(&home)).unwrap();
|
||||
let settings: serde_json::Value = serde_json::from_str(delivery.claude_settings.as_deref().unwrap()).unwrap();
|
||||
assert_eq!(settings["skillOverrides"]["muted"], "user-invocable-only");
|
||||
assert_eq!(settings["skillOverrides"]["off"], "off");
|
||||
|
||||
// Restaging after a session turned `lint` off drops its link and leaves the skill.
|
||||
let session = BTreeMap::from([("lint".to_owned(), AgentSkillMode::Off)]);
|
||||
let restated = resolve(
|
||||
states.iter().map(|s| s.skill.clone()).collect(),
|
||||
Some(&session),
|
||||
&BTreeMap::from([("muted".to_owned(), policy(AgentSkillMode::SlashOnly).unwrap())]),
|
||||
&BTreeMap::from([("off".to_owned(), policy(AgentSkillMode::Off).unwrap())]),
|
||||
true,
|
||||
);
|
||||
stage(&farm, "claude", &restated, &repo, Some(&home)).unwrap();
|
||||
assert_eq!(listed(&claude_tree), ["codexy", "gh", "muted", "tdd"]);
|
||||
assert!(home.join(".agents/skills/lint").is_dir());
|
||||
assert!(farm.join("copilot").is_dir(), "restaging Claude's tree leaves Copilot's alone");
|
||||
|
||||
// An ACP agent gets no farm.
|
||||
let delivery = stage(&farm, "cursor-acp", &states, &repo, Some(&home)).unwrap();
|
||||
assert_eq!(delivery, Delivery::default());
|
||||
|
||||
// The farm goes away with the task.
|
||||
remove_farm(&root.join("store"), "task-1");
|
||||
assert!(!farm.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hub_menu_filters_off_and_keeps_the_agents_own() {
|
||||
let root = PathBuf::from("/r");
|
||||
let states = resolve(
|
||||
vec![skill("tdd", AgentSkillSource::Workspace, &root), skill("lint", AgentSkillSource::User, &root)],
|
||||
Some(&BTreeMap::from([("lint".to_owned(), AgentSkillMode::Off)])),
|
||||
&BTreeMap::new(),
|
||||
&BTreeMap::new(),
|
||||
true,
|
||||
);
|
||||
let menu = menu_commands(vec![cmd("tdd", "from the agent itself")], &states);
|
||||
assert_eq!(names(&menu), ["tdd"]);
|
||||
assert_eq!(menu[0].description, "from the agent itself");
|
||||
assert_eq!(menu[0].source, AgentCommandSource::Skill);
|
||||
}
|
||||
}
|
||||
+239
-125
@@ -1010,6 +1010,7 @@ async fn commands_are_remembered_per_project_and_merged_with_skills_on_disk() {
|
||||
// Another project shares the settings but not the commands.
|
||||
let mgr_b = manager_at(&b, &models, Arc::new(FakeAgent::default()));
|
||||
let claude = mgr_b.providers().into_iter().find(|p| p.id == "claude").unwrap();
|
||||
assert_eq!(claude.config.len(), 2);
|
||||
assert!(claude.commands.is_empty());
|
||||
assert!(mgr_b.commands("claude", None).await.unwrap().is_empty());
|
||||
let mgr_a = manager_at(&a, &models, Arc::new(FakeAgent::default()));
|
||||
@@ -1196,6 +1197,7 @@ async fn a_task_runs_asks_for_permission_and_survives_a_restart() {
|
||||
}
|
||||
let providers = mgr.providers();
|
||||
let claude = providers.iter().find(|p| p.id == "claude").unwrap();
|
||||
assert_eq!(claude.config.iter().map(|o| o.id.as_str()).collect::<Vec<_>>(), ["model", "mode"]);
|
||||
assert_eq!(claude.commands.len(), 1);
|
||||
|
||||
// A new manager (IDE restart) finds the task and resumes its session without duplicating history.
|
||||
@@ -1204,6 +1206,7 @@ async fn a_task_runs_asks_for_permission_and_survives_a_restart() {
|
||||
let mgr2 = manager(tmp.path(), agent2.clone());
|
||||
assert_eq!(mgr2.entries(&task.id, None).unwrap().len(), 5);
|
||||
assert_eq!(mgr2.task(&task.id).unwrap().state.lock().task.title, "Lexer fix");
|
||||
assert_eq!(mgr2.providers().iter().find(|p| p.id == "claude").unwrap().config.len(), 2);
|
||||
mgr2.prompt(&task.id, text("again"), false).await.unwrap();
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
wait_for(&mgr2, &task.id, AgentStatus::Ready).await;
|
||||
@@ -2164,6 +2167,52 @@ async fn usage_limits_and_late_settings() {
|
||||
assert!(agent.calls.lock().iter().any(|c| c == "session/set_config_option \"high\""));
|
||||
let config = mgr.task(&task.id).unwrap().state.lock().task.config.clone();
|
||||
assert_eq!(config.iter().find(|o| o.id == "effort").unwrap().current.as_deref(), Some("high"));
|
||||
for _ in 0..100 {
|
||||
if mgr
|
||||
.shared
|
||||
.known
|
||||
.lock()
|
||||
.get("claude")
|
||||
.and_then(|k| k.thought_levels.get("big"))
|
||||
.and_then(|levels| levels.first())
|
||||
.and_then(|o| o.current.as_deref())
|
||||
== Some("high")
|
||||
{
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
assert_eq!(mgr.shared.known.lock()["claude"].thought_levels["big"][0].current.as_deref(), Some("high"));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn remembered_settings_drop_per_model_choices_for_the_next_task() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
// The effort list depends on the model: what the last session ran means nothing once
|
||||
// the user picks another model, so provider-wide defaults never include it.
|
||||
*agent.extra_options.lock() = vec![json!({"id": "effort", "category": "thought_level",
|
||||
"type": "select", "currentValue": "high",
|
||||
"options": [{"value": "low", "name": "Low"}, {"value": "high", "name": "High"}]})];
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("again"),
|
||||
provider: "claude".into(),
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
|
||||
let provider = mgr.providers().into_iter().find(|p| p.id == "claude").unwrap();
|
||||
assert!(provider.config.iter().all(|o| o.id != "effort"), "a per-model option isn't offered stale");
|
||||
let model = provider.config.iter().find(|o| o.id == "model").unwrap();
|
||||
assert_eq!(model.current.as_deref(), Some("big"), "the model choice survives");
|
||||
}
|
||||
|
||||
fn effort_options(levels: &[&str], current: &str) -> Vec<Value> {
|
||||
@@ -2171,6 +2220,51 @@ fn effort_options(levels: &[&str], current: &str) -> Vec<Value> {
|
||||
"options": levels.iter().map(|v| json!({"value": v, "name": v})).collect::<Vec<_>>()})]
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn thinking_levels_are_remembered_per_provider_and_model() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
*agent.model_options.lock() = HashMap::from([
|
||||
("big".into(), effort_options(&["low", "high"], "high")),
|
||||
("small".into(), effort_options(&["minimal", "medium"], "minimal")),
|
||||
("plain".into(), vec![]),
|
||||
]);
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("again"),
|
||||
provider: "claude".into(),
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
mgr.set_config(&task.id, "model", "small".into()).await.unwrap();
|
||||
mgr.set_config(&task.id, "effort", "medium".into()).await.unwrap();
|
||||
mgr.set_config(&task.id, "model", "plain".into()).await.unwrap();
|
||||
let p = mgr.providers().into_iter().find(|p| p.id == "claude").unwrap();
|
||||
let big = &p.thought_levels["big"][0];
|
||||
assert_eq!(big.current.as_deref(), Some("high"));
|
||||
assert_eq!(big.values.iter().map(|v| v.value.as_str()).collect::<Vec<_>>(), ["low", "high"]);
|
||||
let small = &p.thought_levels["small"][0];
|
||||
assert_eq!(small.current.as_deref(), Some("medium"));
|
||||
assert_eq!(small.values.iter().map(|v| v.value.as_str()).collect::<Vec<_>>(), ["minimal", "medium"]);
|
||||
assert!(p.thought_levels["plain"].is_empty());
|
||||
assert!(!p.thought_levels.contains_key("unknown"));
|
||||
assert!(mgr.providers().iter().find(|p| p.id == "codex").unwrap().thought_levels.is_empty());
|
||||
let saved: HashMap<String, Known> =
|
||||
serde_json::from_slice(&std::fs::read(&mgr.shared.paths.models_file).unwrap()).unwrap();
|
||||
assert_eq!(saved["claude"].thought_levels, p.thought_levels);
|
||||
mgr.shutdown();
|
||||
let restored = manager(tmp.path(), agent);
|
||||
assert_eq!(restored.providers().into_iter().find(|p| p.id == "claude").unwrap().thought_levels, p.thought_levels);
|
||||
restored.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn changing_an_idle_tasks_settings_keeps_its_models_effort_levels() {
|
||||
// Idle selections use cached model controls or discover them before the next prompt.
|
||||
@@ -2209,9 +2303,12 @@ async fn changing_an_idle_tasks_settings_keeps_its_models_effort_levels() {
|
||||
}
|
||||
restored.set_config(&task.id, "model", "big".into()).await.unwrap();
|
||||
restored.set_config(&task.id, option, value.into()).await.unwrap();
|
||||
let levels = restored.shared.paths.catalogs.cached(&restored.shared, "claude-acp").thought_levels;
|
||||
let big = levels.get("big").and_then(|levels| levels.first());
|
||||
assert_eq!(big.map(|o| o.values.len()), Some(2), "{option}: {levels:?}");
|
||||
let p = restored.providers().into_iter().find(|p| p.id == "claude-acp").unwrap();
|
||||
let big = p.thought_levels.get("big").and_then(|levels| levels.first());
|
||||
assert_eq!(big.map(|o| o.values.len()), Some(2), "{option}: {:?}", p.thought_levels);
|
||||
let saved: HashMap<String, Known> =
|
||||
serde_json::from_slice(&std::fs::read(&restored.shared.paths.models_file).unwrap()).unwrap();
|
||||
assert_eq!(saved["claude-acp"].thought_levels, p.thought_levels, "{option}");
|
||||
restored.shutdown();
|
||||
}
|
||||
}
|
||||
@@ -2444,6 +2541,100 @@ async fn upfront_effort_is_validated_after_changing_model_before_the_prompt() {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn unreported_model_switch_does_not_cache_the_previous_models_levels() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
*agent.extra_options.lock() = effort_options(&["low", "high"], "high");
|
||||
let mgr = manager(tmp.path(), agent);
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("again"),
|
||||
provider: "claude".into(),
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
mgr.set_config(&task.id, "model", "small".into()).await.unwrap();
|
||||
let p = mgr.providers().into_iter().find(|p| p.id == "claude").unwrap();
|
||||
assert!(!p.thought_levels.contains_key("small"));
|
||||
assert_eq!(p.thought_levels["big"][0].current.as_deref(), Some("high"));
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn cached_effort_is_not_sent_without_real_session_options() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
*agent.extra_options.lock() = effort_options(&["low", "high"], "low");
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let new = |config| NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("again"),
|
||||
provider: "claude".into(),
|
||||
config,
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
};
|
||||
let warm = mgr.create(new(vec![])).await.unwrap();
|
||||
wait_for(&mgr, &warm.id, AgentStatus::Ready).await;
|
||||
agent.calls.lock().clear();
|
||||
agent.empty_config.store(true, Ordering::Release);
|
||||
let task = mgr
|
||||
.create(new(vec![
|
||||
AgentConfigChoice { id: "model".into(), value: "big".into() },
|
||||
AgentConfigChoice { id: "effort".into(), value: "high".into() },
|
||||
]))
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
assert!(!agent.calls.lock().iter().any(|c| c == "session/set_config_option \"high\""));
|
||||
assert!(
|
||||
mgr.task(&task.id).unwrap().state.lock().task.config.iter().any(|o| o.id == "effort"),
|
||||
"remembered session settings remain visible until the agent refreshes them"
|
||||
);
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn reported_levels_refresh_even_without_a_model_option() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
*agent.extra_options.lock() = effort_options(&["low", "high"], "high");
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("again"),
|
||||
provider: "claude".into(),
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
for levels in [effort_options(&["minimal", "medium"], "medium"), vec![]] {
|
||||
agent.update("s1", json!({"sessionUpdate": "config_option_update", "configOptions": levels}));
|
||||
let expected = config::parse_options(&json!(levels));
|
||||
for _ in 0..100 {
|
||||
if mgr.shared.known.lock()["claude"].thought_levels["big"] == expected {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
assert_eq!(mgr.shared.known.lock()["claude"].thought_levels["big"], expected);
|
||||
}
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retry_updates_become_a_countdown() {
|
||||
let update =
|
||||
@@ -3001,6 +3192,49 @@ async fn a_failed_probe_is_retried_instead_of_remembered() {
|
||||
assert!(!mgr.shared.probes.lock().contains_key("claude"));
|
||||
}
|
||||
|
||||
/// A session report that changes the cached provider config notifies subscribers,
|
||||
/// so the composer re-lists models without waiting for the next task (#1490).
|
||||
/// Reports that change nothing stay silent.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn remembered_config_changes_notify_subscribers_once() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let events = Arc::new(Mutex::new(Vec::new()));
|
||||
let sink = events.clone();
|
||||
mgr.subscribe(Arc::new(move |e| sink.lock().push(e)));
|
||||
events.lock().clear();
|
||||
|
||||
let reported = config::options_of(&json!({ "configOptions": [
|
||||
{ "id": "model", "category": "model", "type": "select", "currentValue": "default",
|
||||
"options": [{ "value": "default" }, { "value": "custom-opus" }] },
|
||||
] }));
|
||||
mgr.shared.remember("claude", Some(&reported), None, Some("default"));
|
||||
assert!(
|
||||
events.lock().iter().any(|ev| matches!(ev, AgentEvent::Providers)),
|
||||
"a first report changing the cache notifies subscribers"
|
||||
);
|
||||
events.lock().clear();
|
||||
|
||||
// The same report again: the cache is unchanged, so subscribers hear nothing.
|
||||
mgr.shared.remember("claude", Some(&reported), None, Some("default"));
|
||||
assert!(events.lock().is_empty(), "an unchanged report must stay silent");
|
||||
|
||||
// A changed model list notifies again, and providers() serves the new list.
|
||||
let updated = config::options_of(&json!({ "configOptions": [
|
||||
{ "id": "model", "category": "model", "type": "select", "currentValue": "default",
|
||||
"options": [{ "value": "default" }, { "value": "custom-opus" }, { "value": "custom-sonnet" }] },
|
||||
] }));
|
||||
mgr.shared.remember("claude", Some(&updated), None, Some("default"));
|
||||
assert!(
|
||||
events.lock().iter().any(|ev| matches!(ev, AgentEvent::Providers)),
|
||||
"a changed model list notifies subscribers"
|
||||
);
|
||||
let claude = mgr.providers().into_iter().find(|p| p.id == "claude").unwrap();
|
||||
let model = claude.config.iter().find(|o| o.category.as_deref() == Some("model")).unwrap();
|
||||
let values: Vec<_> = model.values.iter().map(|v| v.value.as_str()).collect();
|
||||
assert_eq!(values, ["default", "custom-opus", "custom-sonnet"]);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn idle_agents_stop_and_resume_their_session_on_the_next_message() {
|
||||
let new = || NewAgentTask {
|
||||
@@ -3634,123 +3868,6 @@ async fn turn_changed(mgr: &AgentManager, id: &str) -> Vec<(String, ide_vcs::Cha
|
||||
changes.into_iter().map(|c| (c.rel_path, c.kind, c.added, c.removed)).collect()
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_task_lists_what_it_changed_in_a_nested_repository() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
for repo in [root.clone(), root.join("libs/validation")] {
|
||||
std::fs::create_dir_all(&repo).unwrap();
|
||||
std::fs::write(repo.join("a.txt"), "one\n").unwrap();
|
||||
for args in [&["init", "-q", "-b", "main"][..], &["add", "a.txt"], &["commit", "-q", "-m", "init"]] {
|
||||
let ok = std::process::Command::new("git")
|
||||
.args(["-c", "user.name=t", "-c", "user.email=t@t", "-c", "commit.gpgsign=false"])
|
||||
.args(args)
|
||||
.current_dir(&repo)
|
||||
.status()
|
||||
.unwrap()
|
||||
.success();
|
||||
assert!(ok, "{args:?}");
|
||||
}
|
||||
}
|
||||
let mgr = manager(&base.join("ide"), Arc::new(FakeAgent::default()));
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: Some(IpcPath(root.clone())),
|
||||
prompt: text("Hello"),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Local,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
one_turn(&mgr, &task.id, None, || {
|
||||
std::fs::write(root.join("a.txt"), "two\n").unwrap();
|
||||
std::fs::write(root.join("libs/validation/b.txt"), "new\n").unwrap();
|
||||
})
|
||||
.await;
|
||||
let changed: Vec<(String, Option<IpcPath>)> =
|
||||
mgr.changes(&task.id).await.unwrap().into_iter().map(|c| (c.rel_path, c.repo)).collect();
|
||||
assert_eq!(
|
||||
changed,
|
||||
[
|
||||
("a.txt".to_owned(), Some(IpcPath(root.clone()))),
|
||||
("libs/validation/b.txt".to_owned(), Some(IpcPath(root.join("libs/validation")))),
|
||||
]
|
||||
);
|
||||
mgr.rollback_changes(&task.id, None, AgentChangesView::SinceStart).await.unwrap();
|
||||
assert_eq!(std::fs::read_to_string(root.join("a.txt")).unwrap(), "one\n");
|
||||
assert!(!root.join("libs/validation/b.txt").exists());
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn the_last_turn_of_a_task_spans_nested_repositories() {
|
||||
use ide_vcs::ChangeKind::{Added, Modified};
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
let nested = root.join("libs/validation");
|
||||
let git = |repo: &Path, args: &[&str]| {
|
||||
let ok = std::process::Command::new("git")
|
||||
.args(["-c", "user.name=t", "-c", "user.email=t@t", "-c", "commit.gpgsign=false"])
|
||||
.args(args)
|
||||
.current_dir(repo)
|
||||
.status()
|
||||
.unwrap()
|
||||
.success();
|
||||
assert!(ok, "{args:?}");
|
||||
};
|
||||
for repo in [&root, &nested] {
|
||||
std::fs::create_dir_all(repo).unwrap();
|
||||
std::fs::write(repo.join("a.txt"), "one\n").unwrap();
|
||||
git(repo, &["init", "-q", "-b", "main"]);
|
||||
git(repo, &["add", "a.txt"]);
|
||||
git(repo, &["commit", "-q", "-m", "init"]);
|
||||
}
|
||||
let mgr = manager(&base.join("ide"), Arc::new(FakeAgent::default()));
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: Some(IpcPath(root.clone())),
|
||||
prompt: text("Hello"),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Local,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
one_turn(&mgr, &task.id, None, || std::fs::write(root.join("a.txt"), "two\n").unwrap()).await;
|
||||
one_turn(&mgr, &task.id, Some("more"), || {
|
||||
std::fs::write(nested.join("a.txt"), "two\n").unwrap();
|
||||
std::fs::write(nested.join("b.txt"), "new\n").unwrap();
|
||||
// Committed in the nested repository: still the turn's.
|
||||
std::fs::write(nested.join("c.txt"), "committed\n").unwrap();
|
||||
git(&nested, &["add", "c.txt"]);
|
||||
git(&nested, &["commit", "-q", "-m", "c"]);
|
||||
})
|
||||
.await;
|
||||
|
||||
// Only the second turn's files, from the nested repository, named from the project.
|
||||
assert_eq!(
|
||||
turn_changed(&mgr, &task.id).await,
|
||||
[
|
||||
("libs/validation/a.txt".into(), Modified, 1, 1),
|
||||
("libs/validation/b.txt".into(), Added, 1, 0),
|
||||
("libs/validation/c.txt".into(), Added, 1, 0),
|
||||
]
|
||||
);
|
||||
let repos: Vec<_> = mgr.turn_changes(&task.id).await.unwrap().into_iter().map(|c| c.repo).collect();
|
||||
assert_eq!(repos, [Some(IpcPath(nested.clone())), Some(IpcPath(nested.clone())), Some(IpcPath(nested.clone()))]);
|
||||
let then = mgr.base_text(&task.id, nested.join("a.txt"), AgentChangesView::LastTurn).await.unwrap();
|
||||
assert_eq!(then.as_deref(), Some("one\n"));
|
||||
|
||||
mgr.rollback_changes(&task.id, None, AgentChangesView::LastTurn).await.unwrap();
|
||||
assert_eq!(std::fs::read_to_string(nested.join("a.txt")).unwrap(), "one\n");
|
||||
assert!(!nested.join("b.txt").exists());
|
||||
assert_eq!(std::fs::read_to_string(root.join("a.txt")).unwrap(), "two\n", "the first turn's change stays");
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn the_last_turn_lists_and_rolls_back_only_its_own_changes() {
|
||||
use ide_vcs::ChangeKind::{Added, Deleted, Modified};
|
||||
@@ -4415,7 +4532,6 @@ async fn per_session_mcp_overrides_filter_session_and_reload_when_idle() {
|
||||
base: None,
|
||||
mcp_overrides: BTreeMap::from([("slack".into(), false)]),
|
||||
idle: false,
|
||||
skill_overrides: BTreeMap::new(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -4544,7 +4660,6 @@ async fn copilot_falls_back_to_acp_when_headless_probe_session_or_prompt_fails()
|
||||
base: None,
|
||||
mcp_overrides: BTreeMap::new(),
|
||||
idle: false,
|
||||
skill_overrides: BTreeMap::new(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -4570,7 +4685,6 @@ async fn copilot_falls_back_to_acp_when_headless_probe_session_or_prompt_fails()
|
||||
base: None,
|
||||
mcp_overrides: BTreeMap::new(),
|
||||
idle: false,
|
||||
skill_overrides: BTreeMap::new(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -4649,10 +4763,10 @@ done
|
||||
#[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, None);
|
||||
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, None).get("_meta").is_none());
|
||||
assert!(session_params("/p", &none).get("_meta").is_none());
|
||||
}
|
||||
@@ -25,98 +25,6 @@ fn discover(path: &Path) -> IdeResult<Option<Repo>> {
|
||||
Ok(repo)
|
||||
}
|
||||
|
||||
/// The repositories of a project with nested ones (an own `.git` under the project root, not a
|
||||
/// submodule), with the folder their files are named from: the root of the repository holding
|
||||
/// `cwd`, else `cwd`. `None` when only the repository holding `cwd` (if any) is there.
|
||||
fn nested_repos(cwd: &Path) -> IdeResult<Option<(PathBuf, Vec<Repo>)>> {
|
||||
let Ok(cwd) = dunce::canonicalize(cwd) else { return Ok(None) };
|
||||
let found = ide_vcs::Repos::discover(&cwd, &|_| false)?;
|
||||
if found.all().iter().all(|r| cwd.starts_with(r.root())) {
|
||||
return Ok(None);
|
||||
}
|
||||
let base = found.all().iter().map(|r| r.root()).filter(|r| cwd.starts_with(r)).max().unwrap_or(&cwd).to_path_buf();
|
||||
let mut repos = Vec::new();
|
||||
for r in found.all() {
|
||||
repos.extend(discover(r.root())?);
|
||||
}
|
||||
Ok(Some((base, repos)))
|
||||
}
|
||||
|
||||
/// Whether the project at `cwd` holds repositories nested in it: its changes are each one's.
|
||||
pub(crate) fn spans_repos(cwd: &Path) -> bool {
|
||||
nested_repos(cwd).is_ok_and(|r| r.is_some())
|
||||
}
|
||||
|
||||
/// The repositories a turn's files are in, and the folder those files are named from.
|
||||
struct TurnRepos {
|
||||
base: PathBuf,
|
||||
repos: Vec<Repo>,
|
||||
/// The project holds nested repositories: each one's `HEAD` is recorded on its own.
|
||||
nested: bool,
|
||||
}
|
||||
|
||||
impl TurnRepos {
|
||||
fn of(cwd: &Path) -> IdeResult<Option<Self>> {
|
||||
if let Some((base, repos)) = nested_repos(cwd)? {
|
||||
return Ok(Some(Self { base, repos, nested: true }));
|
||||
}
|
||||
Ok(discover(cwd)?.map(|repo| Self { base: repo.root().to_path_buf(), repos: vec![repo], nested: false }))
|
||||
}
|
||||
|
||||
/// The innermost repository holding `path`.
|
||||
fn owner(&self, path: &Path) -> Option<&Repo> {
|
||||
self.repos.iter().filter(|r| path.starts_with(r.root())).max_by_key(|r| r.root().as_os_str().len())
|
||||
}
|
||||
|
||||
/// `repo`'s `HEAD` as the turn `start` began.
|
||||
fn head_then<'a>(&self, start: &'a TurnStart, repo: &Repo) -> Option<&'a str> {
|
||||
if self.nested { start.heads.get(&root_key(repo.root())) } else { start.head.as_ref() }.map(String::as_str)
|
||||
}
|
||||
}
|
||||
|
||||
fn root_key(root: &Path) -> String {
|
||||
root.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
/// `path` as a task in `base` names it, if it is not in a repository nested below `repo` (that
|
||||
/// one lists it itself; to `repo` its folder is untracked).
|
||||
fn nested_rel(base: &Path, repo: &Repo, roots: &[PathBuf], path: &Path) -> Option<String> {
|
||||
let rel = path.strip_prefix(base).ok()?;
|
||||
if path.is_dir()
|
||||
|| roots.iter().any(|n| n.as_path() != repo.root() && n.starts_with(repo.root()) && path.starts_with(n))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some(rel.to_string_lossy().replace('\\', "/"))
|
||||
}
|
||||
|
||||
/// The uncommitted changes in every repository of the project, against each one's `HEAD`.
|
||||
fn nested_changes(cwd: &Path) -> IdeResult<Vec<AgentChange>> {
|
||||
let Some((base, repos)) = nested_repos(cwd)? else { return Ok(Vec::new()) };
|
||||
let roots: Vec<PathBuf> = repos.iter().map(|r| r.root().to_path_buf()).collect();
|
||||
let mut out: Vec<AgentChange> = Vec::new();
|
||||
for repo in &repos {
|
||||
let listed = match repo.head()?.1 {
|
||||
Some(head) => changes(repo.root(), &head)?,
|
||||
None => {
|
||||
repo.status()?.into_iter().filter(|s| s.path.is_file()).map(|s| added(s.path, s.rel_path)).collect()
|
||||
}
|
||||
};
|
||||
for mut c in listed {
|
||||
let Some(rel) = nested_rel(&base, repo, &roots, &c.path.0) else { continue };
|
||||
if out.iter().any(|o| o.path == c.path) {
|
||||
continue;
|
||||
}
|
||||
c.rel_path = rel;
|
||||
c.old_path = None;
|
||||
c.repo = Some(IpcPath(repo.root().to_path_buf()));
|
||||
out.push(c);
|
||||
}
|
||||
}
|
||||
out.sort_by(|a, b| a.rel_path.cmp(&b.rel_path));
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn repo_at(path: &Path) -> IdeResult<Repo> {
|
||||
discover(path)?.ok_or_else(|| IdeError::unavailable(format!("{} is not in a git repository", path.display())))
|
||||
}
|
||||
@@ -130,9 +38,6 @@ pub(crate) fn head_of(path: &Path) -> IdeResult<(String, String)> {
|
||||
|
||||
/// `HEAD`'s commit in `cwd`, `None` outside a repository or before its first commit.
|
||||
pub(crate) fn head_commit(cwd: &Path) -> IdeResult<Option<String>> {
|
||||
if spans_repos(cwd) {
|
||||
return Ok(Some("HEAD".to_owned()));
|
||||
}
|
||||
match discover(cwd)? {
|
||||
Some(repo) => Ok(repo.head()?.1),
|
||||
None => Ok(None),
|
||||
@@ -222,7 +127,6 @@ pub(crate) fn changes(cwd: &Path, base: &str) -> IdeResult<Vec<AgentChange>> {
|
||||
added,
|
||||
removed,
|
||||
old_path: f.old_path,
|
||||
repo: None,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
@@ -239,9 +143,6 @@ pub(crate) fn changes(cwd: &Path, base: &str) -> IdeResult<Vec<AgentChange>> {
|
||||
/// Files renamed since `rev`, by their new repository-relative path: the old path, as a deletion
|
||||
/// to roll back along with the rename.
|
||||
pub(crate) fn rename_sources(cwd: &Path, rev: &str) -> IdeResult<BTreeMap<String, AgentChange>> {
|
||||
if spans_repos(cwd) {
|
||||
return Ok(BTreeMap::new());
|
||||
}
|
||||
let Some(repo) = discover(cwd)? else { return Ok(BTreeMap::new()) };
|
||||
let root = repo.root().to_path_buf();
|
||||
Ok(repo
|
||||
@@ -256,7 +157,6 @@ pub(crate) fn rename_sources(cwd: &Path, rev: &str) -> IdeResult<BTreeMap<String
|
||||
added: 0,
|
||||
removed: 0,
|
||||
old_path: None,
|
||||
repo: None,
|
||||
};
|
||||
Some((f.path, source))
|
||||
})
|
||||
@@ -265,7 +165,7 @@ pub(crate) fn rename_sources(cwd: &Path, rev: &str) -> IdeResult<BTreeMap<String
|
||||
|
||||
fn added(path: IpcPath, rel_path: String) -> AgentChange {
|
||||
let added = std::fs::read_to_string(&*path).map_or(0, |t| t.lines().count() as u32);
|
||||
AgentChange { path, rel_path, kind: ChangeKind::Added, added, removed: 0, old_path: None, repo: None }
|
||||
AgentChange { path, rel_path, kind: ChangeKind::Added, added, removed: 0, old_path: None }
|
||||
}
|
||||
|
||||
/// The commits from `base` (exclusive) to `head` (inclusive) in `cwd`, newest first, each
|
||||
@@ -301,7 +201,6 @@ pub(crate) fn commits(cwd: &Path, base: &str, head: &str) -> IdeResult<Vec<Agent
|
||||
added,
|
||||
removed,
|
||||
old_path: f.old_path,
|
||||
repo: None,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
@@ -367,9 +266,6 @@ impl TaskBase {
|
||||
pub(crate) fn changes(&self, before: &BTreeMap<String, Stamp>) -> IdeResult<Vec<AgentChange>> {
|
||||
let (cwd, start) = match self {
|
||||
Self::Worktree { cwd, base } => return Ok(without_untouched(changes(cwd, base)?, before)),
|
||||
Self::Local { cwd, .. } if spans_repos(cwd) => {
|
||||
return Ok(without_untouched(nested_changes(cwd)?, before));
|
||||
}
|
||||
Self::Local { cwd, start } => (cwd, start.as_deref()),
|
||||
};
|
||||
let Some(repo) = discover(cwd)? else { return Ok(Vec::new()) };
|
||||
@@ -428,9 +324,6 @@ impl TaskBase {
|
||||
/// reads cannot put a file in both lists.
|
||||
pub(crate) fn grouped_changes(&self, before: &BTreeMap<String, Stamp>) -> IdeResult<AgentChanges> {
|
||||
let cwd = self.cwd();
|
||||
if spans_repos(cwd) {
|
||||
return Ok(AgentChanges { uncommitted: self.changes(before)?, commits: Vec::new() });
|
||||
}
|
||||
let Some(repo) = discover(cwd)? else { return Ok(AgentChanges::default()) };
|
||||
let head = repo.head()?.1;
|
||||
let uncommitted = match &head {
|
||||
@@ -460,8 +353,6 @@ impl TaskBase {
|
||||
pub(crate) fn rev(&self) -> IdeResult<Option<String>> {
|
||||
let (cwd, start) = match self {
|
||||
Self::Worktree { base, .. } => return Ok(Some(base.clone())),
|
||||
// Each repository goes back to its own `HEAD`.
|
||||
Self::Local { cwd, .. } if spans_repos(cwd) => return Ok(Some("HEAD".to_owned())),
|
||||
Self::Local { cwd, start } => (cwd, start.as_deref()),
|
||||
};
|
||||
let Some(repo) = discover(cwd)? else { return Ok(None) };
|
||||
@@ -654,18 +545,6 @@ pub(crate) fn stamp(path: &Path) -> Stamp {
|
||||
pub(crate) fn snapshot(cwd: &Path) -> IdeResult<BTreeMap<String, Stamp>> {
|
||||
// Paths and stamps only: no diff and no line counts, which read every untracked file
|
||||
// and held up starting a task in a checkout with many of them.
|
||||
if let Some((base, repos)) = nested_repos(cwd)? {
|
||||
let roots: Vec<PathBuf> = repos.iter().map(|r| r.root().to_path_buf()).collect();
|
||||
let mut out = BTreeMap::new();
|
||||
for repo in &repos {
|
||||
for s in repo.status()? {
|
||||
if let Some(rel) = nested_rel(&base, repo, &roots, &s.path) {
|
||||
out.insert(rel, stamp(&s.path));
|
||||
}
|
||||
}
|
||||
}
|
||||
return Ok(out);
|
||||
}
|
||||
let Some(repo) = Repo::discover(cwd)? else { return Ok(BTreeMap::new()) };
|
||||
Ok(repo.status()?.into_iter().map(|s| (s.rel_path, stamp(&s.path))).collect())
|
||||
}
|
||||
@@ -708,16 +587,10 @@ fn saved_name(rel: &str) -> String {
|
||||
/// into `dir`, so rolling back the task's changes to them restores the user's own edits.
|
||||
/// Whether anything was saved.
|
||||
pub(crate) fn save_before(cwd: &Path, before: &BTreeMap<String, Stamp>, dir: &Path) -> IdeResult<bool> {
|
||||
let root = match nested_repos(cwd)? {
|
||||
Some((base, _)) => base,
|
||||
None => match Repo::discover(cwd)? {
|
||||
Some(repo) => repo.root().to_path_buf(),
|
||||
None => return Ok(false),
|
||||
},
|
||||
};
|
||||
let Some(repo) = Repo::discover(cwd)? else { return Ok(false) };
|
||||
let mut saved = false;
|
||||
for (rel, stamp) in before {
|
||||
let path = root.join(rel);
|
||||
let path = repo.root().join(rel);
|
||||
if stamp.is_none() || !std::fs::metadata(&path).is_ok_and(|m| m.is_file() && m.len() <= SAVED_MAX) {
|
||||
continue;
|
||||
}
|
||||
@@ -752,8 +625,7 @@ pub(crate) fn restore(
|
||||
}
|
||||
None => match rev {
|
||||
Some(rev) => {
|
||||
let at = change.repo.as_ref().map_or(cwd, |r| r.0.as_path());
|
||||
let repo = Repo::discover(at)?.ok_or_else(|| IdeError::invalid("not in a git repository"))?;
|
||||
let repo = Repo::discover(cwd)?.ok_or_else(|| IdeError::invalid("not in a git repository"))?;
|
||||
repo.file_bytes_at(&change.path.0, Some(rev))?
|
||||
}
|
||||
None => None,
|
||||
@@ -793,9 +665,6 @@ pub(crate) struct TurnStart {
|
||||
/// `HEAD` then (`None` outside a repository or before its first commit).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub head: Option<String>,
|
||||
/// With nested repositories, each one's `HEAD` then, by its root.
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub heads: BTreeMap<String, String>,
|
||||
/// The files already changed then, stamped.
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub before: BTreeMap<String, Stamp>,
|
||||
@@ -811,16 +680,8 @@ pub(crate) struct TurnStart {
|
||||
/// The copies `previous` saved of files unchanged since are kept rather than made again, so
|
||||
/// starting a turn copies little more than what the turn before it changed.
|
||||
pub(crate) fn start_turn(cwd: &Path, dir: &Path, previous: Option<&TurnStart>) -> IdeResult<TurnStart> {
|
||||
let Some(at) = TurnRepos::of(cwd)? else { return Ok(TurnStart::default()) };
|
||||
let mut heads = BTreeMap::new();
|
||||
let head = if at.nested {
|
||||
for repo in &at.repos {
|
||||
heads.extend(repo.head()?.1.map(|h| (root_key(repo.root()), h)));
|
||||
}
|
||||
None
|
||||
} else {
|
||||
at.repos[0].head()?.1
|
||||
};
|
||||
let Some(repo) = discover(cwd)? else { return Ok(TurnStart::default()) };
|
||||
let head = repo.head()?.1;
|
||||
// As the turn's end is read, so the two compare.
|
||||
let before = snapshot(cwd)?;
|
||||
let mut saved = BTreeSet::new();
|
||||
@@ -841,7 +702,7 @@ pub(crate) fn start_turn(cwd: &Path, dir: &Path, previous: Option<&TurnStart>) -
|
||||
}
|
||||
}
|
||||
for (rel, stamp) in &before {
|
||||
let path = at.base.join(rel);
|
||||
let path = repo.root().join(rel);
|
||||
if stamp.is_none()
|
||||
|| saved.contains(rel)
|
||||
|| !std::fs::metadata(&path).is_ok_and(|m| m.is_file() && m.len() <= SAVED_MAX)
|
||||
@@ -854,7 +715,7 @@ pub(crate) fn start_turn(cwd: &Path, dir: &Path, previous: Option<&TurnStart>) -
|
||||
saved.insert(rel.clone());
|
||||
}
|
||||
}
|
||||
Ok(TurnStart { head, heads, before, saved, changed: None })
|
||||
Ok(TurnStart { head, before, saved, changed: None })
|
||||
}
|
||||
|
||||
/// The files that changed in `cwd` since the turn `start` began: in the working tree (as
|
||||
@@ -863,25 +724,20 @@ pub(crate) fn changed_in_turn(cwd: &Path, start: &TurnStart) -> IdeResult<(Vec<S
|
||||
let end = snapshot(cwd)?;
|
||||
let worktree = changed_between(&start.before, &end);
|
||||
let mut all: BTreeSet<String> = worktree.iter().cloned().collect();
|
||||
let Some(at) = TurnRepos::of(cwd)? else { return Ok((worktree, all)) };
|
||||
for repo in &at.repos {
|
||||
let (Some(from), Some(to)) = (at.head_then(start, repo), repo.head()?.1) else { continue };
|
||||
if from == to {
|
||||
continue;
|
||||
}
|
||||
// Named from the base, as the working tree's files are.
|
||||
let prefix = rel_in(&at.base, repo.root())?;
|
||||
let named = |rel: String| if prefix.is_empty() { rel } else { format!("{prefix}/{rel}") };
|
||||
if let Some(repo) = discover(cwd)?
|
||||
&& let (Some(from), Some(to)) = (&start.head, repo.head()?.1)
|
||||
&& *from != to
|
||||
{
|
||||
for f in repo.diff_revisions(from, &to)? {
|
||||
all.extend(f.old_path.map(named));
|
||||
all.insert(named(f.path));
|
||||
all.extend(f.old_path);
|
||||
all.insert(f.path);
|
||||
}
|
||||
}
|
||||
Ok((worktree, all))
|
||||
}
|
||||
|
||||
/// The content of `rel` as the turn `start` began (`None`: no file), its copies in `dir`.
|
||||
fn at_turn_start(at: &TurnRepos, rel: &str, start: &TurnStart, dir: &Path) -> IdeResult<Option<Vec<u8>>> {
|
||||
fn at_turn_start(repo: &Repo, rel: &str, start: &TurnStart, dir: &Path) -> IdeResult<Option<Vec<u8>>> {
|
||||
match start.before.get(rel) {
|
||||
Some(None) => Ok(None),
|
||||
Some(Some(_)) => match start.saved.contains(rel).then(|| saved_copy(dir, rel)).flatten() {
|
||||
@@ -890,13 +746,10 @@ fn at_turn_start(at: &TurnRepos, rel: &str, start: &TurnStart, dir: &Path) -> Id
|
||||
"{rel} had changes when the turn started that weren't saved; roll it back in Git instead"
|
||||
))),
|
||||
},
|
||||
None => {
|
||||
let path = at.base.join(rel);
|
||||
match at.owner(&path).and_then(|repo| Some((repo, at.head_then(start, repo)?))) {
|
||||
Some((repo, head)) => repo.file_bytes_at(&path, Some(head)),
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
None => match &start.head {
|
||||
Some(head) => repo.file_bytes_at(&repo.root().join(rel), Some(head)),
|
||||
None => Ok(None),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -918,13 +771,13 @@ pub(crate) fn turn_changes(
|
||||
dir: &Path,
|
||||
changed: &BTreeSet<String>,
|
||||
) -> IdeResult<Vec<AgentChange>> {
|
||||
let Some(at) = TurnRepos::of(cwd)? else { return Ok(Vec::new()) };
|
||||
let Some(repo) = discover(cwd)? else { return Ok(Vec::new()) };
|
||||
let mut out = Vec::new();
|
||||
for rel in changed {
|
||||
let path = at.base.join(rel);
|
||||
let path = repo.root().join(rel);
|
||||
// A folder (a submodule, say) or a file that can't be read has nothing to compare.
|
||||
let Some(now) = existing(&path) else { continue };
|
||||
let (kind, (added, removed)) = match at_turn_start(&at, rel, start, dir) {
|
||||
let (kind, (added, removed)) = match at_turn_start(&repo, rel, start, dir) {
|
||||
Ok(then) if then == now => continue,
|
||||
Ok(then) => {
|
||||
let kind = match (&then, &now) {
|
||||
@@ -937,29 +790,19 @@ pub(crate) fn turn_changes(
|
||||
// Its start wasn't saved: listed, without counts.
|
||||
Err(_) => (ChangeKind::Modified, (0, 0)),
|
||||
};
|
||||
out.push(AgentChange {
|
||||
rel_path: rel.clone(),
|
||||
kind,
|
||||
added,
|
||||
removed,
|
||||
old_path: None,
|
||||
repo: at.nested.then(|| at.owner(&path).map(|r| IpcPath(r.root().to_path_buf()))).flatten(),
|
||||
path: IpcPath(path),
|
||||
});
|
||||
out.push(AgentChange { path: IpcPath(path), rel_path: rel.clone(), kind, added, removed, old_path: None });
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The text of `path` as the turn `start` began, `None` when there was no file.
|
||||
pub(crate) fn turn_text(cwd: &Path, path: &Path, start: &TurnStart, dir: &Path) -> IdeResult<Option<String>> {
|
||||
let Some(at) = TurnRepos::of(cwd)? else { return Ok(None) };
|
||||
let rel = rel_in(&at.base, path)?;
|
||||
if !start.before.contains_key(&rel)
|
||||
&& let Some(head) = at.owner(&at.base.join(&rel)).and_then(|repo| at.head_then(start, repo))
|
||||
{
|
||||
let Some(repo) = discover(cwd)? else { return Ok(None) };
|
||||
let rel = rel_in(repo.root(), path)?;
|
||||
if let (None, Some(head)) = (start.before.get(&rel), &start.head) {
|
||||
return file_at(cwd, path, head);
|
||||
}
|
||||
let Some(bytes) = at_turn_start(&at, &rel, start, dir)? else { return Ok(None) };
|
||||
let Some(bytes) = at_turn_start(&repo, &rel, start, dir)? else { return Ok(None) };
|
||||
let encoding = match ide_vfs::load_text(path) {
|
||||
Ok(loaded) => encoding_rs::Encoding::for_label(loaded.encoding.as_bytes()).unwrap_or(encoding_rs::UTF_8),
|
||||
Err(_) => ide_vfs::detect_encoding(&bytes, None),
|
||||
@@ -985,15 +828,12 @@ fn rel_in(root: &Path, path: &Path) -> IdeResult<String> {
|
||||
|
||||
/// Puts `change` back as it was when the turn `start` began.
|
||||
pub(crate) fn restore_turn(cwd: &Path, start: &TurnStart, dir: &Path, change: &AgentChange) -> IdeResult<()> {
|
||||
let at = TurnRepos::of(cwd)?
|
||||
.ok_or_else(|| IdeError::unavailable(format!("{} is not in a git repository", cwd.display())))?;
|
||||
put(&change.path.0, at_turn_start(&at, &change.rel_path, start, dir)?)
|
||||
let repo = repo_at(cwd)?;
|
||||
put(&change.path.0, at_turn_start(&repo, &change.rel_path, start, dir)?)
|
||||
}
|
||||
|
||||
pub(crate) fn file_at(cwd: &Path, path: &Path, rev: &str) -> IdeResult<Option<String>> {
|
||||
// With nested repositories, the file's own one.
|
||||
let at = if spans_repos(cwd) { path.parent().unwrap_or(cwd) } else { cwd };
|
||||
let Some(repo) = discover(at)? else { return Ok(None) };
|
||||
let Some(repo) = discover(cwd)? else { return Ok(None) };
|
||||
let encoding = match ide_vfs::load_text(path) {
|
||||
Ok(loaded) => encoding_rs::Encoding::for_label(loaded.encoding.as_bytes()).unwrap_or(encoding_rs::UTF_8),
|
||||
Err(_) => ide_vfs::detect_encoding(&repo.file_bytes_at(path, Some(rev))?.unwrap_or_default(), None),
|
||||
@@ -1122,54 +962,6 @@ mod tests {
|
||||
assert!(ok, "git {args:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_project_with_nested_repositories_sees_changes_in_each_one() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let (nested, deeper) = (root.join("libs/validation"), root.join("libs/validation/pkg/sdk"));
|
||||
for repo in [&root, &nested, &deeper] {
|
||||
std::fs::create_dir_all(repo).unwrap();
|
||||
git(repo, &["init", "-q", "-b", "main"]);
|
||||
std::fs::write(repo.join("a.txt"), "one\n").unwrap();
|
||||
git(repo, &["add", "a.txt"]);
|
||||
git(repo, &["commit", "-q", "-m", "init"]);
|
||||
}
|
||||
assert!(spans_repos(&root));
|
||||
std::fs::write(root.join("mine.txt"), "the user's\n").unwrap();
|
||||
let before = snapshot(&root).unwrap();
|
||||
assert_eq!(before.keys().collect::<Vec<_>>(), ["mine.txt"]);
|
||||
|
||||
std::fs::write(root.join("a.txt"), "two\n").unwrap();
|
||||
std::fs::write(nested.join("a.txt"), "two\n").unwrap();
|
||||
std::fs::write(nested.join("b.txt"), "new\n").unwrap();
|
||||
std::fs::write(deeper.join("a.txt"), "two\n").unwrap();
|
||||
let at = TaskBase::Local { cwd: root.clone(), start: None };
|
||||
let changed = at.changes(&before).unwrap();
|
||||
let listed: Vec<(&str, &Path)> =
|
||||
changed.iter().map(|c| (c.rel_path.as_str(), c.repo.as_ref().unwrap().0.as_path())).collect();
|
||||
assert_eq!(
|
||||
listed,
|
||||
[
|
||||
("a.txt", root.as_path()),
|
||||
("libs/validation/a.txt", nested.as_path()),
|
||||
("libs/validation/b.txt", nested.as_path()),
|
||||
("libs/validation/pkg/sdk/a.txt", deeper.as_path()),
|
||||
]
|
||||
);
|
||||
assert_eq!(at.grouped_changes(&before).unwrap().uncommitted.len(), 4);
|
||||
assert_eq!(file_at(&root, &nested.join("a.txt"), "HEAD").unwrap().as_deref(), Some("one\n"));
|
||||
|
||||
let rev = at.rev().unwrap();
|
||||
for change in &changed {
|
||||
restore(&root, rev.as_deref(), change, &before, None).unwrap();
|
||||
}
|
||||
for repo in [&root, &nested, &deeper] {
|
||||
assert_eq!(std::fs::read_to_string(repo.join("a.txt")).unwrap(), "one\n");
|
||||
}
|
||||
assert!(!nested.join("b.txt").exists());
|
||||
assert!(root.join("mine.txt").exists(), "the user's own change stays");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn worktree_changes_are_listed_against_the_base() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -102,8 +102,6 @@ pub enum IdeEvent {
|
||||
WorkspaceEditApplied {
|
||||
id: u32,
|
||||
paths: Vec<crate::IpcPath>,
|
||||
/// Files the edit renamed, as the edit named them: editors open on them follow.
|
||||
moves: Vec<crate::FileMove>,
|
||||
/// Made by an agent through the MCP server's tools: undoable like a refactoring, but
|
||||
/// not announced as one.
|
||||
by_agent: bool,
|
||||
|
||||
@@ -130,11 +130,6 @@ pub struct AgentSettings {
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = BTreeMap<String, AgentMcpServer>)]
|
||||
pub mcp_servers: BTreeMap<String, AgentMcpServer>,
|
||||
/// How agent skills may run, keyed by skill name (`[agents.skills.<name>]`); `SKILL.md`
|
||||
/// files on disk are never modified.
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = BTreeMap<String, AgentSkillPolicy>)]
|
||||
pub skills: BTreeMap<String, AgentSkillPolicy>,
|
||||
}
|
||||
|
||||
impl Default for AgentSettings {
|
||||
@@ -155,7 +150,6 @@ impl Default for AgentSettings {
|
||||
new_task_approvals: NewTaskApprovals::Bypass,
|
||||
defaults: BTreeMap::new(),
|
||||
mcp_servers: BTreeMap::new(),
|
||||
skills: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -211,34 +205,6 @@ impl Default for AgentMcpServer {
|
||||
}
|
||||
}
|
||||
|
||||
/// How an agent skill may run (`[agents.skills.<name>] mode = …`).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AgentSkillMode {
|
||||
/// The model decides when to use it.
|
||||
#[default]
|
||||
Auto,
|
||||
/// Only when the user invokes it with `/name`.
|
||||
SlashOnly,
|
||||
/// Never.
|
||||
Off,
|
||||
}
|
||||
|
||||
/// A skill's policy in Settings › Agents › Skills, stored without touching its `SKILL.md`.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct AgentSkillPolicy {
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = AgentSkillMode)]
|
||||
pub mode: AgentSkillMode,
|
||||
}
|
||||
|
||||
impl Default for AgentSkillPolicy {
|
||||
fn default() -> Self {
|
||||
Self { mode: AgentSkillMode::Auto }
|
||||
}
|
||||
}
|
||||
|
||||
/// A hand-edited value these settings don't know reads as the default, rather than
|
||||
/// failing the whole settings file.
|
||||
fn or_default<'de, D, T>(d: D) -> Result<T, D::Error>
|
||||
|
||||
@@ -110,17 +110,6 @@ pub struct WorkspaceEditPrecondition {
|
||||
}
|
||||
|
||||
impl WorkspaceEdit {
|
||||
/// The files and folders the edit renames, in order.
|
||||
pub fn moves(&self) -> Vec<FileMove> {
|
||||
self.files
|
||||
.iter()
|
||||
.filter_map(|f| match f {
|
||||
FileEdit::Rename { from, to } => Some(FileMove { from: from.clone(), to: to.clone() }),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Coalesces aliases of the same file before applying edits against its original text.
|
||||
/// Resource operations separate batches because later edits may use the new contents.
|
||||
pub fn deduplicate(&mut self) {
|
||||
@@ -195,14 +184,6 @@ pub enum FileEdit {
|
||||
},
|
||||
}
|
||||
|
||||
/// One file or folder move.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct FileMove {
|
||||
pub from: crate::IpcPath,
|
||||
pub to: crate::IpcPath,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Severity {
|
||||
|
||||
@@ -151,7 +151,6 @@ pub struct CommitSettings {
|
||||
/// Commit from the Commit tool window; off = Local Changes in the Git tool
|
||||
/// window and a Commit dialog.
|
||||
pub non_modal: bool,
|
||||
pub include_changes_by_default: bool,
|
||||
/// Start with an empty message instead of the last one / the changelist's.
|
||||
pub clear_initial_message: bool,
|
||||
pub analyze_code: bool,
|
||||
@@ -191,7 +190,6 @@ impl Default for CommitSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
non_modal: true,
|
||||
include_changes_by_default: true,
|
||||
clear_initial_message: false,
|
||||
analyze_code: true,
|
||||
check_todo: true,
|
||||
|
||||
@@ -72,7 +72,7 @@ pub struct Host {
|
||||
/// Projects the MCP server serves without a window.
|
||||
pub mcp_background: mcp::BackgroundProjects,
|
||||
pub(crate) agent_catalogs: Arc<ide_agent::AgentCatalogs>,
|
||||
pub trust: std::sync::Arc<trust::TrustStore>,
|
||||
pub trust: trust::TrustStore,
|
||||
pub(crate) mcp_approvals: Arc<trust::McpServerApprovals>,
|
||||
pub config_dir: PathBuf,
|
||||
/// Persistent user state, including credentials and recovery history.
|
||||
@@ -169,7 +169,7 @@ impl Host {
|
||||
mcp_agent_runs: Default::default(),
|
||||
mcp_background: Default::default(),
|
||||
agent_catalogs: Arc::default(),
|
||||
trust: std::sync::Arc::new(trust::TrustStore::load(&config_dir, &data_dir)),
|
||||
trust: trust::TrustStore::load(&config_dir, &data_dir),
|
||||
mcp_approvals: Arc::new(trust::McpServerApprovals::load(&data_dir)),
|
||||
proxy_password: ide_ssh::secrets::SecretFile::new(data_dir.join("proxy-password.json")),
|
||||
proxy_session_password: Mutex::default(),
|
||||
|
||||
@@ -668,8 +668,8 @@ async fn text_search(call: Call, is_regex: bool) -> IdeResult<Output> {
|
||||
if hits.len() > limit {
|
||||
break;
|
||||
}
|
||||
// Find in Files reports a very long line in windows cut around its matches: such lines
|
||||
// are matched again in the file's whole text, so a match keeps its real end.
|
||||
// Find in Files keeps a window of very long lines and drops the matches outside it:
|
||||
// such lines are matched again in the file's whole text.
|
||||
let long = |m: &ide_search::LineMatch| m.text_offset > 0 || m.text.encode_utf16().count() + 1 >= LINE_WINDOW;
|
||||
let whole = if file.matches.iter().any(long) {
|
||||
crate::ops::fs::fs_read_text(&host, call.window(), file.path.0.clone())
|
||||
@@ -679,15 +679,11 @@ async fn text_search(call: Call, is_regex: bool) -> IdeResult<Output> {
|
||||
} else {
|
||||
None
|
||||
};
|
||||
// One window per far-apart match: a line is expanded once.
|
||||
let mut expanded = std::collections::HashSet::new();
|
||||
for m in &file.matches {
|
||||
if let Some((ranges, text)) = &whole
|
||||
&& long(m)
|
||||
{
|
||||
if expanded.insert(m.line) {
|
||||
hits.extend(line_hits(path, text, ranges, m.line));
|
||||
}
|
||||
hits.extend(line_hits(path, text, ranges, m.line));
|
||||
continue;
|
||||
}
|
||||
let line_end = m.text_offset + m.text.encode_utf16().count() as u32;
|
||||
|
||||
@@ -7,9 +7,8 @@ use ide_agent::registry::{AgentRegistry, RegistryPaths};
|
||||
use ide_agent::{
|
||||
AcpImportOutcome, AgentAcceptOutcome, AgentChange, AgentChanges, AgentChangesView, AgentCliOffer,
|
||||
AgentCliUpdateResult, AgentCommand, AgentContextUsage, AgentEntry, AgentEvent, AgentModelCatalog, AgentProbe,
|
||||
AgentPrompt, AgentProvider, AgentQueued, AgentSkillMode, AgentSkillPolicy, AgentSkillState, AgentTask,
|
||||
CustomAgentInput, ExternalSession, McpExternalSource, McpImportSelection, McpProbeResult, McpScope, McpServer,
|
||||
McpServerInput, McpTransport, NewAgentTask, SkillsPolicy,
|
||||
AgentPrompt, AgentProvider, AgentQueued, AgentTask, CustomAgentInput, ExternalSession, McpExternalSource,
|
||||
McpImportSelection, McpProbeResult, McpScope, McpServer, McpServerInput, McpTransport, NewAgentTask,
|
||||
};
|
||||
use ide_command::command;
|
||||
use ide_core::error::ErrorKind;
|
||||
@@ -1029,148 +1028,6 @@ pub fn agent_set_mcp_overrides(
|
||||
host.project(window)?.agents.set_mcp_overrides(&task, overrides)
|
||||
}
|
||||
|
||||
/// Updates per-session skill modes on `task`.
|
||||
#[command(trust = always)]
|
||||
pub fn agent_set_skill_overrides(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
task: String,
|
||||
overrides: std::collections::BTreeMap<String, AgentSkillMode>,
|
||||
) -> IdeResult<AgentTask> {
|
||||
host.project(window)?.agents.set_skill_overrides(&task, overrides)
|
||||
}
|
||||
|
||||
/// Every skill discovered in the project and the user's folders, with the mode a session
|
||||
/// of this project runs it with (without any session's own overrides).
|
||||
#[command(trust = always)]
|
||||
pub async fn agent_skills_list(host: &Host, window: &str) -> IdeResult<Vec<AgentSkillState>> {
|
||||
let project = host.project(window)?;
|
||||
let root = project.root.clone();
|
||||
let (policy, home) = (skills_policy(&project), dirs::home_dir());
|
||||
tokio::task::spawn_blocking(move || {
|
||||
Ok(ide_agent::skills::resolve(
|
||||
ide_agent::skills::discover_skills(&root, home.as_deref()),
|
||||
None,
|
||||
&policy.workspace,
|
||||
&policy.user,
|
||||
policy.workspace_trusted,
|
||||
))
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
}
|
||||
|
||||
/// Sets how `name` may run in `scope`, in the settings file of that scope, and returns the
|
||||
/// updated list. `SKILL.md` files are never touched; the default `auto` removes the entry.
|
||||
#[command(trust = always)]
|
||||
pub fn agent_skills_set_mode(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
name: String,
|
||||
scope: McpScope,
|
||||
mode: AgentSkillMode,
|
||||
) -> IdeResult<Vec<AgentSkillState>> {
|
||||
let name = name.trim().to_owned();
|
||||
if name.is_empty() {
|
||||
return Err(IdeError::invalid("a skill needs a name"));
|
||||
}
|
||||
let project = host.project(window).ok().filter(|p| !p.light);
|
||||
let (mut user, mut workspace) = skills_maps(host, project.as_ref());
|
||||
match scope {
|
||||
McpScope::User => {
|
||||
let changed = if mode == AgentSkillMode::Auto {
|
||||
user.remove(&name).is_some()
|
||||
} else {
|
||||
user.insert(name, AgentSkillPolicy { mode }).map(|p| p.mode) != Some(mode)
|
||||
};
|
||||
if changed {
|
||||
persist_skills_map(host, None, scope, &user)?;
|
||||
}
|
||||
}
|
||||
McpScope::Workspace => {
|
||||
let map =
|
||||
workspace.as_mut().ok_or_else(|| IdeError::invalid("Open a project to configure workspace skills"))?;
|
||||
let changed = if mode == AgentSkillMode::Auto {
|
||||
map.remove(&name).is_some()
|
||||
} else {
|
||||
map.insert(name, AgentSkillPolicy { mode }).map(|p| p.mode) != Some(mode)
|
||||
};
|
||||
if changed {
|
||||
let map = map.clone();
|
||||
persist_skills_map(host, project.as_ref(), scope, &map)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
match project {
|
||||
Some(project) => {
|
||||
let root = project.root.clone();
|
||||
let policy = skills_policy(&project);
|
||||
let home = dirs::home_dir();
|
||||
Ok(ide_agent::skills::resolve(
|
||||
ide_agent::skills::discover_skills(&root, home.as_deref()),
|
||||
None,
|
||||
&policy.workspace,
|
||||
&policy.user,
|
||||
policy.workspace_trusted,
|
||||
))
|
||||
}
|
||||
None => Ok(Vec::new()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The user's and the workspace's skill policies (`[agents.skills.<name>]`).
|
||||
fn skills_maps(
|
||||
host: &Host,
|
||||
project: Option<&std::sync::Arc<crate::Project>>,
|
||||
) -> (std::collections::BTreeMap<String, AgentSkillPolicy>, Option<std::collections::BTreeMap<String, AgentSkillPolicy>>)
|
||||
{
|
||||
let user = host.global_settings.effective().agents.skills.clone();
|
||||
let workspace =
|
||||
project.map(|p| p.settings.layer(ide_workspace::settings::SettingsScope::Project).agents.skills.clone());
|
||||
(user, workspace)
|
||||
}
|
||||
|
||||
/// Saves `map` into its scope's settings and tells the windows.
|
||||
fn persist_skills_map(
|
||||
host: &Host,
|
||||
project: Option<&std::sync::Arc<crate::Project>>,
|
||||
scope: McpScope,
|
||||
map: &std::collections::BTreeMap<String, AgentSkillPolicy>,
|
||||
) -> IdeResult<()> {
|
||||
let value = if map.is_empty() {
|
||||
serde_json::Value::Null
|
||||
} else {
|
||||
serde_json::to_value(map).map_err(|e| IdeError::invalid(e.to_string()))?
|
||||
};
|
||||
let event = IdeEvent::SettingsChanged { key: "agents.skills".into() };
|
||||
match scope {
|
||||
McpScope::User => {
|
||||
host.global_settings.set(ide_workspace::settings::SettingsScope::Global, "agents.skills", value)?;
|
||||
for p in host.projects() {
|
||||
p.settings.reload();
|
||||
p.agents.notify_mcp_servers_changed();
|
||||
p.sink.emit(event.clone());
|
||||
}
|
||||
}
|
||||
McpScope::Workspace => {
|
||||
let p = project.ok_or_else(|| IdeError::invalid("Open a project to configure workspace skills"))?;
|
||||
p.settings.set(ide_workspace::settings::SettingsScope::Project, "agents.skills", value)?;
|
||||
p.agents.notify_mcp_servers_changed();
|
||||
p.sink.emit(event);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The skill policies a session of `project` resolves against.
|
||||
fn skills_policy(project: &crate::Project) -> SkillsPolicy {
|
||||
SkillsPolicy {
|
||||
user: project.settings.layer(ide_workspace::settings::SettingsScope::Global).agents.skills.clone(),
|
||||
workspace: project.settings.layer(ide_workspace::settings::SettingsScope::Project).agents.skills.clone(),
|
||||
workspace_trusted: project.trusted.load(std::sync::atomic::Ordering::Acquire),
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_project_root(root: &std::path::Path, requested: Option<&std::path::Path>) -> IdeResult<std::path::PathBuf> {
|
||||
let Some(requested) = requested else {
|
||||
return Ok(root.to_path_buf());
|
||||
@@ -1326,9 +1183,6 @@ ide_command::domain!(
|
||||
agent_set_config,
|
||||
agent_set_env,
|
||||
agent_set_mcp_overrides,
|
||||
agent_set_skill_overrides,
|
||||
agent_skills_list,
|
||||
agent_skills_set_mode,
|
||||
agent_stop_background,
|
||||
agent_subscribe,
|
||||
agent_unarchive,
|
||||
|
||||
@@ -85,7 +85,7 @@ pub async fn doc_set_line_ending(host: &Host, window: &str, doc: DocId, line_end
|
||||
}
|
||||
|
||||
/// Structure view: LSP document symbols when available (with tree-sitter
|
||||
/// visibility and type-alias kinds), tree-sitter otherwise.
|
||||
/// visibility), tree-sitter otherwise.
|
||||
/// Tree-sitter answers come from the per-document tree cache (incremental
|
||||
/// re-parse); large documents get no syntax structure.
|
||||
#[command(trust = always)]
|
||||
@@ -113,13 +113,10 @@ pub async fn doc_outline(host: &Host, window: &str, doc: DocId) -> IdeResult<Vec
|
||||
};
|
||||
let syntax = || project.syntax.outline(doc, &snap.language, snap.version, &snap.text);
|
||||
Ok(match lsp {
|
||||
// Server symbols carry no visibility, nor a kind for type aliases; borrow them from
|
||||
// the syntax tree.
|
||||
// Server symbols carry no visibility; borrow it from the syntax tree.
|
||||
Some(mut items) => {
|
||||
if !snap.large {
|
||||
let syntax = syntax();
|
||||
ide_language::merge_visibility(&mut items, &syntax);
|
||||
ide_language::merge_kinds(&mut items, &syntax);
|
||||
ide_language::merge_visibility(&mut items, &syntax());
|
||||
}
|
||||
items
|
||||
}
|
||||
|
||||
@@ -335,12 +335,6 @@ pub fn set_settings(
|
||||
project.agents.notify_mcp_servers_changed();
|
||||
}
|
||||
}
|
||||
// A skill policy change re-resolves the modes; an idle session restarts to pick them up.
|
||||
if key == "agents" || key == "agents.skills" || key.starts_with("agents.skills.") {
|
||||
for project in affected() {
|
||||
project.agents.notify_mcp_servers_changed();
|
||||
}
|
||||
}
|
||||
// A new interpreter / toolchain / server executable restarts the language servers it affects.
|
||||
// So do inspections that are compiler options (`ide-sdk` `configure_java_compiler`).
|
||||
let code_style = key == "editor"
|
||||
|
||||
@@ -22,17 +22,6 @@ pub fn literal_range(l: ide_language::Literal) -> ide_search::LiteralRange {
|
||||
ide_search::LiteralRange { start: l.start, end: l.end, kind }
|
||||
}
|
||||
|
||||
/// Comments and string literals of `text`, for the search context of Find and Replace in Files.
|
||||
pub(crate) fn literals_of(
|
||||
project: &crate::project::Project,
|
||||
syntax: &ide_language::Syntax,
|
||||
path: &Path,
|
||||
text: &str,
|
||||
) -> Option<Vec<ide_search::LiteralRange>> {
|
||||
let language = project.languages.detect(path, text.lines().next());
|
||||
Some(syntax.literals(&language, text)?.into_iter().map(literal_range).collect())
|
||||
}
|
||||
|
||||
/// Find in Files. Results stream through `on_event`; ends with `Done`.
|
||||
/// Cancel with `cancel_request(request)`.
|
||||
#[command(trust = always)]
|
||||
@@ -109,7 +98,10 @@ pub(crate) fn search_project(
|
||||
Some(ProjectFileSet::Test) => roots.is_test(rel),
|
||||
_ => true,
|
||||
};
|
||||
let literals = |path: &Path, text: &str| literals_of(project, syntax, path, text);
|
||||
let literals = |path: &Path, text: &str| {
|
||||
let language = project.languages.detect(path, text.lines().next());
|
||||
Some(syntax.literals(&language, text)?.into_iter().map(literal_range).collect())
|
||||
};
|
||||
let defaults = project.documents.file_defaults();
|
||||
let decode = |path: &Path, bytes: &[u8]| ide_vfs::decode_text(bytes, defaults.fallback_for(path));
|
||||
let mut total = SearchSummary::default();
|
||||
|
||||
@@ -75,19 +75,9 @@ pub async fn replace_in_files(
|
||||
let summary = tokio::task::spawn_blocking(move || {
|
||||
let targets = if all_in_scope { scope_targets(&project, &syntax, &query, targets, &cancel)? } else { targets };
|
||||
let host = DocumentsHost(&project.documents);
|
||||
let literals = |path: &Path, text: &str| super::literals_of(&project, &syntax, path, text);
|
||||
ide_search::replace_files_in_context(
|
||||
&host,
|
||||
&query,
|
||||
&replacement,
|
||||
preserve_case,
|
||||
&targets,
|
||||
Some(&literals),
|
||||
&cancel,
|
||||
&|e| {
|
||||
let _ = events.send(e);
|
||||
},
|
||||
)
|
||||
ide_search::replace_files(&host, &query, &replacement, preserve_case, &targets, &cancel, &|e| {
|
||||
let _ = events.send(e);
|
||||
})
|
||||
})
|
||||
.await
|
||||
.map_err(|e| ide_core::IdeError::internal(e.to_string()));
|
||||
|
||||
@@ -738,19 +738,6 @@ impl Host {
|
||||
let approvals = self.mcp_approvals.clone();
|
||||
let secrets = self.agent_secrets.clone();
|
||||
let root = root.to_path_buf();
|
||||
// The skill policies sessions resolve against: both settings layers and the
|
||||
// workspace's trust as it stands when a session starts.
|
||||
let skill_settings = settings.clone();
|
||||
let skill_root = root.clone();
|
||||
let trust = self.trust.clone();
|
||||
agents.set_skills_policy_hook(Box::new(move || {
|
||||
let layer = |scope| skill_settings.layer(scope).agents.skills.clone();
|
||||
ide_agent::SkillsPolicy {
|
||||
user: layer(ide_workspace::settings::SettingsScope::Global),
|
||||
workspace: layer(ide_workspace::settings::SettingsScope::Project),
|
||||
workspace_trusted: trust.trusted(&skill_root).unwrap_or(false),
|
||||
}
|
||||
}));
|
||||
agents.set_mcp_servers_hook(Box::new(move || {
|
||||
crate::ops::agent::session_mcp_servers(&settings, &approvals, &secrets, &root)
|
||||
}));
|
||||
|
||||
@@ -187,19 +187,6 @@ async fn reads_unsaved_text_and_searches_the_overlay_with_a_limit() {
|
||||
assert_eq!(std::fs::read_to_string(h.root.join("src/a.txt")).unwrap(), "old text\nneedle needle\n");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn every_match_of_a_long_line_is_found_once() {
|
||||
let h = Harness::new();
|
||||
std::fs::write(
|
||||
h.root.join("src/min.js"),
|
||||
format!("a=1;{}b='longneedle';{}longneedle\n", "x".repeat(2000), "y".repeat(2000)),
|
||||
)
|
||||
.unwrap();
|
||||
let found = h.json("search_text", json!({"q":"longneedle","limit":20})).await;
|
||||
let columns: Vec<_> = found["items"].as_array().unwrap().iter().map(|i| i["startColumn"].clone()).collect();
|
||||
assert_eq!(columns, [json!(2008), json!(4020)], "{found}");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn window_reports_supply_editor_selection_and_problems_then_disappear_on_close() {
|
||||
let h = Harness::new();
|
||||
|
||||
@@ -195,56 +195,3 @@ async fn replace_all_saves_open_buffers_without_unsaved_changes() {
|
||||
assert_eq!(project.documents.text_snapshot(edited).unwrap().text, "DONE\nmore\n");
|
||||
host.close_project("main");
|
||||
}
|
||||
|
||||
/// Replace All past the limit replaces what the search lists: only the matches its Search
|
||||
/// Context keeps (comments, string literals or code), as below the limit.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn replace_all_past_the_limit_keeps_to_the_search_context() {
|
||||
use ide_search::SearchContext as C;
|
||||
let comments = |word: &str| lines(2001, &format!("// {word}"));
|
||||
let code = |name: &str, string: &str| format!("fn {name}() -> &'static str {{ \"{string}\" }}\n");
|
||||
let original = format!("{}{}", comments("tok"), code("tok", "tok"));
|
||||
let cases = [
|
||||
(C::Any, format!("{}{}", comments("X"), code("X", "X"))),
|
||||
(C::InComments, format!("{}{}", comments("X"), code("tok", "tok"))),
|
||||
(C::InStringLiterals, format!("{}{}", comments("tok"), code("tok", "X"))),
|
||||
(C::ExceptComments, format!("{}{}", comments("tok"), code("X", "X"))),
|
||||
(C::ExceptStringLiterals, format!("{}{}", comments("X"), code("X", "tok"))),
|
||||
(C::ExceptCommentsAndStringLiterals, format!("{}{}", comments("tok"), code("X", "tok"))),
|
||||
];
|
||||
for (context, expected) in cases {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
std::fs::write(root.join("lib.rs"), &original).unwrap();
|
||||
let host = Host::new(HostConfig {
|
||||
config_dir: base.join("config"),
|
||||
data_dir: base.join("data"),
|
||||
local_data_dir: base.join("data"),
|
||||
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
|
||||
syntax: Arc::default(),
|
||||
sink_for: Box::new(|_| Arc::new(NullSink)),
|
||||
owner: |w| w,
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
project_environment: false,
|
||||
});
|
||||
host.trust.decide(&root, true, false).unwrap();
|
||||
host.open_project("main", &root).unwrap();
|
||||
ops::search::replace_in_files(
|
||||
&host,
|
||||
"main",
|
||||
RequestId::next(),
|
||||
SearchQuery { context, ..query("tok", false) },
|
||||
"X".into(),
|
||||
false,
|
||||
vec![],
|
||||
true,
|
||||
ops::Channel::new(|_| {}),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(std::fs::read_to_string(root.join("lib.rs")).unwrap(), expected, "{context:?}");
|
||||
host.close_project("main");
|
||||
}
|
||||
}
|
||||
@@ -25,7 +25,7 @@ pub use syntax::{
|
||||
CSS_CLASS, CSS_ID, CSS_VARIABLE, ClassBases, ConfigurationKey, ExternalFold, ExternalSymbol, ExternalSyntax,
|
||||
ExternalToken, FileReference, Literal, LiteralKind, MAX_CACHED_TREES, MAX_PARSE_BYTES, ParsedTree, SpellingKind,
|
||||
SpellingRegion, Syntax, SyntaxCache, SyntaxCacheStats, SyntaxHighlightKind, SyntaxHighlights, TreeError,
|
||||
VueComponentImport, VueRefAccess, VueRefElement, WebReference, WebReferenceKind, merge_kinds, merge_visibility,
|
||||
VueComponentImport, VueRefAccess, VueRefElement, WebReference, WebReferenceKind, merge_visibility,
|
||||
set_external_syntax, shift_pos, shift_range,
|
||||
};
|
||||
pub use syntax::{MethodBody, PhpAlignment, PythonClassFacts, PythonFacts, PythonMethodFacts};
|
||||
|
||||
@@ -28,7 +28,7 @@ use ide_core::{LanguageId, OutlineItem, Pos, Range};
|
||||
pub use inheritance::ClassBases;
|
||||
pub use lines::{shift_pos, shift_range};
|
||||
pub use literals::{Literal, LiteralKind, SpellingKind, SpellingRegion};
|
||||
pub use outline::{merge_kinds, merge_visibility};
|
||||
pub use outline::merge_visibility;
|
||||
pub use php_align::PhpAlignment;
|
||||
pub use python_facts::{MethodBody, PythonClassFacts, PythonFacts, PythonMethodFacts};
|
||||
use std::cell::RefCell;
|
||||
|
||||
@@ -495,36 +495,6 @@ pub fn merge_visibility(target: &mut [OutlineItem], source: &[OutlineItem]) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Takes the syntax tree's kind where a server reported a declared type as a value or a type
|
||||
/// parameter: LSP has no kind for type aliases, so servers fall back to one of those
|
||||
/// (typescript-language-server: Variable; rust-analyzer, sourcekit-lsp: TypeParameter).
|
||||
/// Matched by name and position like [`merge_visibility`].
|
||||
pub fn merge_kinds(target: &mut [OutlineItem], source: &[OutlineItem]) {
|
||||
fn index(items: &[OutlineItem], out: &mut HashMap<(ide_core::Pos, String), SymbolKind>) {
|
||||
for i in items {
|
||||
if i.kind.is_type_like() {
|
||||
out.insert((i.selection_range.start, i.name.clone()), i.kind);
|
||||
}
|
||||
index(&i.children, out);
|
||||
}
|
||||
}
|
||||
fn apply(items: &mut [OutlineItem], map: &HashMap<(ide_core::Pos, String), SymbolKind>) {
|
||||
for i in items {
|
||||
if matches!(i.kind, SymbolKind::Variable | SymbolKind::TypeParameter)
|
||||
&& let Some(&kind) = map.get(&(i.selection_range.start, i.name.clone()))
|
||||
{
|
||||
i.kind = kind;
|
||||
}
|
||||
apply(&mut i.children, map);
|
||||
}
|
||||
}
|
||||
let mut map = HashMap::new();
|
||||
index(source, &mut map);
|
||||
if !map.is_empty() {
|
||||
apply(target, &map);
|
||||
}
|
||||
}
|
||||
|
||||
/// End of `node` without trailing whitespace (C macros and others include the newline).
|
||||
fn trimmed_end(node: &Node, text: &str) -> usize {
|
||||
let (s, e) = (node.start_byte(), node.end_byte());
|
||||
|
||||
@@ -1476,88 +1476,6 @@ fn merge_visibility_matches_by_name_and_position() {
|
||||
assert_eq!(lsp[1].visibility, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merge_kinds_names_types_a_server_reported_as_values_or_type_parameters() {
|
||||
fn kinds(items: &[OutlineItem], out: &mut Vec<(String, SymbolKind)>) {
|
||||
for i in items {
|
||||
out.push((i.name.clone(), i.kind));
|
||||
kinds(&i.children, out);
|
||||
}
|
||||
}
|
||||
/// The syntax outline with each kind replaced as a server reports it.
|
||||
fn as_server(ts: &[OutlineItem], server: &[(&str, SymbolKind)]) -> Vec<OutlineItem> {
|
||||
fn set(items: &mut [OutlineItem], server: &[(&str, SymbolKind)], at: &mut usize) {
|
||||
for i in items {
|
||||
i.kind = server[*at].1;
|
||||
assert_eq!(i.name, server[*at].0);
|
||||
*at += 1;
|
||||
set(&mut i.children, server, at);
|
||||
}
|
||||
}
|
||||
let mut lsp = ts.to_vec();
|
||||
set(&mut lsp, server, &mut 0);
|
||||
lsp
|
||||
}
|
||||
fn merged(language: &str, src: &str, server: &[(&str, SymbolKind)]) -> Vec<(String, SymbolKind)> {
|
||||
let ts = syntax().outline(&lang(language), src);
|
||||
let mut lsp = as_server(&ts, server);
|
||||
crate::merge_kinds(&mut lsp, &ts);
|
||||
let mut out = Vec::new();
|
||||
kinds(&lsp, &mut out);
|
||||
out
|
||||
}
|
||||
use SymbolKind as K;
|
||||
let owned = |v: &[(&str, SymbolKind)]| v.iter().map(|(n, k)| (n.to_string(), *k)).collect::<Vec<_>>();
|
||||
|
||||
// typescript-language-server: a type alias is a Variable; `const` is one too.
|
||||
let ts = "type Cents = number;\ninterface Shape {}\nconst rate = 1;\n";
|
||||
assert_eq!(
|
||||
merged("typescript", ts, &[("Cents", K::Variable), ("Shape", K::Interface), ("rate", K::Variable)]),
|
||||
owned(&[("Cents", K::TypeAlias), ("Shape", K::Interface), ("rate", K::Variable)]),
|
||||
);
|
||||
|
||||
// rust-analyzer: type aliases and associated types are TypeParameters, a trait an Interface.
|
||||
let rs = "pub type Meters = u32;\ntrait Measure { type Unit; }\nstruct Rope;\nimpl Measure for Rope { type Unit = Meters; }\n";
|
||||
assert_eq!(
|
||||
merged(
|
||||
"rust",
|
||||
rs,
|
||||
&[
|
||||
("Meters", K::TypeParameter),
|
||||
("Measure", K::Interface),
|
||||
("Unit", K::TypeParameter),
|
||||
("Rope", K::Struct),
|
||||
("impl Measure for Rope", K::Variable),
|
||||
("Unit", K::TypeParameter),
|
||||
],
|
||||
),
|
||||
owned(&[
|
||||
("Meters", K::TypeAlias),
|
||||
("Measure", K::Interface),
|
||||
("Unit", K::TypeAlias),
|
||||
("Rope", K::Struct),
|
||||
("impl Measure for Rope", K::Variable),
|
||||
("Unit", K::TypeAlias),
|
||||
]),
|
||||
);
|
||||
|
||||
// sourcekit-lsp: typealias and associatedtype are TypeParameters.
|
||||
let swift = "typealias Meters = Int\nprotocol Measure { associatedtype Unit }\n";
|
||||
assert_eq!(
|
||||
merged("swift", swift, &[("Meters", K::TypeParameter), ("Measure", K::Interface), ("Unit", K::TypeParameter)]),
|
||||
owned(&[("Meters", K::TypeAlias), ("Measure", K::Interface), ("Unit", K::TypeAlias)]),
|
||||
);
|
||||
|
||||
// A type kind the server chose stays: clangd's Class for a typedef, gopls's Struct.
|
||||
let c = "typedef unsigned int meters;\n";
|
||||
assert_eq!(merged("c", c, &[("meters", K::Class)]), owned(&[("meters", K::Class)]));
|
||||
let go = "package p\n\ntype Point struct{}\n";
|
||||
assert_eq!(
|
||||
merged("go", go, &[("p", K::Package), ("Point", K::Struct)]),
|
||||
owned(&[("p", K::Package), ("Point", K::Struct)])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spelling_regions_cover_declared_names_only() {
|
||||
let src = "// note\nfn parse_input(raw_text: &str) -> Value { let mut counter = helper(raw_text); \"hi\" }\n";
|
||||
|
||||
@@ -1337,10 +1337,6 @@ pub fn configure_server(cfg: &mut LanguageServerConfig, root: &Path, server_root
|
||||
cfg.args = vec!["--lsp".into(), "--stdio".into()];
|
||||
cfg.display_name = Some("TypeScript 7".into());
|
||||
cfg.initialization_options = None;
|
||||
// Completing a JSX prop adds `=""` or `={}` by its type, as vtsls does by default;
|
||||
// TypeScript 7 adds no value unless asked.
|
||||
let jsx = json!({ "preferences": { "jsxAttributeCompletionStyle": "auto" } });
|
||||
merge_init_options(cfg, json!({ "typescript": jsx, "javascript": jsx }));
|
||||
cfg.tsserver_project = false;
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1725,15 +1725,7 @@ fn typescript_7_runs_its_own_language_server() {
|
||||
assert_eq!(Path::new(&cfg.command), native, "{name}");
|
||||
assert_eq!(cfg.args, ["--lsp", "--stdio"]);
|
||||
assert_eq!(cfg.display_name.as_deref(), Some("TypeScript 7"));
|
||||
// The tsserver-based server's options don't apply; JSX prop completion adds a value.
|
||||
let options = serde_json::to_value(cfg.initialization_options.as_ref().unwrap()).unwrap();
|
||||
for language in ["typescript", "javascript"] {
|
||||
assert_eq!(
|
||||
options[language],
|
||||
serde_json::json!({ "preferences": { "jsxAttributeCompletionStyle": "auto" } })
|
||||
);
|
||||
}
|
||||
assert_eq!(options.as_object().unwrap().len(), 2, "{options}");
|
||||
assert!(cfg.initialization_options.is_none());
|
||||
}
|
||||
// Picked as a directory (its `lib`, as for older versions), too.
|
||||
s.languages.typescript.version = modules.join("typescript/lib").to_string_lossy().into_owned();
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
//! Parallel walk + per-file search.
|
||||
|
||||
use crate::iter::for_each_match;
|
||||
use crate::line::line_matches;
|
||||
use crate::line::line_match;
|
||||
use crate::mask::FileMask;
|
||||
use crate::pattern::ScopePattern;
|
||||
use crate::query::{Compiled, line_terminator};
|
||||
use crate::{
|
||||
FileMatches, LineMatch, LiteralRange, Literals, PathFilter, SearchContext, SearchScope, SearchSummary, TextSource,
|
||||
FileMatches, LineMatch, LiteralKind, LiteralRange, Literals, PathFilter, SearchContext, SearchScope, SearchSummary,
|
||||
TextSource,
|
||||
};
|
||||
use grep_regex::RegexMatcher;
|
||||
use grep_searcher::{BinaryDetection, Searcher, SearcherBuilder, Sink, SinkMatch};
|
||||
@@ -51,7 +52,6 @@ struct Control<'a> {
|
||||
matches: AtomicU32,
|
||||
files: AtomicU32,
|
||||
max: u32,
|
||||
whole_word: bool,
|
||||
}
|
||||
|
||||
impl Control<'_> {
|
||||
@@ -131,7 +131,6 @@ pub(crate) fn run(req: Request<'_>) -> IdeResult<SearchSummary> {
|
||||
matches: AtomicU32::new(0),
|
||||
files: AtomicU32::new(0),
|
||||
max: if req.max_matches == 0 { DEFAULT_MAX_MATCHES } else { req.max_matches },
|
||||
whole_word: req.compiled.whole_word,
|
||||
},
|
||||
};
|
||||
let mut searcher_builder = SearcherBuilder::new();
|
||||
@@ -463,6 +462,12 @@ impl<'a> FileSink<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Kind of the comment or string literal containing byte `pos` (`literals` sorted).
|
||||
fn literal_at(literals: &[LiteralRange], pos: usize) -> Option<LiteralKind> {
|
||||
let i = literals.partition_point(|l| l.start <= pos);
|
||||
literals[..i].last().filter(|l| pos < l.end).map(|l| l.kind)
|
||||
}
|
||||
|
||||
impl Sink for FileSink<'_> {
|
||||
type Error = io::Error;
|
||||
|
||||
@@ -483,12 +488,12 @@ impl Sink for FileSink<'_> {
|
||||
let mut found = std::mem::take(&mut self.found);
|
||||
let mut ranges = std::mem::take(&mut self.ranges);
|
||||
found.clear();
|
||||
for_each_match(self.matcher, self.ctl.whole_word, &buffer[..range.end], range.start, |mm| {
|
||||
for_each_match(self.matcher, &buffer[..range.end], range.start, |mm| {
|
||||
found.push((mm.start() - range.start, mm.end() - range.start));
|
||||
});
|
||||
if let Some((context, literals)) = self.context {
|
||||
let block_start = usize::try_from(m.absolute_byte_offset()).unwrap_or(usize::MAX);
|
||||
found.retain(|&(a, _)| context.keeps(literals, block_start.saturating_add(a)));
|
||||
found.retain(|&(a, _)| context.accepts(literal_at(literals, block_start.saturating_add(a))));
|
||||
}
|
||||
|
||||
let mut next = found.iter().copied().peekable();
|
||||
@@ -516,7 +521,7 @@ impl Sink for FileSink<'_> {
|
||||
if !ranges.is_empty() {
|
||||
self.count = self.count.saturating_add(u32::try_from(ranges.len()).unwrap_or(u32::MAX));
|
||||
let line_no = u32::try_from(line_no).unwrap_or(u32::MAX);
|
||||
line_matches(line_no, &block[line_start..content_end], &ranges, &mut self.lines);
|
||||
self.lines.push(line_match(line_no, &block[line_start..content_end], &ranges));
|
||||
}
|
||||
line_start = line_end_incl;
|
||||
line_no += 1;
|
||||
@@ -701,7 +706,6 @@ mod budget_tests {
|
||||
matches: AtomicU32::new(0),
|
||||
files: AtomicU32::new(0),
|
||||
max,
|
||||
whole_word: false,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,27 +1,16 @@
|
||||
//! Match iteration that never splits a UTF-8 sequence after an empty match
|
||||
//! (`grep-matcher`'s iterators advance by a single byte), and that applies
|
||||
//! IDEA's whole-word rule.
|
||||
//! (`grep-matcher`'s iterators advance by a single byte).
|
||||
|
||||
use grep_matcher::{Captures, Match, Matcher};
|
||||
use grep_regex::{RegexCaptures, RegexMatcher};
|
||||
|
||||
/// Calls `f` for each non-overlapping match in `haystack[at..]`; `haystack[..at]`
|
||||
/// is only used as look-behind context. With `whole_word`, only [`is_whole_word`] matches.
|
||||
pub(crate) fn for_each_match(
|
||||
matcher: &RegexMatcher,
|
||||
whole_word: bool,
|
||||
haystack: &[u8],
|
||||
at: usize,
|
||||
mut f: impl FnMut(Match),
|
||||
) {
|
||||
/// is only used as look-behind context.
|
||||
pub(crate) fn for_each_match(matcher: &RegexMatcher, haystack: &[u8], at: usize, mut f: impl FnMut(Match)) {
|
||||
let mut at = at;
|
||||
let mut last_end = None;
|
||||
while at <= haystack.len() {
|
||||
let Ok(Some(m)) = matcher.find_at(haystack, at) else { break };
|
||||
if whole_word && !is_whole_word(haystack, m) {
|
||||
at = next_char(haystack, m.start());
|
||||
continue;
|
||||
}
|
||||
at = advance(haystack, m);
|
||||
if m.is_empty() && last_end == Some(m.end()) {
|
||||
continue;
|
||||
@@ -34,7 +23,6 @@ pub(crate) fn for_each_match(
|
||||
/// Like [`for_each_match`] but with capture groups.
|
||||
pub(crate) fn for_each_captures(
|
||||
matcher: &RegexMatcher,
|
||||
whole_word: bool,
|
||||
haystack: &[u8],
|
||||
caps: &mut RegexCaptures,
|
||||
mut f: impl FnMut(&RegexCaptures),
|
||||
@@ -46,10 +34,6 @@ pub(crate) fn for_each_captures(
|
||||
break;
|
||||
}
|
||||
let Some(m) = caps.get(0) else { break };
|
||||
if whole_word && !is_whole_word(haystack, m) {
|
||||
at = next_char(haystack, m.start());
|
||||
continue;
|
||||
}
|
||||
at = advance(haystack, m);
|
||||
if m.is_empty() && last_end == Some(m.end()) {
|
||||
continue;
|
||||
@@ -61,59 +45,12 @@ pub(crate) fn for_each_captures(
|
||||
|
||||
/// Where to resume after `m`: its end, or past the next char for empty matches.
|
||||
fn advance(haystack: &[u8], m: Match) -> usize {
|
||||
if !m.is_empty() { m.end() } else { next_char(haystack, m.end()) }
|
||||
}
|
||||
|
||||
/// The start of the char after the one at `at`.
|
||||
fn next_char(haystack: &[u8], at: usize) -> usize {
|
||||
let mut next = at + 1;
|
||||
if !m.is_empty() {
|
||||
return m.end();
|
||||
}
|
||||
let mut next = m.end() + 1;
|
||||
while next < haystack.len() && (haystack[next] & 0xC0) == 0x80 {
|
||||
next += 1;
|
||||
}
|
||||
next
|
||||
}
|
||||
|
||||
/// IDEA's whole word (`FindManagerBase.isWholeWord`): an edge where the match has an
|
||||
/// identifier character must not touch another one, unless it follows an escape such as
|
||||
/// `\n`; an edge with another character only must not repeat that character (`==` is not
|
||||
/// in `===`).
|
||||
fn is_whole_word(haystack: &[u8], m: Match) -> bool {
|
||||
let (start, end) = (m.start(), m.end());
|
||||
let word_start = match (char_before(haystack, start), char_at(haystack, start)) {
|
||||
(Some(prev), Some(first)) if is_identifier(first) => {
|
||||
let escaped = char_before(haystack, start - prev.len_utf8()) == Some('\\');
|
||||
!is_identifier(prev) || escaped
|
||||
}
|
||||
(Some(prev), Some(first)) => prev != first,
|
||||
_ => true,
|
||||
};
|
||||
let word_end = match (char_at(haystack, end), char_before(haystack, end)) {
|
||||
(Some(next), Some(last)) if is_identifier(last) => !is_identifier(next),
|
||||
(Some(next), Some(last)) => next != last,
|
||||
(Some(_), None) | (None, _) => true,
|
||||
};
|
||||
word_start && word_end
|
||||
}
|
||||
|
||||
/// Java's identifier part, near enough: letters, digits, `_` and `$`.
|
||||
fn is_identifier(c: char) -> bool {
|
||||
c.is_alphanumeric() || c == '_' || c == '$'
|
||||
}
|
||||
|
||||
/// The char starting at byte `at` (`None` at the end or in invalid UTF-8).
|
||||
fn char_at(haystack: &[u8], at: usize) -> Option<char> {
|
||||
let rest = haystack.get(at..)?;
|
||||
let len = rest.len().min(4);
|
||||
let s = match std::str::from_utf8(&rest[..len]) {
|
||||
Ok(s) => s,
|
||||
Err(e) => std::str::from_utf8(&rest[..e.valid_up_to()]).ok()?,
|
||||
};
|
||||
s.chars().next()
|
||||
}
|
||||
|
||||
/// The char ending at byte `at` (`None` at the start or in invalid UTF-8).
|
||||
fn char_before(haystack: &[u8], at: usize) -> Option<char> {
|
||||
let head = haystack.get(..at)?;
|
||||
let from = head.len().saturating_sub(4);
|
||||
(from..head.len()).find_map(|i| std::str::from_utf8(&head[i..]).ok().and_then(|s| s.chars().next_back()))
|
||||
}
|
||||
@@ -22,7 +22,7 @@ pub use mask::FileMask;
|
||||
pub use pattern::ScopePattern;
|
||||
pub use replace::{
|
||||
ReplaceEvent, ReplaceHost, ReplacePreview, ReplaceSummary, ReplaceTarget, apply_edits, preserve_case, preview,
|
||||
replace_files, replace_files_in_context, replacement_edits,
|
||||
replace_files, replacement_edits,
|
||||
};
|
||||
pub use words::{WordFiles, WordQuery, files_with_word};
|
||||
|
||||
@@ -99,15 +99,8 @@ impl SearchContext {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a match starting at byte `at` is kept, given the file's sorted comments and
|
||||
/// string literals. Find and Replace both filter with it, so they keep the same matches.
|
||||
pub fn keeps(self, literals: &[LiteralRange], at: usize) -> bool {
|
||||
let i = literals.partition_point(|l| l.start <= at);
|
||||
self.accepts(literals[..i].last().filter(|l| at < l.end).map(|l| l.kind))
|
||||
}
|
||||
|
||||
/// Only matches inside comments / string literals: files without any are skipped.
|
||||
pub(crate) fn needs_literals(self) -> bool {
|
||||
fn needs_literals(self) -> bool {
|
||||
matches!(self, Self::InComments | Self::InStringLiterals)
|
||||
}
|
||||
}
|
||||
@@ -167,8 +160,7 @@ pub type PathFilter<'a> = &'a (dyn Fn(&str) -> bool + Sync);
|
||||
pub struct LineMatch {
|
||||
/// 0-based line.
|
||||
pub line: u32,
|
||||
/// Line text, truncated around the matches for very long lines: such a line comes as one
|
||||
/// `LineMatch` per window, so the same `line` can repeat.
|
||||
/// Line text, truncated around the match for very long lines.
|
||||
pub text: String,
|
||||
/// UTF-16 column ranges within `text`.
|
||||
pub ranges: Vec<(u32, u32)>,
|
||||
@@ -293,9 +285,7 @@ pub fn match_ranges(text: &str, query: &SearchQuery) -> IdeResult<Vec<(usize, us
|
||||
}
|
||||
let compiled = query::compile(query)?;
|
||||
let mut out = Vec::new();
|
||||
iter::for_each_match(&compiled.matcher, compiled.whole_word, text.as_bytes(), 0, |m| {
|
||||
out.push((m.start(), m.end()))
|
||||
});
|
||||
iter::for_each_match(&compiled.matcher, text.as_bytes(), 0, |m| out.push((m.start(), m.end())));
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
@@ -318,7 +308,7 @@ pub fn replace_in_text(text: &str, query: &SearchQuery, replacement: &str) -> Id
|
||||
let mut out = Vec::with_capacity(text.len());
|
||||
let mut count = 0u32;
|
||||
let mut last = 0;
|
||||
iter::for_each_captures(matcher, compiled.whole_word, haystack, &mut caps, |caps| {
|
||||
iter::for_each_captures(matcher, haystack, &mut caps, |caps| {
|
||||
let Some(m) = caps.get(0) else { return };
|
||||
out.extend_from_slice(&haystack[last..m.start()]);
|
||||
last = m.end();
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
//! Turns a matched line plus byte ranges into [`LineMatch`]es with UTF-16
|
||||
//! columns. A very long line is cut into windows: one around its first match
|
||||
//! and the matches that fit with it, then one around each match left out.
|
||||
//! Turns a matched line plus byte ranges into a [`LineMatch`] with UTF-16
|
||||
//! columns, truncating very long lines to a window around the first match.
|
||||
|
||||
use crate::LineMatch;
|
||||
|
||||
@@ -9,57 +8,33 @@ pub(crate) const MAX_LINE_LEN: usize = 500;
|
||||
/// How much text before the first match a truncated line keeps.
|
||||
const CONTEXT_BEFORE: usize = 100;
|
||||
|
||||
/// Appends the matches of one line to `out`: a single [`LineMatch`], or one per window of a
|
||||
/// very long line. `line` excludes the line terminator; `ranges` are sorted, non-overlapping
|
||||
/// `line` excludes the line terminator; `ranges` are sorted, non-overlapping
|
||||
/// byte ranges within `line`.
|
||||
pub(crate) fn line_matches(line_no: u32, line: &[u8], ranges: &[(usize, usize)], out: &mut Vec<LineMatch>) {
|
||||
pub(crate) fn line_match(line_no: u32, line: &[u8], ranges: &[(usize, usize)]) -> LineMatch {
|
||||
match std::str::from_utf8(line) {
|
||||
Ok(s) => from_str(line_no, s, ranges, out),
|
||||
Ok(s) => from_str(line_no, s, ranges),
|
||||
Err(_) => {
|
||||
let (s, mapped) = lossy(line, ranges);
|
||||
from_str(line_no, &s, &mapped, out)
|
||||
from_str(line_no, &s, &mapped)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn line_match(line_no: u32, line: &[u8], ranges: &[(usize, usize)]) -> LineMatch {
|
||||
let mut out = Vec::new();
|
||||
line_matches(line_no, line, ranges, &mut out);
|
||||
out.swap_remove(0)
|
||||
}
|
||||
|
||||
fn from_str(line_no: u32, s: &str, ranges: &[(usize, usize)], out: &mut Vec<LineMatch>) {
|
||||
if s.len() <= MAX_LINE_LEN || utf16_len(s.as_bytes()) <= MAX_LINE_LEN {
|
||||
out.push(in_window(line_no, s, ranges, (0, s.len())).0);
|
||||
return;
|
||||
}
|
||||
let mut rest = ranges;
|
||||
loop {
|
||||
let bounds = window(s, floor_boundary(s, rest.first().map_or(0, |r| r.0.min(s.len()))));
|
||||
let (m, used) = in_window(line_no, s, rest, bounds);
|
||||
out.push(m);
|
||||
rest = &rest[used.max(1)..];
|
||||
if rest.is_empty() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The [`LineMatch`] of the text in `bounds` with the leading `ranges` that end inside it (at
|
||||
/// least the first one, cut to the window), and how many ranges it took.
|
||||
fn in_window(line_no: u32, s: &str, ranges: &[(usize, usize)], (start, end): (usize, usize)) -> (LineMatch, usize) {
|
||||
fn from_str(line_no: u32, s: &str, ranges: &[(usize, usize)]) -> LineMatch {
|
||||
let (start, end) = if s.len() <= MAX_LINE_LEN || utf16_len(s.as_bytes()) <= MAX_LINE_LEN {
|
||||
(0, s.len())
|
||||
} else {
|
||||
window(s, floor_boundary(s, ranges.first().map_or(0, |r| r.0.min(s.len()))))
|
||||
};
|
||||
let text = &s[start..end];
|
||||
let text_offset = if start == 0 { 0 } else { utf16_len(&s.as_bytes()[..start]) };
|
||||
|
||||
let mut out = Vec::with_capacity(ranges.len());
|
||||
let (mut pos, mut col) = (start, 0usize);
|
||||
let mut used = 0;
|
||||
for &(a, b) in ranges {
|
||||
if a > end || (a == end && b > a) || (used > 0 && b > end) {
|
||||
if a > end || (a == end && b > a) {
|
||||
break;
|
||||
}
|
||||
used += 1;
|
||||
let (a, b) = (floor_boundary(s, a.max(start)), ceil_boundary(s, b.min(end)));
|
||||
if a < pos {
|
||||
continue;
|
||||
@@ -70,7 +45,7 @@ fn in_window(line_no: u32, s: &str, ranges: &[(usize, usize)], (start, end): (us
|
||||
pos = b;
|
||||
out.push((col_a as u32, col as u32));
|
||||
}
|
||||
(LineMatch { line: line_no, text: text.to_owned(), ranges: out, text_offset: text_offset as u32 }, used)
|
||||
LineMatch { line: line_no, text: text.to_owned(), ranges: out, text_offset: text_offset as u32 }
|
||||
}
|
||||
|
||||
/// Byte window `[start, end)` of at most `MAX_LINE_LEN` UTF-16 units that
|
||||
@@ -211,30 +186,4 @@ mod tests {
|
||||
assert_eq!(m.ranges, vec![(100, 106)]);
|
||||
assert!(utf16_len(m.text.as_bytes()) <= MAX_LINE_LEN);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matches_outside_the_first_window_get_their_own() {
|
||||
// Two matches 100 apart share a window; the one 1000 further gets another.
|
||||
let s = format!("{}ab{}cd{}ef{}", "x".repeat(1000), "x".repeat(100), "x".repeat(1000), "x".repeat(10));
|
||||
let at = |needle: &str| s.find(needle).unwrap();
|
||||
let ranges = [(at("ab"), at("ab") + 2), (at("cd"), at("cd") + 2), (at("ef"), at("ef") + 2)];
|
||||
let mut out = Vec::new();
|
||||
line_matches(7, s.as_bytes(), &ranges, &mut out);
|
||||
let found: Vec<Vec<u32>> =
|
||||
out.iter().map(|m| m.ranges.iter().map(|&(a, _)| m.text_offset + a).collect()).collect();
|
||||
let col = |needle: &str| at(needle) as u32;
|
||||
assert_eq!(found, vec![vec![col("ab"), col("cd")], vec![col("ef")]]);
|
||||
assert!(out.iter().all(|m| m.line == 7 && utf16_len(m.text.as_bytes()) <= MAX_LINE_LEN));
|
||||
assert_eq!(&out[1].text[out[1].ranges[0].0 as usize..out[1].ranges[0].1 as usize], "ef");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_match_longer_than_the_window_is_cut_to_it() {
|
||||
let s = format!("{}{}tail", "x".repeat(100), "y".repeat(1000));
|
||||
let mut out = Vec::new();
|
||||
line_matches(0, s.as_bytes(), &[(100, 1100), (1100, 1104)], &mut out);
|
||||
assert_eq!(out.len(), 2);
|
||||
assert_eq!(out[0].ranges, vec![(100, 500)]);
|
||||
assert_eq!(out[1].text_offset + out[1].ranges[0].0, 1100);
|
||||
}
|
||||
}
|
||||
@@ -9,8 +9,6 @@ use ide_core::{IdeError, IdeResult};
|
||||
pub(crate) struct Compiled {
|
||||
pub matcher: RegexMatcher,
|
||||
pub multi_line: bool,
|
||||
/// Keep only whole-word matches ([`crate::iter`] checks IDEA's rule on each match).
|
||||
pub whole_word: bool,
|
||||
}
|
||||
|
||||
/// The line terminator shared by the matcher and the searcher. CRLF mode lets
|
||||
@@ -21,13 +19,12 @@ pub(crate) fn line_terminator() -> LineTerminator {
|
||||
|
||||
pub(crate) fn compile(query: &SearchQuery) -> IdeResult<Compiled> {
|
||||
let multi_line = needs_multi_line(query);
|
||||
let whole_word = query.whole_word;
|
||||
match build(query, multi_line) {
|
||||
Ok(matcher) => Ok(Compiled { matcher, multi_line, whole_word }),
|
||||
Ok(matcher) => Ok(Compiled { matcher, multi_line }),
|
||||
// Patterns such as `[\n]` or `\x0A` can only match across lines;
|
||||
// retry in multi-line mode before reporting an error.
|
||||
Err(err) if !multi_line => match build(query, true) {
|
||||
Ok(matcher) => Ok(Compiled { matcher, multi_line: true, whole_word }),
|
||||
Ok(matcher) => Ok(Compiled { matcher, multi_line: true }),
|
||||
Err(_) => Err(invalid_pattern(query, &err)),
|
||||
},
|
||||
Err(err) => Err(invalid_pattern(query, &err)),
|
||||
@@ -38,8 +35,7 @@ fn build(query: &SearchQuery, multi_line: bool) -> Result<RegexMatcher, grep_reg
|
||||
let mut b = RegexMatcherBuilder::new();
|
||||
b.case_smart(false)
|
||||
.case_insensitive(!query.case_sensitive)
|
||||
// Not `.word()`: ripgrep's rule wants a non-word character on both sides even of
|
||||
// `foo(`, IDEA's (in `iter`) only beside the match's identifier characters.
|
||||
.word(query.whole_word)
|
||||
.fixed_strings(!query.is_regex)
|
||||
.unicode(true)
|
||||
// `^`/`$` always mean start/end of line, as in IDEA and ripgrep.
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
//! (the document layer in the app, so open editors update and each file is one
|
||||
//! undoable step).
|
||||
|
||||
use crate::{LiteralRange, Literals, SearchContext, SearchQuery, iter, query};
|
||||
use crate::{SearchQuery, iter, query};
|
||||
use grep_matcher::{Captures, Matcher};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult, Pos, Range, TextEdit};
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -128,11 +128,10 @@ pub fn replacement_edits(
|
||||
preserve: bool,
|
||||
only: Option<&[Pos]>,
|
||||
) -> IdeResult<Vec<TextEdit>> {
|
||||
edits_except(text, query, replacement, preserve, only, None, None)
|
||||
edits_except(text, query, replacement, preserve, only, None)
|
||||
}
|
||||
|
||||
/// [`replacement_edits`] leaving out the matches that start at `skip` and, given the text's
|
||||
/// comments and string literals, those outside the query's [`crate::SearchContext`].
|
||||
/// [`replacement_edits`] leaving out the matches that start at `skip`.
|
||||
fn edits_except(
|
||||
text: &str,
|
||||
query: &SearchQuery,
|
||||
@@ -140,7 +139,6 @@ fn edits_except(
|
||||
preserve: bool,
|
||||
only: Option<&[Pos]>,
|
||||
skip: Option<&[Pos]>,
|
||||
literals: Option<&[LiteralRange]>,
|
||||
) -> IdeResult<Vec<TextEdit>> {
|
||||
if query.pattern.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
@@ -155,13 +153,10 @@ fn edits_except(
|
||||
let mut caps = matcher.new_captures().map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
let mut edits = Vec::new();
|
||||
let mut buf = Vec::new();
|
||||
iter::for_each_captures(matcher, compiled.whole_word, haystack, &mut caps, |caps| {
|
||||
iter::for_each_captures(matcher, haystack, &mut caps, |caps| {
|
||||
let Some(m) = caps.get(0) else { return };
|
||||
let start = lines.pos(m.start());
|
||||
if only.as_ref().is_some_and(|o| !o.contains(&start))
|
||||
|| skip.contains(&start)
|
||||
|| literals.is_some_and(|l| !query.context.keeps(l, m.start()))
|
||||
{
|
||||
if only.as_ref().is_some_and(|o| !o.contains(&start)) || skip.contains(&start) {
|
||||
return;
|
||||
}
|
||||
let mut new_text = if query.is_regex {
|
||||
@@ -232,23 +227,6 @@ pub fn replace_files(
|
||||
cancel: &CancellationToken,
|
||||
on_event: &dyn Fn(ReplaceEvent),
|
||||
) -> IdeResult<ReplaceSummary> {
|
||||
replace_files_in_context(host, query, replacement, preserve, targets, None, cancel, on_event)
|
||||
}
|
||||
|
||||
/// [`replace_files`] honouring [`SearchQuery::context`] with the comments and string literals
|
||||
/// `literals` finds, as [`crate::search_in_context`] does; without it every match is plain code.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn replace_files_in_context(
|
||||
host: &dyn ReplaceHost,
|
||||
query: &SearchQuery,
|
||||
replacement: &str,
|
||||
preserve: bool,
|
||||
targets: &[ReplaceTarget],
|
||||
literals: Option<Literals<'_>>,
|
||||
cancel: &CancellationToken,
|
||||
on_event: &dyn Fn(ReplaceEvent),
|
||||
) -> IdeResult<ReplaceSummary> {
|
||||
let literals = literals.filter(|_| query.context != SearchContext::Any);
|
||||
// Fail fast on an invalid pattern instead of once per file.
|
||||
if !query.pattern.is_empty() {
|
||||
query::compile(query)?;
|
||||
@@ -266,14 +244,8 @@ pub fn replace_files_in_context(
|
||||
if only.is_some_and(|o| o.is_empty()) {
|
||||
continue;
|
||||
}
|
||||
let result = host.edit_file(&target.path, &mut |text| {
|
||||
let found = match literals.map(|l| l(&target.path, text)) {
|
||||
// No syntax tree: nothing is in a comment or string, as in the search.
|
||||
Some(None) if query.context.needs_literals() => return Ok(Vec::new()),
|
||||
found => found.map(Option::unwrap_or_default),
|
||||
};
|
||||
edits_except(text, query, replacement, preserve, only, skip, found.as_deref())
|
||||
});
|
||||
let result =
|
||||
host.edit_file(&target.path, &mut |text| edits_except(text, query, replacement, preserve, only, skip));
|
||||
match result {
|
||||
Ok(n) => {
|
||||
if n > 0 {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult, Pos, TextEdit};
|
||||
use ide_search::{
|
||||
LiteralKind, LiteralRange, ReplaceEvent, ReplaceHost, ReplaceTarget, SearchQuery, SearchScope, preserve_case,
|
||||
preview, replace_files, replace_files_in_context, replacement_edits,
|
||||
ReplaceEvent, ReplaceHost, ReplaceTarget, SearchQuery, SearchScope, preserve_case, preview, replace_files,
|
||||
replacement_edits,
|
||||
};
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
@@ -169,46 +169,3 @@ fn replace_files_respects_selected_matches_and_invalid_patterns() {
|
||||
let err = replace_files(&docs, ®ex("("), "x", false, &t, &CancellationToken::new(), &|_| {}).unwrap_err();
|
||||
assert_eq!(err.kind, ide_core::error::ErrorKind::InvalidInput);
|
||||
}
|
||||
|
||||
/// `// …` comments and `"…"` strings of `.rs` files; other files have no syntax tree.
|
||||
fn toy_literals(path: &Path, text: &str) -> Option<Vec<LiteralRange>> {
|
||||
if path.extension().is_none_or(|e| e != "rs") {
|
||||
return None;
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for (i, _) in text.match_indices("//") {
|
||||
let end = text[i..].find('\n').map_or(text.len(), |n| i + n);
|
||||
out.push(LiteralRange { start: i, end, kind: LiteralKind::Comment });
|
||||
}
|
||||
let quotes: Vec<usize> = text.match_indices('"').map(|(i, _)| i).collect();
|
||||
for pair in quotes.chunks(2) {
|
||||
if let [a, b] = pair {
|
||||
out.push(LiteralRange { start: *a, end: b + 1, kind: LiteralKind::String });
|
||||
}
|
||||
}
|
||||
out.sort_by_key(|l| l.start);
|
||||
Some(out)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replace_files_in_context_keeps_to_the_search_context() {
|
||||
use ide_search::SearchContext as C;
|
||||
let text = "foo(\"foo\"); // foo\nfoo\n";
|
||||
let plain = "foo // foo\n";
|
||||
let cases = [
|
||||
(C::Any, "x(\"x\"); // x\nx\n", "x // x\n"),
|
||||
(C::InComments, "foo(\"foo\"); // x\nfoo\n", plain),
|
||||
(C::InStringLiterals, "foo(\"x\"); // foo\nfoo\n", plain),
|
||||
(C::ExceptComments, "x(\"x\"); // foo\nx\n", "x // x\n"),
|
||||
(C::ExceptStringLiterals, "x(\"foo\"); // x\nx\n", "x // x\n"),
|
||||
(C::ExceptCommentsAndStringLiterals, "x(\"foo\"); // foo\nx\n", "x // x\n"),
|
||||
];
|
||||
for (context, in_rs, in_txt) in cases {
|
||||
let docs = FakeDocs::with(&[("a.rs", text), ("b.txt", plain)]);
|
||||
let q = SearchQuery { context, ..query("foo") };
|
||||
let t = targets(&["a.rs", "b.txt"]);
|
||||
replace_files_in_context(&docs, &q, "x", false, &t, Some(&toy_literals), &CancellationToken::new(), &|_| {})
|
||||
.unwrap();
|
||||
assert_eq!((docs.text("a.rs").as_str(), docs.text("b.txt").as_str()), (in_rs, in_txt), "{context:?}");
|
||||
}
|
||||
}
|
||||
@@ -132,36 +132,6 @@ fn whole_word() {
|
||||
assert_eq!(views[0].matches[0].ranges, vec![(0, 3), (27, 30), (32, 35)]);
|
||||
}
|
||||
|
||||
/// IDEA's whole word: a word boundary is needed only at an edge where the match has an
|
||||
/// identifier character; a punctuation edge only needs a different character beside it.
|
||||
#[test]
|
||||
fn whole_word_needs_a_boundary_only_at_identifier_edges() {
|
||||
let starts = |text: &str, q: SearchQuery| -> Vec<usize> {
|
||||
let q = SearchQuery { whole_word: true, ..q };
|
||||
ide_search::match_ranges(text, &q).unwrap().into_iter().map(|r| r.0).collect()
|
||||
};
|
||||
let text = "doWork(arg); redoWork(x); list: string[] = [];";
|
||||
assert_eq!(starts(text, query("doWork(")), [0]);
|
||||
assert_eq!(starts(text, query("(arg)")), [6]);
|
||||
assert_eq!(starts(text, query("[]")), [38, 43]);
|
||||
assert_eq!(starts(text, query("list")), [26]);
|
||||
assert_eq!(starts("a == b; c === d", query("==")), [2]);
|
||||
// `$` is part of an identifier (Java, Kotlin, JavaScript).
|
||||
assert_eq!(starts("foo$bar foo", query("foo")), [8]);
|
||||
// After an escape such as `\n`, a word starts.
|
||||
assert_eq!(starts(r#"s = "\nfoo";"#, query("foo")), [7]);
|
||||
assert_eq!(starts("é1 1 éé", query("1")), [4]);
|
||||
// Regex matches follow the same rule.
|
||||
assert_eq!(starts(text, regex(r"\w+\(")), [0, 13]);
|
||||
assert_eq!(starts(text, regex(r"\[\]")), [38, 43]);
|
||||
|
||||
let p = project(&[("a.ts", text.as_bytes())]);
|
||||
let (views, summary) = run(p.path(), &SearchQuery { whole_word: true, ..query("[]") });
|
||||
assert_eq!((summary.matches, views[0].matches[0].ranges.clone()), (2, vec![(38, 40), (43, 45)]));
|
||||
let (out, n) = replace_in_text(text, &SearchQuery { whole_word: true, ..query("doWork(") }, "run(").unwrap();
|
||||
assert_eq!((out.as_str(), n), ("run(arg); redoWork(x); list: string[] = [];", 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_regex_is_reported() {
|
||||
let p = project(&[("a.txt", b"x\n")]);
|
||||
@@ -461,41 +431,6 @@ fn long_lines_are_truncated() {
|
||||
assert_eq!(second.text, "short needle");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_match_of_a_long_line_is_reported_in_its_own_window() {
|
||||
let long = format!("a='needle';{}b='needle';{}needle!\n", "x".repeat(2000), "y".repeat(2000));
|
||||
let p = project(&[("min.js", long.as_bytes())]);
|
||||
let (views, summary) = run(p.path(), &query("needle"));
|
||||
assert_eq!(summary.matches, 3);
|
||||
let lines = &views[0].matches;
|
||||
assert_eq!(lines.len(), 3, "one window per far-apart match");
|
||||
let line_utf16: Vec<u16> = long.trim_end().encode_utf16().collect();
|
||||
let mut starts = Vec::new();
|
||||
for m in lines {
|
||||
assert_eq!(m.line, 0);
|
||||
assert!(m.text.encode_utf16().count() <= 500);
|
||||
let [(a, b)] = m.ranges[..] else { panic!("{:?}", m.ranges) };
|
||||
let text: Vec<u16> = m.text.encode_utf16().collect();
|
||||
assert_eq!(String::from_utf16(&text[a as usize..b as usize]).unwrap(), "needle");
|
||||
let col = (m.text_offset + a) as usize;
|
||||
assert_eq!(String::from_utf16(&line_utf16[col..col + 6]).unwrap(), "needle");
|
||||
starts.push(ide_core::Pos::new(0, m.text_offset + a));
|
||||
}
|
||||
// The reported positions are the ones Replace takes: all of them are replaced.
|
||||
let edits = ide_search::replacement_edits(&long, &query("needle"), "pin", false, Some(&starts)).unwrap();
|
||||
assert_eq!(edits.len(), 3);
|
||||
assert!(!ide_search::apply_edits(&long, &edits).contains("needle"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_limit_counts_every_match_of_a_long_line() {
|
||||
let long = format!("needle{}needle{}needle\n", "x".repeat(1000), "y".repeat(1000));
|
||||
let p = project(&[("min.js", long.as_bytes())]);
|
||||
let (views, summary) = run(p.path(), &SearchQuery { max_matches: 2, ..query("needle") });
|
||||
assert!(summary.limit_hit);
|
||||
assert_eq!((summary.matches, total(&views)), (2, 2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multi_line_matches() {
|
||||
let p = project(&[("a.rs", b"fn foo() {\n bar();\n}\nfoo\nbar\n")]);
|
||||
|
||||
@@ -315,41 +315,6 @@ mod tests {
|
||||
assert_eq!(skipped.all().len(), 2);
|
||||
}
|
||||
|
||||
/// A workspace: members in repositories of their own (one with a nested repository, not a
|
||||
/// submodule), a plain folder, and a member that is a subfolder of a bigger repository; the
|
||||
/// container's agent folder links to each member and must not add a repository again.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn workspace_members_bring_their_repositories_once() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let (api, web, plain, mono) = (base.join("api"), base.join("web"), base.join("plain"), base.join("mono"));
|
||||
git_init(&api);
|
||||
git_init(&api.join("libs/sdk"));
|
||||
git_init(&web);
|
||||
std::fs::create_dir_all(&plain).unwrap();
|
||||
git_init(&mono);
|
||||
let docs = mono.join("docs");
|
||||
std::fs::create_dir_all(&docs).unwrap();
|
||||
let container = base.join("ws");
|
||||
let links = container.join(".openidea/agent-root");
|
||||
std::fs::create_dir_all(&links).unwrap();
|
||||
for (name, target) in [("api", &api), ("web", &web), ("plain", &plain), ("docs", &docs)] {
|
||||
std::os::unix::fs::symlink(target, links.join(name)).unwrap();
|
||||
// A link elsewhere in the container: never followed either.
|
||||
std::os::unix::fs::symlink(target, container.join(name)).unwrap();
|
||||
}
|
||||
|
||||
let roots = [container.clone(), api.clone(), web.clone(), plain.clone(), docs.clone()];
|
||||
let repos = Repos::discover_roots(&roots, &|_| false).unwrap();
|
||||
let found: Vec<&Path> = repos.all().iter().map(|r| r.root()).collect();
|
||||
assert_eq!(found, [api.as_path(), &api.join("libs/sdk"), &mono, &web]);
|
||||
let file = api.join("libs/sdk/lib.rs");
|
||||
assert_eq!(repos.for_path(&file).unwrap().root(), api.join("libs/sdk"), "a nested file is its own repo's");
|
||||
assert_eq!(repos.for_path(&docs.join("a.md")).unwrap().root(), mono, "a subfolder member is its repo's");
|
||||
assert!(repos.for_path(&plain.join("x")).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn side_by_side_repositories_without_an_enclosing_one() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -235,12 +235,6 @@ fn gix_status(r: &Repo, ignored: &IgnoredNames) -> IdeResult<Entries> {
|
||||
Ok((map, conflicts))
|
||||
}
|
||||
|
||||
/// Keeps `git status` from rewriting the index with refreshed stat data. Such a write is not
|
||||
/// one of ours to the watcher, so it would schedule another refresh, which runs git again (#4792).
|
||||
fn read_only() -> [(&'static str, &'static std::ffi::OsStr); 1] {
|
||||
[("GIT_OPTIONAL_LOCKS", std::ffi::OsStr::new("0"))]
|
||||
}
|
||||
|
||||
/// `git status --porcelain=v2`: what git lists, unreadable directories skipped.
|
||||
/// In Restricted Mode git compares content without the repository's clean/process
|
||||
/// filters and doesn't ask submodules for their own status (which runs their config).
|
||||
@@ -251,7 +245,7 @@ fn cli_status(r: &Repo, ignored: &IgnoredNames) -> IdeResult<Entries> {
|
||||
if !crate::execution_allowed() {
|
||||
args.push("--ignore-submodules=dirty");
|
||||
}
|
||||
let out = crate::cli::run_env(r.root(), &args, None, &read_only())?;
|
||||
let out = crate::cli::run(r.root(), &args, None)?;
|
||||
Ok(parse_porcelain_v2(&String::from_utf8_lossy(&out.stdout), ignored))
|
||||
}
|
||||
|
||||
@@ -266,7 +260,7 @@ fn cli_status_paths(r: &Repo, ignored: &IgnoredNames, paths: &[String]) -> IdeRe
|
||||
}
|
||||
args.push("--");
|
||||
args.extend(paths.iter().map(String::as_str));
|
||||
let out = crate::cli::run_env(r.root(), &args, None, &read_only())?;
|
||||
let out = crate::cli::run(r.root(), &args, None)?;
|
||||
Ok(parse_porcelain_v2(&String::from_utf8_lossy(&out.stdout), ignored))
|
||||
}
|
||||
|
||||
@@ -403,29 +397,6 @@ mod tests {
|
||||
assert!(staged.stdout.is_empty(), "{}", String::from_utf8_lossy(&staged.stdout));
|
||||
}
|
||||
|
||||
/// #4792: the dirty-scope `git status` must not rewrite the index after refreshing stale
|
||||
/// stat data, or the watcher sees a foreign index write and refreshes again.
|
||||
#[test]
|
||||
fn git_status_of_paths_leaves_the_index_alone() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = tmp.path();
|
||||
git(dir, &["init", "-q"]);
|
||||
git(dir, &["config", "user.name", "Test User"]);
|
||||
git(dir, &["config", "user.email", "[email protected]"]);
|
||||
git(dir, &["config", "commit.gpgsign", "false"]);
|
||||
std::fs::write(dir.join("a.txt"), "a\n").unwrap();
|
||||
commit_all(dir, "base");
|
||||
// Same content, new stat data: plain `git status` would refresh and write the index.
|
||||
std::thread::sleep(std::time::Duration::from_millis(1100));
|
||||
std::fs::write(dir.join("a.txt"), "a\n").unwrap();
|
||||
let index = dir.join(".git/index");
|
||||
let before = std::fs::read(&index).unwrap();
|
||||
|
||||
let repo = Repo::discover(dir).unwrap().expect("repository found");
|
||||
assert!(status_paths(&repo, &["a.txt".to_owned()]).unwrap().is_empty());
|
||||
assert_eq!(std::fs::read(&index).unwrap(), before, "git status rewrote the index");
|
||||
}
|
||||
|
||||
/// git's porcelain answer (used when gitoxide can't read the tree) matches gitoxide's.
|
||||
#[test]
|
||||
fn git_and_gitoxide_report_the_same_status() {
|
||||
|
||||
@@ -422,8 +422,6 @@ impl Documents {
|
||||
}
|
||||
// Validate project rules before path resolution can erase linked components.
|
||||
crate::file_ops::validate_workspace_edit_paths(edit)?;
|
||||
// Editors know the paths as the edit named them, before link resolution.
|
||||
let moves = edit.moves();
|
||||
let mut edit = normalize_edit(edit)?;
|
||||
let captured = !edit.preconditions.is_empty();
|
||||
crate::file_ops::expand_workspace_edit(&mut edit)?;
|
||||
@@ -503,7 +501,7 @@ impl Documents {
|
||||
});
|
||||
}
|
||||
history.prune(SystemTime::now(), MAX_HISTORY_BYTES, MAX_HISTORY_AGE);
|
||||
self.sink.emit(IdeEvent::WorkspaceEditApplied { id, paths: affected, moves, by_agent });
|
||||
self.sink.emit(IdeEvent::WorkspaceEditApplied { id, paths: affected, by_agent });
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -4,13 +4,20 @@
|
||||
|
||||
use crate::documents::Documents;
|
||||
use crate::history::LocalHistory;
|
||||
pub use ide_core::FileMove;
|
||||
use ide_core::{FileEdit, IdeError, IdeResult, WorkspaceEdit};
|
||||
use parking_lot::Mutex;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// One file or folder move.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct FileMove {
|
||||
pub from: ide_core::IpcPath,
|
||||
pub to: ide_core::IpcPath,
|
||||
}
|
||||
|
||||
/// What [`FileMoves::undo`] did.
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
|
||||
@@ -898,16 +898,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn commit_default_inclusion_persists() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let store = SettingsStore::load(tmp.path(), None);
|
||||
assert!(store.effective().vcs.commit.include_changes_by_default);
|
||||
let settings = store.set(SettingsScope::Global, "vcs.commit.includeChangesByDefault", json!(false)).unwrap();
|
||||
assert!(!settings.vcs.commit.include_changes_by_default);
|
||||
assert!(!SettingsStore::load(tmp.path(), None).effective().vcs.commit.include_changes_by_default);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inspection_profiles_live_in_their_layers() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use ide_core::{ChangeSet, FileEdit, FileMove, LanguageId, NullSink, Pos, Range, TextChange, TextEdit, WorkspaceEdit};
|
||||
use ide_core::{ChangeSet, FileEdit, LanguageId, NullSink, Pos, Range, TextChange, TextEdit, WorkspaceEdit};
|
||||
use ide_core::{IdeEvent, error::ErrorKind};
|
||||
use ide_workspace::Documents;
|
||||
use parking_lot::Mutex;
|
||||
@@ -162,45 +162,6 @@ fn undo_id(events: &Mutex<Vec<IdeEvent>>) -> u32 {
|
||||
.expect("successful transaction has one undo record")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn applied_event_lists_the_files_the_edit_renamed() {
|
||||
for by_agent in [false, true] {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let from = tmp.path().join("ListPrice.java");
|
||||
let to = tmp.path().join("BasePrice.java");
|
||||
let user = tmp.path().join("BulkDiscount.java");
|
||||
std::fs::write(&from, "old").unwrap();
|
||||
std::fs::write(&user, "old\n").unwrap();
|
||||
let (docs, events) = recorded_documents();
|
||||
let edit = WorkspaceEdit {
|
||||
files: vec![edit(&user, "new"), FileEdit::Rename { from: from.clone().into(), to: to.clone().into() }],
|
||||
..Default::default()
|
||||
};
|
||||
if by_agent { docs.apply_agent_workspace_edit(&edit) } else { docs.apply_workspace_edit(&edit) }.unwrap();
|
||||
let moves = events
|
||||
.lock()
|
||||
.iter()
|
||||
.find_map(|event| match event {
|
||||
IdeEvent::WorkspaceEditApplied { moves, .. } => Some(moves.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(moves, vec![FileMove { from: from.into(), to: to.into() }], "by_agent: {by_agent}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn applied_event_lists_no_moves_for_text_edits() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let path = tmp.path().join("a.txt");
|
||||
std::fs::write(&path, "old\n").unwrap();
|
||||
let (docs, events) = recorded_documents();
|
||||
docs.apply_workspace_edit(&WorkspaceEdit { files: vec![edit(&path, "new")], ..Default::default() }).unwrap();
|
||||
assert!(
|
||||
events.lock().iter().any(|e| matches!(e, IdeEvent::WorkspaceEditApplied { moves, .. } if moves.is_empty()))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undo_keeps_the_encoding_chosen_for_a_file_opened_after_the_edit() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -83,8 +83,6 @@ On your own messages you can **Edit** (the messages after it are replaced; files
|
||||
|
||||
In an existing chat, open **Model › Refresh models** to discover newly available models without sending a message or changing the selection. If the agent can't switch in place, the choice stays pending. You can choose an effort level as soon as the provider reports the new model's options. On your next message, OpenIDEA reopens the same session and applies the model and any effort you selected before sending. If the session can't be reopened or rejects either choice, OpenIDEA restores the previous selection and reports the error without sending the message.
|
||||
|
||||
The model picker of an existing chat offers the agent's current model list, the same one New Task uses, plus the model the chat runs. It doesn't depend on what that chat's session reported when it started, so a model found by a refresh in any chat or in New Task can be chosen in every chat of that agent.
|
||||
|
||||
**Focus Agent Input** defaults to `⌘L` on macOS and `Ctrl+L` on Windows / Linux in every built-in keymap. When focus is inside your writable task conversation, in either an editor tab or the tool window, it returns focus to the message input without changing your draft, caret position or selection—even when pressed repeatedly. It does not send a message or jump through message history.
|
||||
|
||||
With focus anywhere else, the same shortcut jumps to the message input of the task shown in an editor tab or the tool window (the one you used last, if several are shown), unless a panel claims the shortcut there: in a code editor `⌘L` / `Ctrl+L` keeps its editor meaning (for example Go to Line), and in a terminal on Windows / Linux `Ctrl+L` still reaches the shell. It does not apply to archived tasks, subagent conversations or the New Task page, and does not take focus from open popups or dialogs. To change or remove the binding, open **Settings › Keymap › Agents › Focus Agent Input**.
|
||||
@@ -141,14 +139,6 @@ Tasks are saved per project and survive restarts. When the agent supports resumi
|
||||
- **Agent Configs**: discovers servers already configured in `~/.copilot/mcp-config.json` (and installed Copilot CLI plugins), `~/.claude.json`, `~/.codex/config.toml`, `~/.cursor/mcp.json`, `~/.gemini/settings.json`, `~/.jetbrains/mcp/mcp.json`, `.mcp.json`, and `.vscode/mcp.json` so you can import them into Global or Project settings with one click. You can also add or edit servers via structured fields or raw `mcpServers` JSON (**Add from JSON**), and run **Test Connection** to inspect the tools a server advertises.
|
||||
- **Per-session (`MCP` / `/mcp`)**: in both **New Agent Task** and active task conversations, open **MCP** in the composer toolbar (or run `/mcp`) to enable or disable individual servers—including the built-in `openidea` server—for that task only, or click **Reset** to return to the inherited defaults.
|
||||
|
||||
### Agent skills
|
||||
|
||||
**Settings › Agents › Skills** lists every skill (`SKILL.md` folders) in one place, grouped by the folder it was found in: the project's `.agents/skills` and `.openidea/skills`, your `~/.agents/skills` (what `npx skills add` fills), and each CLI's own folders (`.claude/skills`, `.github/skills`, `.codex/skills`, `.cursor/skills`, `~/.claude/skills`, `~/.copilot/skills` and its installed plugins, `~/.codex/skills`, `~/.cursor/skills`). Symlinked copies of the same skill appear once, and expanding a row shows its canonical path and the `SKILL.md` validation result.
|
||||
|
||||
Each skill runs in one of three modes, set globally or per workspace without ever editing the skill's files: **Auto** (the model decides), **Slash only** (just `/name`), or **Off**. A workspace can turn a global skill off without prose rules in `AGENTS.md`; a skill the settings keep off shows as **Enable in Settings** in the session picker.
|
||||
|
||||
In the composer, `/skills` (or the **Add Context** menu) opens the per-session picker next to the MCP one: turn individual skills off for this task only, or **Reset** to the inherited modes. The `/` menu offers the active skills of every agent, and Claude Code, Copilot and Codex all receive the same set. Agents that only speak ACP keep their own `/` menu, so turning a skill off there stops OpenIDEA from offering it but is otherwise best-effort.
|
||||
|
||||
While the agent works, the line under the conversation says what it is doing: thinking, reading, editing, running a command, writing its reply.
|
||||
|
||||
## Add a custom agent
|
||||
|
||||
@@ -36,7 +36,7 @@ Enable or disable postfix completion, individual templates, `Tab` expansion and
|
||||
|
||||
## Emmet
|
||||
|
||||
In HTML, Vue, Svelte, JSX and TSX files, and in CSS, SCSS, Less and Sass, `⇥` / `Tab` expands Emmet abbreviations, for example `ul>li*3` or `m10`. In markup files, the editor context menu also has **Update Tag with Emmet**, which rewrites the tag at the caret from an abbreviation.
|
||||
In HTML, Vue and Svelte files, and in CSS, SCSS, Less and Sass, `⇥` / `Tab` expands Emmet abbreviations, for example `ul>li*3` or `m10`. In markup files, the editor context menu also has **Update Tag with Emmet**, which rewrites the tag at the caret from an abbreviation.
|
||||
|
||||
## Write your own templates
|
||||
|
||||
|
||||
@@ -96,7 +96,7 @@ With **Do not step into library scripts** (**Settings › Build, Execution, Depl
|
||||
|
||||
## Framework support
|
||||
|
||||
- **React**: JSX and TSX get their own highlighting modes and full TypeScript server support. Typing `>` closes the tag, renaming an opening or closing tag renames its partner, and completing a prop name or typing `=` after one inserts `""` for string props or `{}` for others (from the prop's type). `⇥` / `Tab` expands Emmet abbreviations among an element's children or after `return` / `=>`: `.card` becomes `<div className="card"></div>`.
|
||||
- **React**: JSX and TSX get their own highlighting modes and full TypeScript server support. There is no React-specific tooling beyond that.
|
||||
- **Vue**: `.vue` files are highlighted per block and served by Vue Language Server in hybrid mode. In a Vue CLI project without `tsconfig.json`, webpack's `resolve.alias` entries (such as `@/`) are read so imports resolve. Prettier formats `.vue` files. Emmet works in templates.
|
||||
- **Svelte**: Svelte Language Server; highlighting uses the HTML mode (script as TypeScript, style as CSS). Emmet works in markup.
|
||||
- **Astro**: Astro Language Server with its own highlighting mode. It needs Node.js; if it can't find one, select it in **Settings › Languages & Frameworks › JavaScript Runtime**.
|
||||
@@ -109,3 +109,4 @@ With **Do not step into library scripts** (**Settings › Build, Execution, Depl
|
||||
- Bun runs but can't be debugged: its inspector uses the WebKit protocol, which vscode-js-debug can't attach to.
|
||||
- Deno has run and debug support but no Deno language server; Deno files use the TypeScript servers.
|
||||
- Coverage of Deno tasks is not supported.
|
||||
- Emmet expands in HTML, Vue and Svelte, not in JSX.
|
||||
@@ -83,8 +83,6 @@ Codex 有自己的项目信任设置。如果它禁用了当前项目的 `.codex
|
||||
|
||||
在已有对话中,打开**模型 › 刷新模型**即可查找新上线的模型,不会发送消息或更改当前选择。如果 agent 无法直接切换,所选模型会保持待应用状态。提供商返回新模型支持的思考强度后,你就可以选择强度。发送下一条消息时,OpenIDEA 会先恢复原会话并应用所选模型和思考强度,再发送消息。如果无法恢复会话,或原会话不接受其中任何一项,OpenIDEA 会还原之前的选择并提示错误,不会发送该消息。
|
||||
|
||||
已有对话的模型选择器会列出该 agent 当前的模型列表(与新任务使用的相同),外加该对话正在使用的模型。它不依赖该对话会话启动时报告的列表,因此在任一对话或新任务中通过刷新找到的模型,可在该 agent 的所有对话中选用。
|
||||
|
||||
所有内置按键映射中,**聚焦 Agent 输入框** 的默认快捷键都是 macOS 上的 `⌘L`、Windows / Linux 上的 `Ctrl+L`。焦点位于你自己的可输入任务对话中时,无论对话显示在编辑器标签页还是工具窗口中,它都会将焦点移回消息输入框,保留草稿、光标位置和选区;重复按下也不会改变这些内容。它不会发送消息,也不会跳转消息历史。
|
||||
|
||||
焦点位于其他位置时,同一快捷键会跳转到编辑器标签页或工具窗口中显示的任务的消息输入框(显示多个时,选择你最近使用的那个),除非该位置有面板占用此快捷键:在代码编辑器中,`⌘L` / `Ctrl+L` 保留编辑器含义(例如“转到行”);在 Windows / Linux 的终端中,`Ctrl+L` 仍会发送给 shell。此快捷键不适用于已归档任务、子 agent 对话或“新建任务”页面,也不会从打开的弹出窗口或对话框中抢走焦点。要修改或移除绑定,请打开 **设置 › 按键映射 › 智能体 › 聚焦 Agent 输入框**。
|
||||
@@ -141,14 +139,6 @@ agent 运行过一个任务后,新任务会以它自动批准所有操作的
|
||||
- **智能体配置**:自动发现 `~/.copilot/mcp-config.json`(及已安装的 Copilot CLI 插件)、`~/.claude.json`、`~/.codex/config.toml`、`~/.cursor/mcp.json`、`~/.gemini/settings.json`、`~/.jetbrains/mcp/mcp.json`、`.mcp.json` 和 `.vscode/mcp.json` 中已配置的服务器,可一键导入到全局或项目设置。添加或编辑服务器时既可使用表单,也可直接粘贴 `mcpServers` JSON(**从 JSON 添加**),并可通过 **测试连接** 查看服务器声明的工具列表。
|
||||
- **按会话覆盖(`MCP` / `/mcp`)**:在 **新建 Agent 任务** 和进行中的任务对话中,单击输入框工具栏的 **MCP**(或输入 `/mcp`),即可仅针对当前任务开启或关闭任意服务器(包括内置的 `openidea` 服务器),或点击 **重置** 恢复继承的默认状态。
|
||||
|
||||
### 智能体技能
|
||||
|
||||
**设置 › 智能体 › 技能** 把所有技能(`SKILL.md` 文件夹)汇总在一个列表里,并按发现它们的文件夹分组:项目的 `.agents/skills` 与 `.openidea/skills`、你的 `~/.agents/skills`(即 `npx skills add` 填充的目录),以及各 CLI 自己的文件夹(`.claude/skills`、`.github/skills`、`.codex/skills`、`.cursor/skills`、`~/.claude/skills`、`~/.copilot/skills` 及其已安装插件、`~/.codex/skills`、`~/.cursor/skills`)。同一技能的符号链接副本只显示一次,展开一行可以看到其规范路径与 `SKILL.md` 的校验结果。
|
||||
|
||||
每个技能有三种运行模式,可全局或按工作区设置,且从不改动技能自身的文件:**自动**(由模型决定)、**仅斜杠**(只通过 `/名称` 调用)或 **关闭**。工作区可以关闭一个全局技能,而无需在 `AGENTS.md` 里写文字规则;被设置关闭的技能在会话选择器中会显示为 **在设置中启用**。
|
||||
|
||||
在输入框中,`/skills`(或 **添加上下文** 菜单)会打开与 MCP 并排的会话技能选择器:仅为当前任务关闭单个技能,或点击 **重置** 恢复继承的模式。`/` 菜单会列出所有智能体的活动技能,Claude Code、Copilot 与 Codex 收到的是同一套技能。只讲 ACP 协议的智能体保留自己的 `/` 菜单,因此在那里关闭技能只会让 OpenIDEA 不再提供它,其余尽力而为。
|
||||
|
||||
agent 工作时,对话下方的状态行显示它正在做什么:思考、读取、编辑、运行命令、输出回复。
|
||||
|
||||
## 添加自定义 agent
|
||||
|
||||
@@ -36,7 +36,7 @@ items.for → for (var item : items) { … }
|
||||
|
||||
## Emmet
|
||||
|
||||
在 HTML、Vue、Svelte、JSX、TSX 文件以及 CSS、SCSS、Less、Sass 中,`⇥` / `Tab` 会展开 Emmet 缩写,例如 `ul>li*3` 或 `m10`。在标记语言文件中,编辑器右键菜单还提供 **使用 Emmet 更新标签**,用一个缩写改写光标所在的标签。
|
||||
在 HTML、Vue、Svelte 文件以及 CSS、SCSS、Less、Sass 中,`⇥` / `Tab` 会展开 Emmet 缩写,例如 `ul>li*3` 或 `m10`。在标记语言文件中,编辑器右键菜单还提供 **使用 Emmet 更新标签**,用一个缩写改写光标所在的标签。
|
||||
|
||||
## 编写自己的模板
|
||||
|
||||
|
||||
@@ -96,7 +96,7 @@ Jest 和 Vitest 的输出会解析成测试树,支持 **重新运行失败的
|
||||
|
||||
## 框架支持
|
||||
|
||||
- **React**:JSX 和 TSX 有各自的高亮模式,并获得完整的 TypeScript 服务器支持。输入 `>` 会自动闭合标签,修改开始或结束标签名会同步修改另一端,补全属性名或在属性名后输入 `=` 会按属性类型插入 `""`(字符串)或 `{}`(其他类型)。在元素的子内容中或 `return` / `=>` 之后,`⇥` / `Tab` 会展开 Emmet 缩写:`.card` 会变成 `<div className="card"></div>`。
|
||||
- **React**:JSX 和 TSX 有各自的高亮模式,并获得完整的 TypeScript 服务器支持;除此之外没有 React 专属功能。
|
||||
- **Vue**:`.vue` 文件按块高亮,由 Vue Language Server 以 hybrid 模式提供支持。没有 `tsconfig.json` 的 Vue CLI 项目会读取 webpack 的 `resolve.alias`(如 `@/`),让 import 能正确解析。Prettier 可格式化 `.vue` 文件,模板中可用 Emmet。
|
||||
- **Svelte**:使用 Svelte Language Server;高亮沿用 HTML 模式(script 按 TypeScript、style 按 CSS),标记部分可用 Emmet。
|
||||
- **Astro**:使用 Astro Language Server,有专门的高亮模式。它需要 Node.js,找不到时请在 **设置 › 语言和框架 › JavaScript 运行时** 中选择。
|
||||
@@ -109,3 +109,4 @@ Jest 和 Vitest 的输出会解析成测试树,支持 **重新运行失败的
|
||||
- Bun 可以运行但无法调试:它的 inspector 使用 WebKit 协议,vscode-js-debug 无法附加。
|
||||
- Deno 支持运行和调试,但没有 Deno 语言服务器,Deno 文件使用 TypeScript 服务器。
|
||||
- 不支持 Deno task 的覆盖率。
|
||||
- Emmet 只在 HTML、Vue 和 Svelte 中展开,JSX 中不可用。
|
||||
@@ -1,74 +0,0 @@
|
||||
import { expect, test } from "./fixtures";
|
||||
|
||||
test("Appearance keeps themes and UI font controls grouped across Settings widths", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 1120, height: 800 });
|
||||
await page.keyboard.press("Meta+,");
|
||||
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
|
||||
const search = dialog.getByRole("textbox", { name: "Search settings" });
|
||||
await search.fill("Use custom font");
|
||||
await dialog.getByRole("treeitem", { name: "Appearance", exact: true }).click();
|
||||
await search.clear();
|
||||
|
||||
const theme = dialog.getByRole("button", { name: "Theme", exact: true });
|
||||
const sync = dialog.getByRole("checkbox", { name: "Sync with OS", exact: true });
|
||||
const preferences = dialog.getByRole("button", { name: "Preferred themes", exact: true });
|
||||
const more = dialog.getByRole("button", { name: "Get more themes", exact: true });
|
||||
const font = dialog.getByRole("combobox", { name: "UI font", exact: true });
|
||||
const fallback = dialog.getByRole("combobox", { name: "UI fallback font", exact: true });
|
||||
const size = dialog.getByRole("textbox", { name: "UI font size", exact: true });
|
||||
const custom = dialog.getByRole("checkbox", { name: "Use custom font:", exact: true });
|
||||
await expect(preferences).toBeDisabled();
|
||||
await expect(font).toBeDisabled();
|
||||
await expect(size).toBeDisabled();
|
||||
await expect(fallback).toBeDisabled();
|
||||
|
||||
const [themeBox, gearBox, linkBox, fontBox, sizeBox, fallbackBox] = await Promise.all(
|
||||
[theme, preferences, more, font, size, fallback].map((control) => control.boundingBox()),
|
||||
);
|
||||
if (!themeBox || !gearBox || !linkBox || !fontBox || !sizeBox || !fallbackBox) {
|
||||
throw new Error("Missing Appearance control bounds");
|
||||
}
|
||||
expect(linkBox.y).toBeGreaterThan(themeBox.y + themeBox.height);
|
||||
expect(gearBox.x).toBeGreaterThan(themeBox.x + themeBox.width);
|
||||
expect(gearBox.y + gearBox.height / 2).toBeCloseTo(themeBox.y + themeBox.height / 2, 0);
|
||||
expect(sizeBox.y).toBeCloseTo(fontBox.y, 0);
|
||||
expect(sizeBox.x).toBeGreaterThan(fontBox.x + fontBox.width);
|
||||
expect(fallbackBox.x).toBeCloseTo(fontBox.x, 0);
|
||||
expect(fallbackBox.y).toBeGreaterThan(fontBox.y);
|
||||
|
||||
await sync.check();
|
||||
await expect(theme).toBeDisabled();
|
||||
for (const width of [580, 520]) {
|
||||
await page.setViewportSize({ width, height: 800 });
|
||||
await preferences.click();
|
||||
const popup = page.getByRole("dialog", { name: "Preferred themes", exact: true });
|
||||
const light = popup.getByRole("button", { name: "Preferred light theme", exact: true });
|
||||
const dark = popup.getByRole("button", { name: "Preferred dark theme", exact: true });
|
||||
await expect(light).toBeInViewport({ ratio: 1 });
|
||||
await expect(dark).toBeInViewport({ ratio: 1 });
|
||||
const [lightBox, darkBox] = await Promise.all([light.boundingBox(), dark.boundingBox()]);
|
||||
if (!lightBox || !darkBox) throw new Error("Missing preferred theme bounds");
|
||||
expect(lightBox.x).toBeCloseTo(darkBox.x, 0);
|
||||
expect(lightBox.width).toBeCloseTo(darkBox.width, 0);
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(popup).toBeHidden();
|
||||
for (const field of [font, size, fallback]) await expect(field).toBeInViewport({ ratio: 1 });
|
||||
const [narrowFont, narrowSize, narrowFallback] = await Promise.all(
|
||||
[font, size, fallback].map((control) => control.boundingBox()),
|
||||
);
|
||||
if (!narrowFont || !narrowSize || !narrowFallback) throw new Error("Missing narrow font control bounds");
|
||||
expect(narrowSize.y).toBeGreaterThan(narrowFont.y);
|
||||
expect(narrowFallback.x).toBeCloseTo(narrowFont.x, 0);
|
||||
}
|
||||
|
||||
await custom.check();
|
||||
await font.fill("Inter");
|
||||
await size.fill("15");
|
||||
await fallback.fill("Noto Sans CJK SC");
|
||||
await fallback.press("Enter");
|
||||
await expect(font).toHaveValue("Inter");
|
||||
await expect(size).toHaveValue("15");
|
||||
await expect(fallback).toHaveValue("Noto Sans CJK SC");
|
||||
await dialog.getByRole("button", { name: "Cancel", exact: true }).click();
|
||||
await expect(dialog).toBeHidden();
|
||||
});
|
||||
@@ -1,95 +0,0 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import type { PatchFile } from "../src/bindings";
|
||||
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
|
||||
|
||||
const repo = "/dev/billing";
|
||||
const path = "/tmp/release-2026/requests/adjust-invoices.patch";
|
||||
const patch = "diff --git a/ledger/invoice.ts b/ledger/invoice.ts";
|
||||
const invoice: PatchFile = {
|
||||
path: "ledger/invoice.ts",
|
||||
oldPath: null,
|
||||
kind: "modified",
|
||||
added: 3,
|
||||
removed: 1,
|
||||
binary: false,
|
||||
applies: true,
|
||||
};
|
||||
|
||||
async function openPatch(page: Page, source: "file" | "clipboard", files: PatchFile[]) {
|
||||
await page.evaluate(
|
||||
async ({ source, repo, path, patch, files }) => {
|
||||
const handlers = window.__ipc.handlers;
|
||||
handlers.fs_read_text = () => patch;
|
||||
handlers.clipboard_text = () => patch;
|
||||
handlers.vcs_patch_preview = () => files;
|
||||
handlers.vcs_apply_patch = () => ({ applied: [files[0]?.path], conflicts: [] });
|
||||
const store = "/src/features/vcs/store.ts";
|
||||
const context = "/src/platform/context.ts";
|
||||
const actions = "/src/platform/actions.ts";
|
||||
(await import(/* @vite-ignore */ store)).useVcs.setState({ available: true, root: repo, repo, roots: [repo] });
|
||||
(await import(/* @vite-ignore */ context)).setContext("vcsAvailable", true);
|
||||
const { executeAction } = await import(/* @vite-ignore */ actions);
|
||||
await executeAction(source === "file" ? "vcs.applyPatch" : "vcs.applyPatchFromClipboard", path);
|
||||
},
|
||||
{ source, repo, path, patch, files },
|
||||
);
|
||||
}
|
||||
|
||||
test("Apply Patch keeps the source, repository and file status aligned in a narrow dialog", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 485, height: 490 });
|
||||
await stubDesktop(page);
|
||||
await openPatch(page, "file", [
|
||||
invoice,
|
||||
{ ...invoice, path: "apps/batch/ledger/international/settlement/settle-invoice.ts", applies: false },
|
||||
...Array.from({ length: 20 }, (_, i) => ({ ...invoice, path: `ledger/settlement-${i + 1}.ts` })),
|
||||
]);
|
||||
const dialog = page.getByRole("dialog", { name: "Apply Patch: adjust-invoices.patch", exact: true });
|
||||
const source = dialog.getByRole("textbox", { name: "Patch source", exact: true });
|
||||
const target = dialog.getByRole("textbox", { name: "Repository", exact: true });
|
||||
const list = dialog.getByRole("listbox", { name: "Patch files", exact: true });
|
||||
|
||||
await expect(source).toHaveValue(path);
|
||||
await expect(source).not.toBeEditable();
|
||||
await expect(target).toHaveValue(repo);
|
||||
await expect(dialog.getByRole("heading", { name: "Patch files", exact: true })).toBeVisible();
|
||||
await expect(dialog.getByText("22 files", { exact: true })).toBeVisible();
|
||||
expect((await source.boundingBox())!.y).toBeLessThan((await target.boundingBox())!.y);
|
||||
expect((await target.boundingBox())!.y).toBeLessThan((await list.boundingBox())!.y);
|
||||
|
||||
const stats = list.getByText("+3 −1", { exact: true });
|
||||
const first = (await stats.nth(0).boundingBox())!;
|
||||
const second = (await stats.nth(1).boundingBox())!;
|
||||
expect(Math.abs(first.x - second.x)).toBeLessThan(1);
|
||||
await expect(list.getByLabel("Does not apply cleanly", { exact: true })).toBeInViewport({ ratio: 1 });
|
||||
await expect(dialog.getByRole("status")).toHaveText("1 file will be merged; conflicts open in the merge tool");
|
||||
await list.press("End");
|
||||
await expect(list.getByText("settlement-20.ts", { exact: true })).toBeInViewport({ ratio: 1 });
|
||||
await expect(dialog.getByRole("button", { name: "Apply", exact: true })).toBeInViewport({ ratio: 1 });
|
||||
expect(await dialog.locator("[data-dialog-body]").evaluate((el) => el.scrollWidth - el.clientWidth)).toBe(0);
|
||||
await dialog.getByRole("button", { name: "Cancel", exact: true }).click();
|
||||
await expect(dialog).toBeHidden();
|
||||
expect(await ipcCalls(page, "vcs_apply_patch")).toEqual([]);
|
||||
});
|
||||
|
||||
test("Apply Patch previews clipboard contents and applies them to the previewed repository", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await stubDesktop(page);
|
||||
await openPatch(page, "clipboard", []);
|
||||
const dialog = page.getByRole("dialog", { name: "Apply Patch: Clipboard", exact: true });
|
||||
await expect(dialog.getByRole("textbox", { name: "Patch source", exact: true })).toHaveValue("Clipboard");
|
||||
await expect(dialog.getByText("No changes", { exact: true })).toBeVisible();
|
||||
const apply = dialog.getByRole("button", { name: "Apply", exact: true });
|
||||
await expect(apply).toBeDisabled();
|
||||
await dialog.getByRole("button", { name: "Cancel", exact: true }).click();
|
||||
await expect(dialog).toBeHidden();
|
||||
|
||||
await openPatch(page, "clipboard", [invoice]);
|
||||
await expect(dialog.getByText("1 file", { exact: true })).toBeVisible();
|
||||
await expect(apply).toBeEnabled();
|
||||
await apply.click();
|
||||
await expect(dialog).toBeHidden();
|
||||
await expect.poll(() => ipcCalls(page, "vcs_apply_patch")).toEqual([{ repo, patch }]);
|
||||
});
|
||||
@@ -1,18 +1,7 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import type { BuildModel, BuildTool, MavenDependency } from "../src/platform/ipc";
|
||||
import type { BuildModel, BuildTool } from "../src/platform/ipc";
|
||||
import { expect, stubDesktop, test } from "./fixtures";
|
||||
|
||||
const jsonCore: MavenDependency = {
|
||||
groupId: "com.example.json",
|
||||
artifactId: "json-core",
|
||||
version: "2.1.0",
|
||||
type: "jar",
|
||||
classifier: null,
|
||||
scope: "compile",
|
||||
optional: false,
|
||||
children: [],
|
||||
};
|
||||
|
||||
const model: BuildModel = {
|
||||
maven: {
|
||||
projects: [
|
||||
@@ -28,14 +17,7 @@ const model: BuildModel = {
|
||||
modules: [],
|
||||
aggregated: false,
|
||||
plugins: [],
|
||||
dependencies: [
|
||||
jsonCore,
|
||||
{
|
||||
...jsonCore,
|
||||
artifactId: "json-mapper",
|
||||
children: [{ ...jsonCore, version: "2.0.0", omitted: "conflict", conflictWith: "2.1.0" }],
|
||||
},
|
||||
],
|
||||
dependencies: [],
|
||||
profiles: [],
|
||||
javaVersion: 21,
|
||||
command: "mvn",
|
||||
@@ -115,45 +97,3 @@ for (const tool of ["maven", "gradle"] as const) {
|
||||
await expect(menu).toBeHidden();
|
||||
});
|
||||
}
|
||||
|
||||
test("Dependency Analyzer pairs its pane controls and stacks usages in a narrow editor", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 1360, height: 780 });
|
||||
await showTool(page, "maven");
|
||||
const toolActions = page.getByRole("toolbar", { name: "Maven actions" });
|
||||
await toolActions.getByRole("button", { name: "More Actions", exact: true }).click();
|
||||
await page.getByRole("menuitem", { name: "Analyze Dependencies…", exact: true }).click();
|
||||
|
||||
const filters = page.getByRole("toolbar", { name: "Dependency Analyzer", exact: true });
|
||||
const resolved = page.getByRole("heading", { name: "Resolved Dependencies", exact: true });
|
||||
const usages = page.getByRole("heading", { name: "Usages of com.example.json:json-core:2.1.0", exact: true });
|
||||
const dependencies = page.getByRole("tree", { name: "Dependencies", exact: true });
|
||||
const core = dependencies.getByRole("treeitem", { name: /^com\.example\.json:json-core\b/ });
|
||||
const treeMode = page.getByRole("button", { name: "Show as Tree", exact: true });
|
||||
const conflicts = filters.getByRole("button", { name: "Show conflicts only", exact: true });
|
||||
await expect(resolved).toBeVisible();
|
||||
await expect(filters.getByRole("button", { name: "Show as Tree" })).toHaveCount(0);
|
||||
await treeMode.click();
|
||||
await expect(treeMode).toHaveAttribute("aria-pressed", "true");
|
||||
await page.getByRole("button", { name: "Show as List", exact: true }).click();
|
||||
await conflicts.press("Space");
|
||||
await expect(conflicts).toHaveAttribute("aria-pressed", "true");
|
||||
await expect(dependencies.getByRole("treeitem")).toHaveCount(1);
|
||||
await core.click();
|
||||
await expect(usages).toBeVisible();
|
||||
await expect(page.getByText("omitted for conflict with 2.1.0")).toBeVisible();
|
||||
const wideLeft = (await resolved.boundingBox())!;
|
||||
const wideRight = (await usages.boundingBox())!;
|
||||
expect(Math.abs(wideLeft.y - wideRight.y)).toBeLessThan(1);
|
||||
expect(wideRight.x).toBeGreaterThan(wideLeft.x + wideLeft.width);
|
||||
|
||||
await page.setViewportSize({ width: 790, height: 780 });
|
||||
await expect
|
||||
.poll(async () => (await usages.boundingBox())!.y - (await resolved.boundingBox())!.y)
|
||||
.toBeGreaterThan(100);
|
||||
expect(Math.abs((await usages.boundingBox())!.x - (await resolved.boundingBox())!.x)).toBeLessThan(1);
|
||||
expect(await filters.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
|
||||
await expect(core).toHaveAttribute("aria-selected", "true");
|
||||
await expect(page.getByRole("button", { name: "Copy Coordinates" })).toBeInViewport({ ratio: 1 });
|
||||
});
|
||||
@@ -76,34 +76,6 @@ test("⌘K commits the checked changes with the typed message", async ({ workben
|
||||
await expect(changes.getByRole("checkbox", { name: "Include build.gradle.kts in commit" })).toBeHidden();
|
||||
});
|
||||
|
||||
test("turning off default inclusion starts Commit with all files unchecked", async ({ workbench: page }) => {
|
||||
await page.keyboard.press("Meta+,");
|
||||
const settings = page.getByRole("dialog", { name: "Settings", exact: true });
|
||||
const label = "Include changes in the commit by default";
|
||||
await settings.getByRole("textbox", { name: "Search settings" }).fill(label);
|
||||
await settings.getByRole("treeitem", { name: "Commit", exact: true }).click();
|
||||
const toggle = settings.getByRole("checkbox", { name: label, exact: true });
|
||||
await expect(toggle).toBeChecked();
|
||||
await toggle.click();
|
||||
await settings.getByRole("button", { name: "OK", exact: true }).click();
|
||||
await expect(settings).not.toBeVisible();
|
||||
|
||||
await stubRepository(page);
|
||||
await page.keyboard.press("Meta+k");
|
||||
const panel = page.getByRole("region", { name: "Commit", exact: true });
|
||||
const changes = panel.getByRole("tree", { name: "Changes" });
|
||||
const tracked = changes.getByRole("checkbox", { name: "Include build.gradle.kts in commit" });
|
||||
await expect(tracked).toHaveAttribute("aria-checked", "false");
|
||||
await expect(changes.getByRole("checkbox", { name: "Include Unversioned Files in commit" })).not.toBeChecked();
|
||||
await tracked.click();
|
||||
await expect(tracked).toBeChecked();
|
||||
await panel.getByRole("textbox", { name: "Commit message" }).fill("Commit the selected file");
|
||||
await panel.getByRole("button", { name: "Commit", exact: true }).click();
|
||||
await expect.poll(() => ipcCalls(page, "vcs_commit")).toHaveLength(1);
|
||||
const [committed] = await ipcCalls(page, "vcs_commit");
|
||||
expect(committed!.options).toMatchObject({ stage: [`${ROOT}/build.gradle.kts`] });
|
||||
});
|
||||
|
||||
test("commit message history opens above the message without an empty icon column", async ({ workbench: page }) => {
|
||||
await stubRepository(page);
|
||||
await page.keyboard.press("Meta+k");
|
||||
|
||||
@@ -2,7 +2,7 @@ import { expect, test } from "./fixtures";
|
||||
|
||||
for (const [id, selector] of [
|
||||
["general", "[class*='radios'] label"],
|
||||
["notifications", "[role='listbox'] [role='option'] > [class*='notificationGroupLabel']"],
|
||||
["notifications", "table tbody td:first-child"],
|
||||
["keymap", "[class*='presetLabel']"],
|
||||
["editor.inspections", "[class*='profileControls'] > span:first-child"],
|
||||
["vcs.issueNavigation", "[class*='pageBody'] button:not([aria-label])"],
|
||||
|
||||
@@ -39,55 +39,3 @@ test("Compare With… compares against a file picked in the browser", async ({ w
|
||||
const tabs = page.getByRole("tablist", { name: "Editor tabs" });
|
||||
await expect(tabs.getByRole("tab", { name: /other\.md/ })).toBeVisible({ timeout: 15_000 });
|
||||
});
|
||||
|
||||
for (const fragment of [false, true]) {
|
||||
test(`clipboard comparison labels the ${fragment ? "selection" : "file"} and its origin`, async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.evaluate(async (fragment) => {
|
||||
const path = "/dev/acme-api/src/estimate.ts";
|
||||
const source = "const estimate = 4;\nconst total = estimate + 1;\n";
|
||||
const backend = "/src/editor/core/backend.ts";
|
||||
(await import(/* @vite-ignore */ backend)).docBackend().files.set(path, source);
|
||||
const service = "/src/workbench/contributions.ts";
|
||||
await (await import(/* @vite-ignore */ service)).editorService().openFile(path);
|
||||
const editor = "/src/editor/api.ts";
|
||||
const { view } = (await import(/* @vite-ignore */ editor)).activeEditor()!;
|
||||
view.dispatch({ selection: { anchor: 0, head: fragment ? source.indexOf("\n") : 0 } });
|
||||
view.focus();
|
||||
Object.defineProperty(navigator, "clipboard", {
|
||||
value: { readText: async () => "const estimate = 3;\n" },
|
||||
configurable: true,
|
||||
});
|
||||
localStorage.setItem("openidea.vcs.diffOptions", JSON.stringify({ mode: "split", collapse: false }));
|
||||
const actions = "/src/platform/actions.ts";
|
||||
await (await import(/* @vite-ignore */ actions)).executeAction("diff.compareWithClipboard");
|
||||
}, fragment);
|
||||
|
||||
const toolbar = page.getByRole("toolbar", { name: "Diff", exact: true });
|
||||
const viewer = toolbar.locator("..");
|
||||
const file = fragment ? "Selection from estimate.ts" : "estimate.ts";
|
||||
const caption = viewer.getByTitle(`${file} src`, { exact: true });
|
||||
const clipboard = viewer.getByTitle("From Clipboard", { exact: true });
|
||||
await expect(clipboard).toBeVisible();
|
||||
await expect(caption.getByText("src", { exact: true })).toBeVisible();
|
||||
await expect(caption.getByText(file, { exact: true })).toHaveCSS("font-size", "13px");
|
||||
await expect(caption.getByText("src", { exact: true })).toHaveCSS("font-size", "12px");
|
||||
const sides = viewer.locator(".cm-content");
|
||||
await expect(sides.first()).toContainText("const estimate = 3;");
|
||||
await expect(sides.last()).toContainText("const estimate = 4;");
|
||||
const remainingLine = sides.last().getByText("const total =", { exact: false });
|
||||
if (fragment) await expect(remainingLine).toBeHidden();
|
||||
else await expect(remainingLine).toBeVisible();
|
||||
const tabs = page.getByRole("tablist", { name: "Editor tabs" });
|
||||
const title = `Clipboard ↔ estimate.ts${fragment ? " (selection)" : ""}`;
|
||||
await expect(tabs.getByRole("tab", { name: title, exact: true })).toBeVisible();
|
||||
|
||||
await toolbar.getByRole("button", { name: "Swap Sides", exact: true }).click();
|
||||
await expect(caption).toBeVisible();
|
||||
expect((await caption.boundingBox())!.x).toBeLessThan((await clipboard.boundingBox())!.x);
|
||||
await toolbar.getByRole("button", { name: "Settings", exact: true }).click();
|
||||
await page.getByRole("menuitemcheckbox", { name: "Unified Viewer", exact: true }).click();
|
||||
await expect(viewer.getByTitle(`${file} src → From Clipboard`, { exact: true })).toBeVisible();
|
||||
});
|
||||
}
|
||||
@@ -1,71 +0,0 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import { expect, test } from "./fixtures";
|
||||
|
||||
async function openConsoleSettings(page: Page) {
|
||||
await page.keyboard.press("Meta+,");
|
||||
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
|
||||
const search = dialog.getByRole("textbox", { name: "Search settings" });
|
||||
await search.fill("Fold console lines that contain");
|
||||
await dialog.getByRole("treeitem", { name: "Console", exact: true }).click();
|
||||
await search.clear();
|
||||
return dialog;
|
||||
}
|
||||
|
||||
test("Console settings put folding between the basic controls and log colors", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 1120, height: 740 });
|
||||
const dialog = await openConsoleSettings(page);
|
||||
const wrap = dialog.getByRole("checkbox", { name: "Use soft wraps in console", exact: true });
|
||||
const override = dialog.getByRole("checkbox", { name: /^Override console cycle buffer size/ });
|
||||
const size = dialog.getByRole("textbox", { name: "Override console cycle buffer size", exact: true });
|
||||
const encoding = dialog.getByRole("button", { name: "Default encoding", exact: true });
|
||||
const list = dialog.getByRole("listbox", { name: "Fold console lines that contain", exact: true });
|
||||
const colors = dialog.getByRole("checkbox", { name: "Colour log lines by level", exact: true });
|
||||
await expect(list).toBeVisible();
|
||||
expect((await list.boundingBox())!.width).toBeGreaterThan(480);
|
||||
const controls = [wrap, override, encoding, list, colors];
|
||||
const positions = await Promise.all(controls.map(async (control) => (await control.boundingBox())!.y));
|
||||
positions.forEach((y, index) => {
|
||||
if (index > 0) expect(y).toBeGreaterThan(positions[index - 1]!);
|
||||
});
|
||||
|
||||
for (const width of [580, 520]) {
|
||||
await page.setViewportSize({ width, height: 740 });
|
||||
for (const control of [...controls, size]) await expect(control).toBeInViewport({ ratio: 1 });
|
||||
expect(await list.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
|
||||
}
|
||||
});
|
||||
|
||||
test("Console settings keep the stored buffer size and fold rules across Apply and reopen", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
const dialog = await openConsoleSettings(page);
|
||||
const override = dialog.getByRole("checkbox", { name: /^Override console cycle buffer size/ });
|
||||
const size = dialog.getByRole("textbox", { name: "Override console cycle buffer size", exact: true });
|
||||
const list = dialog.getByRole("listbox", { name: "Fold console lines that contain", exact: true });
|
||||
await override.check();
|
||||
await expect(size).toBeEnabled();
|
||||
await size.fill("2048");
|
||||
await override.uncheck();
|
||||
await expect(size).toBeDisabled();
|
||||
await expect(size).toHaveValue("2048");
|
||||
|
||||
await dialog.getByRole("button", { name: "Add", exact: true }).click();
|
||||
const pattern = list.getByRole("textbox", { name: "Pattern", exact: true });
|
||||
await pattern.fill("at example.retry");
|
||||
await pattern.press("Enter");
|
||||
await expect(list.getByRole("option", { name: "at example.retry", exact: true })).toBeVisible();
|
||||
const apply = dialog.getByRole("button", { name: "Apply", exact: true });
|
||||
await apply.click();
|
||||
await expect(apply).toBeDisabled();
|
||||
await dialog.getByRole("button", { name: "Cancel", exact: true }).click();
|
||||
await expect(dialog).toBeHidden();
|
||||
|
||||
await openConsoleSettings(page);
|
||||
await expect(override).not.toBeChecked();
|
||||
await expect(size).toBeDisabled();
|
||||
await expect(size).toHaveValue("2048");
|
||||
await expect(list.getByRole("option", { name: "at example.retry", exact: true })).toBeVisible();
|
||||
await override.check();
|
||||
await expect(size).toBeEnabled();
|
||||
await expect(size).toHaveValue("2048");
|
||||
});
|
||||
@@ -1,61 +0,0 @@
|
||||
import { expect, test } from "./fixtures";
|
||||
|
||||
test("Date Formats keeps its preview beside the formatting controls and updates it while editing", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.clock.setFixedTime(new Date(2026, 0, 16, 14, 35));
|
||||
await page.keyboard.press("Meta+,");
|
||||
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
|
||||
const search = dialog.getByRole("textbox", { name: "Search settings" });
|
||||
const openPage = async () => {
|
||||
await search.fill("Date Formats");
|
||||
await dialog.getByRole("treeitem", { name: "Date Formats", exact: true }).click();
|
||||
await search.clear();
|
||||
};
|
||||
await openPage();
|
||||
|
||||
const override = dialog.getByRole("checkbox", { name: "Override system date and time format" });
|
||||
const pattern = dialog.getByRole("textbox", { name: /^Date format/ });
|
||||
const hour = dialog.getByRole("checkbox", { name: "Use 24-hour time format" });
|
||||
const pretty = dialog.getByRole("checkbox", { name: "Use pretty formatting" });
|
||||
const hint = dialog.getByText("Placeholders: yyyy, yy, MMMM, MMM, MM, M, dd, d", { exact: true });
|
||||
const initialPreview = dialog.getByText(/Today .* · /);
|
||||
|
||||
for (const width of [1120, 580, 520]) {
|
||||
await page.setViewportSize({ width, height: 680 });
|
||||
await expect(async () => {
|
||||
const [hourBox, previewBox, prettyBox, patternBox, hintBox] = await Promise.all(
|
||||
[hour, initialPreview, pretty, pattern, hint].map((control) => control.boundingBox()),
|
||||
);
|
||||
expect(previewBox!.y).toBeGreaterThan(hourBox!.y + hourBox!.height);
|
||||
expect(prettyBox!.y).toBeGreaterThan(previewBox!.y + previewBox!.height);
|
||||
if (width === 1120) {
|
||||
expect(hintBox!.x).toBeGreaterThan(patternBox!.x + patternBox!.width);
|
||||
expect(hintBox!.y + hintBox!.height).toBeLessThanOrEqual(patternBox!.y + patternBox!.height + 1);
|
||||
} else {
|
||||
expect(hintBox!.y).toBeGreaterThanOrEqual(patternBox!.y + patternBox!.height);
|
||||
}
|
||||
}).toPass({ timeout: 3000 });
|
||||
}
|
||||
|
||||
const preview = dialog.getByRole("status", { name: /^Preview/ });
|
||||
await expect(pattern).toBeDisabled();
|
||||
await expect(hour).toBeDisabled();
|
||||
await expect(pretty).toBeEnabled();
|
||||
await override.check();
|
||||
await pattern.fill("yyyy-MM-dd");
|
||||
await expect(preview).toHaveText("Today 12:35 · 2026-01-13 14:35");
|
||||
await hour.uncheck();
|
||||
await expect(preview).toHaveText("Today 12:35 PM · 2026-01-13 2:35 PM");
|
||||
await pretty.uncheck();
|
||||
await expect(preview).toHaveText("2026-01-16 12:35 PM · 2026-01-13 2:35 PM");
|
||||
|
||||
await dialog.getByRole("button", { name: "OK", exact: true }).click();
|
||||
await page.keyboard.press("Meta+,");
|
||||
await openPage();
|
||||
await expect(override).toBeChecked();
|
||||
await expect(pattern).toHaveValue("yyyy-MM-dd");
|
||||
await expect(hour).not.toBeChecked();
|
||||
await expect(pretty).not.toBeChecked();
|
||||
await expect(preview).toHaveText("2026-01-16 12:35 PM · 2026-01-13 2:35 PM");
|
||||
});
|
||||
@@ -1,56 +0,0 @@
|
||||
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
|
||||
|
||||
test("Debugger Data Views keeps the hover delay with its setting at each window width", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 1120, height: 740 });
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(() => {
|
||||
window.__ipc.handlers.settings_get_global = () => ({});
|
||||
});
|
||||
await page.keyboard.press("Meta+,");
|
||||
const settings = page.getByRole("dialog", { name: "Settings", exact: true });
|
||||
const search = settings.getByRole("textbox", { name: "Search settings" });
|
||||
await search.fill("value tooltip delay");
|
||||
await settings.getByRole("treeitem", { name: "Data Views", exact: true }).click();
|
||||
await search.clear();
|
||||
|
||||
const hover = settings.getByRole("checkbox", { name: "Show value tooltip on mouse hover", exact: true });
|
||||
const delay = settings.getByRole("textbox", { name: "Value tooltip delay (ms)", exact: true });
|
||||
const selection = settings.getByRole("checkbox", { name: "Show value tooltip on code selection", exact: true });
|
||||
const sort = settings.getByRole("checkbox", { name: "Sort values alphabetically", exact: true });
|
||||
const editor = settings.getByRole("region", { name: "Editor", exact: true });
|
||||
|
||||
for (const width of [1120, 580, 520]) {
|
||||
await page.setViewportSize({ width, height: 740 });
|
||||
await expect(delay).toBeInViewport({ ratio: 1 });
|
||||
const [toggleBox, delayBox, selectionBox] = await Promise.all(
|
||||
[hover, delay, selection].map((control) => control.boundingBox()),
|
||||
);
|
||||
if (!toggleBox || !delayBox || !selectionBox) throw new Error("Missing Data Views control bounds");
|
||||
expect(delayBox.y + delayBox.height).toBeLessThan(selectionBox.y);
|
||||
if (width === 1120) {
|
||||
expect(delayBox.x).toBeGreaterThan(toggleBox.x + toggleBox.width);
|
||||
expect(Math.abs(delayBox.y + delayBox.height / 2 - toggleBox.y - toggleBox.height / 2)).toBeLessThan(3);
|
||||
} else {
|
||||
expect(delayBox.y).toBeGreaterThan(toggleBox.y + toggleBox.height);
|
||||
}
|
||||
}
|
||||
await expect(editor.getByRole("checkbox", { name: "Show values inline", exact: true })).toBeVisible();
|
||||
await expect(editor.getByRole("checkbox", { name: "Sort values alphabetically", exact: true })).toHaveCount(0);
|
||||
await expect(sort).toBeVisible();
|
||||
|
||||
await expect(hover).toBeChecked();
|
||||
await expect(delay).toHaveValue("700");
|
||||
await delay.fill("900");
|
||||
await selection.uncheck();
|
||||
await hover.uncheck();
|
||||
await expect(delay).toBeDisabled();
|
||||
await expect(delay).toHaveValue("900");
|
||||
await selection.check();
|
||||
await expect(hover).not.toBeChecked();
|
||||
await hover.check();
|
||||
await expect(delay).toBeEnabled();
|
||||
await expect(delay).toHaveValue("900");
|
||||
await settings.getByRole("button", { name: "Cancel", exact: true }).click();
|
||||
await expect(settings).toBeHidden();
|
||||
expect(await ipcCalls(page, "settings_set")).toEqual([]);
|
||||
});
|
||||
@@ -1,104 +0,0 @@
|
||||
import type { Locator } from "@playwright/test";
|
||||
import { expect, stubDesktop, test } from "./fixtures";
|
||||
|
||||
async function expectAligned(grid: Locator, names: string[]) {
|
||||
await expect(grid.getByRole("columnheader")).toHaveText(names);
|
||||
await expect
|
||||
.poll(() =>
|
||||
grid.evaluate((element) => {
|
||||
const head = [...element.querySelectorAll('[role="columnheader"]')].filter(
|
||||
(cell) => cell.getClientRects().length,
|
||||
);
|
||||
const row = element.querySelector('[aria-rowindex="2"]');
|
||||
const cells = [...(row?.querySelectorAll('[role="gridcell"]') ?? [])].filter(
|
||||
(cell) => cell.getClientRects().length,
|
||||
);
|
||||
return (
|
||||
cells.length === head.length &&
|
||||
head.every((cell, index) => {
|
||||
const header = cell.getBoundingClientRect();
|
||||
const value = cells[index]!.getBoundingClientRect();
|
||||
return Math.abs(header.x - value.x) < 1 && Math.abs(header.width - value.width) < 1;
|
||||
})
|
||||
);
|
||||
}),
|
||||
)
|
||||
.toBe(true);
|
||||
}
|
||||
|
||||
test("directory comparison mirrors both sides and keeps the headers aligned while the list scrolls", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 1220, height: 780 });
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async () => {
|
||||
const entry = {
|
||||
leftKind: "file",
|
||||
rightKind: "file",
|
||||
status: "different",
|
||||
leftSize: 120,
|
||||
rightSize: 144,
|
||||
leftModified: Date.UTC(2026, 9, 8, 12),
|
||||
rightModified: Date.UTC(2026, 9, 9, 12),
|
||||
};
|
||||
const handlers = window.__ipc.handlers;
|
||||
handlers.fs_entry_kind = ({ path }) => (String(path).endsWith(".txt") ? "file" : "dir");
|
||||
handlers.cancel_request = () => null;
|
||||
handlers.fs_read_text = () => "";
|
||||
handlers.fs_compare_directories = () => [
|
||||
{ ...entry, path: "00-configuration.txt" },
|
||||
...Array.from({ length: 65 }, (_, index) => ({ ...entry, path: `log-${index}.txt` })),
|
||||
{ ...entry, path: "only-left.txt", rightKind: null, rightSize: null, status: "leftOnly" },
|
||||
{ ...entry, path: "shared.txt", status: "equal" },
|
||||
];
|
||||
const actions = "/src/platform/actions.ts";
|
||||
const { executeAction } = await import(/* @vite-ignore */ actions);
|
||||
await executeAction("toolwindow.hideAll");
|
||||
await executeAction("diff.compareDirectories", ["/dev/acme-api/source", "/dev/acme-api/target"]);
|
||||
});
|
||||
|
||||
const grid = page.getByRole("grid", { name: "Compared files" });
|
||||
const filter = page.getByRole("textbox", { name: "Filter by name" });
|
||||
const source = page.getByText("Left: source", { exact: true });
|
||||
const target = page.getByText("Right: target", { exact: true });
|
||||
await expect(source).toBeVisible();
|
||||
await expect(target).toBeVisible();
|
||||
const [pathBox, filterBox] = await Promise.all([source.boundingBox(), filter.boundingBox()]);
|
||||
if (!pathBox || !filterBox) throw new Error("Missing comparison toolbar bounds");
|
||||
expect(pathBox.y).toBeGreaterThanOrEqual(filterBox.y + filterBox.height);
|
||||
await expectAligned(grid, ["Name", "Size", "Date", "", "Date", "Size", "Name"]);
|
||||
const first = grid.getByRole("row").filter({ has: page.getByRole("gridcell", { name: "00-configuration.txt" }) });
|
||||
const values = await first.getByRole("gridcell").allTextContents();
|
||||
expect(values.at(0)).toBe("00-configuration.txt");
|
||||
expect(values.at(1)).toBe("120 B");
|
||||
expect(values.at(-2)).toBe("144 B");
|
||||
expect(values.at(-1)).toBe("00-configuration.txt");
|
||||
const rows = grid.locator('[role="rowgroup"][tabindex="0"]');
|
||||
expect(await rows.evaluate((el) => el.scrollHeight)).toBeGreaterThan(await rows.evaluate((el) => el.clientHeight));
|
||||
|
||||
await page.setViewportSize({ width: 630, height: 740 });
|
||||
await expectAligned(grid, ["Name", "Size", "", "Size", "Name"]);
|
||||
await expect(first.getByRole("gridcell").first()).toHaveAttribute("title", /00-configuration.txt.*120 B/);
|
||||
const setContainerType = (value: string) =>
|
||||
filter.evaluate((el, type) => {
|
||||
const container = el.parentElement?.parentElement;
|
||||
if (!container) throw new Error("Missing directory comparison container");
|
||||
container.style.containerType = type;
|
||||
}, value);
|
||||
await setContainerType("normal");
|
||||
await expectAligned(grid, ["Name", "Size", "Date", "", "Date", "Size", "Name"]);
|
||||
await expect(first.getByRole("gridcell").first()).toBeInViewport({ ratio: 1 });
|
||||
await setContainerType("");
|
||||
await page.setViewportSize({ width: 360, height: 740 });
|
||||
await expectAligned(grid, ["Name", "", "Name"]);
|
||||
|
||||
await page.setViewportSize({ width: 630, height: 740 });
|
||||
await filter.fill("shared");
|
||||
await expect(page.getByText("No matching differences", { exact: true })).toBeVisible();
|
||||
await page.getByRole("button", { name: "Show identical files" }).click();
|
||||
const shared = grid.getByRole("gridcell", { name: "shared.txt", exact: true });
|
||||
await expect(shared).toHaveCount(2);
|
||||
await shared.first().click();
|
||||
await expect(page.getByRole("button", { name: "Copy to Right", exact: true })).toBeEnabled();
|
||||
await expect(page.getByRole("toolbar", { name: "Diff", exact: true })).toBeVisible();
|
||||
});
|
||||
@@ -121,82 +121,3 @@ test("Git Log keeps filters and actions inside the commit pane at the minimum wi
|
||||
await toolbar.getByRole("button", { name: "More Filters" }).click();
|
||||
await expect(page.getByRole("menuitem", { name: "Paths" })).toBeVisible();
|
||||
});
|
||||
|
||||
test("the Paths filter replaces the repository filter and can be cleared from overflow", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.evaluate(async () => {
|
||||
const storeModule = "/src/features/vcs/store.ts";
|
||||
const { useVcs } = await import(/* @vite-ignore */ storeModule);
|
||||
const root = "/dev/acme-api";
|
||||
const other = "/dev/tools";
|
||||
const branch = (name: string) => ({
|
||||
name,
|
||||
current: true,
|
||||
remote: false,
|
||||
upstream: null,
|
||||
ahead: 0,
|
||||
behind: 0,
|
||||
lastCommitMs: 0,
|
||||
commit: "",
|
||||
});
|
||||
const handlers = window.__ipc.handlers;
|
||||
handlers.vcs_branches = ({ repo }) => [branch(repo === other ? "tools-main" : "api-main")];
|
||||
useVcs.setState({ roots: [root, other], branches: [branch("api-main")] });
|
||||
handlers.fs_read_dir = ({ path }) =>
|
||||
path === root ? [{ name: "api.ts", path: root + "/api.ts", kind: "file", size: 0, mtimeMs: 0 }] : [];
|
||||
const log = handlers.vcs_log!;
|
||||
handlers.vcs_log = (args) => {
|
||||
const { paths } = args.query as { paths?: string[] };
|
||||
return log({ ...args, query: { ...(args.query as object), skip: paths?.includes(root + "/api.ts") ? 1 : 0 } });
|
||||
};
|
||||
});
|
||||
await page.setViewportSize({ width: 600, height: 550 });
|
||||
const toolbar = page.getByRole("toolbar", { name: "Log filters" });
|
||||
const overflow = toolbar.getByRole("button", { name: "More Filters" });
|
||||
await overflow.click();
|
||||
await page.getByRole("menuitem", { name: "Paths", exact: true }).click();
|
||||
const acme = page.getByRole("menuitemcheckbox", { name: "acme-api" });
|
||||
await expect(acme).toHaveAttribute("aria-checked", "true");
|
||||
await acme.click();
|
||||
await overflow.click();
|
||||
await page.getByRole("menuitem", { name: "Paths: tools", exact: true }).click();
|
||||
await expect(acme).toHaveAttribute("aria-checked", "false");
|
||||
await page.getByRole("menuitem", { name: "Select in Tree…" }).click();
|
||||
const picker = page.getByRole("dialog", { name: "Filter by Paths" });
|
||||
const pathTree = picker.getByRole("tree", { name: "Files and folders" });
|
||||
const repo = pathTree.getByRole("checkbox", { name: "acme-api" });
|
||||
await expect(repo).toBeVisible();
|
||||
const tree = await pathTree.boundingBox();
|
||||
const row = await repo.locator("xpath=ancestor::label").boundingBox();
|
||||
expect(tree!.x + tree!.width).toBeGreaterThanOrEqual(row!.x + row!.width);
|
||||
await repo.check();
|
||||
await picker.getByRole("button", { name: "OK" }).click();
|
||||
await page.setViewportSize({ width: 1100, height: 720 });
|
||||
const branches = page.getByRole("tree", { name: "Branches", exact: true });
|
||||
await expect(branches.getByText("api-main", { exact: true })).toBeVisible();
|
||||
await expect(branches.getByText("tools-main", { exact: true })).toHaveCount(0);
|
||||
await page.setViewportSize({ width: 600, height: 550 });
|
||||
|
||||
await overflow.click();
|
||||
await page.getByRole("menuitem", { name: /^Paths:/ }).click();
|
||||
await page.getByRole("menuitem", { name: "Select in Tree…" }).click();
|
||||
await repo.uncheck();
|
||||
await repo.locator("xpath=ancestor::*[@data-row]").locator("[data-tree-toggle]").click();
|
||||
await picker.getByRole("checkbox", { name: "api.ts" }).check();
|
||||
await picker.getByRole("button", { name: "OK" }).click();
|
||||
const firstCommit = page.getByRole("listbox", { name: "Commits" }).getByRole("option").first();
|
||||
await expect(firstCommit.getByText("Commit 1", { exact: true })).toBeVisible();
|
||||
await overflow.click();
|
||||
await page.getByRole("menuitem", { name: /^Paths:/ }).click();
|
||||
await page.getByRole("menuitem", { name: "All" }).click();
|
||||
await expect(firstCommit.getByText("Commit 0", { exact: true })).toBeVisible();
|
||||
|
||||
await overflow.click();
|
||||
await page.getByRole("menuitem", { name: "Paths", exact: true }).click();
|
||||
await expect(page.getByRole("menuitemcheckbox", { name: "api.ts" })).toBeVisible();
|
||||
await page.getByRole("menuitem", { name: "Select…", exact: true }).click();
|
||||
await picker.getByRole("textbox", { name: "Paths" }).fill("acme-api/api.ts");
|
||||
await picker.getByRole("button", { name: "OK" }).click();
|
||||
await expect(firstCommit.getByText("Commit 1", { exact: true })).toBeVisible();
|
||||
});
|
||||
@@ -1,65 +0,0 @@
|
||||
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
|
||||
|
||||
test("Git settings keep the executable and Test button together at narrow widths", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 560, height: 740 });
|
||||
await stubDesktop(page);
|
||||
const gitPath = "C:/Program Files/Git/cmd/git.exe";
|
||||
const longPath = `C:/${"long-directory-name".repeat(20)}/git.exe`;
|
||||
await page.evaluate(
|
||||
({ gitPath, longPath }) => {
|
||||
window.__ipc.handlers.vcs_detected_git = () => gitPath;
|
||||
window.__ipc.handlers.vcs_git_version = ({ path }) => ({ path: path || longPath, version: "git version 2.49.0" });
|
||||
window.__ipc.handlers.git_credentials = () => [];
|
||||
},
|
||||
{ gitPath, longPath },
|
||||
);
|
||||
await page.keyboard.press("Meta+,");
|
||||
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
|
||||
const search = dialog.getByRole("textbox", { name: "Search settings" });
|
||||
await search.fill("Path to Git executable");
|
||||
await dialog.getByRole("treeitem", { name: "Git", exact: true }).click();
|
||||
await search.clear();
|
||||
|
||||
const path = dialog.getByRole("textbox", { name: /^Path to Git executable:?$/ });
|
||||
const testButton = dialog.getByRole("button", { name: "Test", exact: true });
|
||||
const branches = dialog.getByRole("textbox", { name: /^Protected branches:?$/ });
|
||||
await expect(path).toHaveAttribute("placeholder", `Auto-detected: ${gitPath}`);
|
||||
for (const width of [560, 580, 1120]) {
|
||||
await page.setViewportSize({ width, height: 740 });
|
||||
await path.scrollIntoViewIfNeeded();
|
||||
const [field, button, patterns] = await Promise.all([
|
||||
path.boundingBox(),
|
||||
testButton.boundingBox(),
|
||||
branches.boundingBox(),
|
||||
]);
|
||||
if (!field || !button || !patterns) throw new Error("Missing Git settings control bounds");
|
||||
expect(field.y).toBeCloseTo(button.y, 0);
|
||||
if (width <= 580) {
|
||||
const label = await dialog.getByText("Path to Git executable", { exact: true }).boundingBox();
|
||||
if (!label) throw new Error("Missing Git executable label bounds");
|
||||
expect(label.y + label.height).toBeLessThan(field.y);
|
||||
expect(field.width).toBeGreaterThan(150);
|
||||
}
|
||||
expect(field.x + field.width).toBeLessThan(button.x);
|
||||
expect(button.x + button.width).toBeCloseTo(patterns.x + patterns.width, 0);
|
||||
}
|
||||
|
||||
await page.setViewportSize({ width: 560, height: 740 });
|
||||
await testButton.click();
|
||||
const result = dialog.getByRole("status").filter({ hasText: "Git version is 2.49.0" });
|
||||
await expect(result).toContainText(longPath);
|
||||
await expect(result).toBeInViewport({ ratio: 1 });
|
||||
await path.fill(gitPath);
|
||||
await expect(result).toHaveCount(0);
|
||||
await testButton.click();
|
||||
await expect(result).toContainText(gitPath);
|
||||
expect(await ipcCalls(page, "vcs_git_version")).toEqual([{ path: "" }, { path: gitPath }]);
|
||||
expect(await ipcCalls(page, "settings_set")).toEqual([]);
|
||||
|
||||
const update = dialog.getByRole("radiogroup", { name: "Update method" });
|
||||
const merge = update.getByRole("radio", { name: "Merge" });
|
||||
const rebase = update.getByRole("radio", { name: "Rebase" });
|
||||
await expect(merge).toBeChecked();
|
||||
await merge.press("ArrowRight");
|
||||
await expect(rebase).toBeChecked();
|
||||
});
|
||||
@@ -1,88 +0,0 @@
|
||||
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
|
||||
|
||||
test("Gradle keeps the local installation with Distribution and saves edits in project scope", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 1120, height: 760 });
|
||||
await stubDesktop(page);
|
||||
const gradleHome = "C:/Tools/Gradle 8.14";
|
||||
await page.evaluate((path) => {
|
||||
window.__ipc.handlers.settings_get_global = () => ({});
|
||||
window.__ipc.handlers.settings_get = () => ({});
|
||||
window.__ipc.handlers.settings_set = () => ({});
|
||||
window.__ipc.handlers.sdk_detect = () => [];
|
||||
window.__ipc.handlers["plugin:dialog|open"] = () => path;
|
||||
}, gradleHome);
|
||||
|
||||
await page.keyboard.press("Meta+,");
|
||||
const settings = page.getByRole("dialog", { name: "Settings", exact: true });
|
||||
const search = settings.getByRole("textbox", { name: "Search settings" });
|
||||
await search.fill("Gradle JVM");
|
||||
await settings.getByRole("treeitem", { name: "Gradle", exact: true }).click();
|
||||
await search.clear();
|
||||
|
||||
const userHome = settings.getByRole("textbox", { name: /^Gradle user home:?$/ });
|
||||
const runUsing = settings.getByRole("button", { name: "Build and run using", exact: true });
|
||||
const distribution = settings.getByRole("button", { name: "Distribution", exact: true });
|
||||
const jvm = settings.getByRole("button", { name: "Gradle JVM", exact: true });
|
||||
const installation = settings.getByRole("textbox", { name: "Gradle home", exact: true });
|
||||
const [user, run, distro, sdk] = await Promise.all(
|
||||
[userHome, runUsing, distribution, jvm].map((el) => el.boundingBox()),
|
||||
);
|
||||
if (!user || !run || !distro || !sdk) throw new Error("Missing Gradle settings fields");
|
||||
expect(user.y).toBeLessThan(run.y);
|
||||
expect(run.y).toBeLessThan(distro.y);
|
||||
expect(distro.y).toBeLessThan(sdk.y);
|
||||
await expect(
|
||||
settings
|
||||
.getByRole("region", { name: "Build and Run", exact: true })
|
||||
.getByRole("button", { name: "Build and run using" }),
|
||||
).toBeVisible();
|
||||
const runtime = settings.getByRole("region", { name: "Gradle runtime", exact: true });
|
||||
await expect(runtime.getByRole("button", { name: "Distribution", exact: true })).toBeVisible();
|
||||
await expect(runtime.getByRole("button", { name: "Gradle JVM", exact: true })).toBeVisible();
|
||||
|
||||
await expect(distribution).toHaveText("Gradle wrapper");
|
||||
await expect(installation).toHaveCount(0);
|
||||
await distribution.click();
|
||||
await page.getByRole("option", { name: "Local installation", exact: true }).click();
|
||||
const browse = installation.locator("..").getByRole("button", { name: /^Browse/ });
|
||||
|
||||
for (const width of [1120, 580, 520]) {
|
||||
await page.setViewportSize({ width, height: 760 });
|
||||
await expect(browse).toBeInViewport({ ratio: 1 });
|
||||
const [choice, path, button, java] = await Promise.all(
|
||||
[distribution, installation, browse, jvm].map((el) => el.boundingBox()),
|
||||
);
|
||||
if (!choice || !path || !button || !java) throw new Error("Missing local installation controls");
|
||||
expect(path.width).toBeGreaterThan(120);
|
||||
expect(path.y + path.height / 2).toBeCloseTo(button.y + button.height / 2, 0);
|
||||
expect(path.y + path.height).toBeLessThan(java.y);
|
||||
if (width === 1120) {
|
||||
expect(path.x).toBeGreaterThan(choice.x + choice.width);
|
||||
expect(path.y).toBeCloseTo(choice.y, 0);
|
||||
} else {
|
||||
expect(path.x).toBeCloseTo(choice.x, 0);
|
||||
expect(path.y).toBeGreaterThan(choice.y + choice.height);
|
||||
}
|
||||
}
|
||||
|
||||
await browse.click();
|
||||
await expect(installation).toHaveValue(gradleHome);
|
||||
await userHome.fill("C:/Build Cache/Gradle");
|
||||
await distribution.click();
|
||||
await page.getByRole("option", { name: "Gradle wrapper", exact: true }).click();
|
||||
await expect(installation).toHaveCount(0);
|
||||
await distribution.click();
|
||||
await page.getByRole("option", { name: "Local installation", exact: true }).click();
|
||||
await expect(installation).toHaveValue(gradleHome);
|
||||
expect(await ipcCalls(page, "settings_set")).toEqual([]);
|
||||
await settings.getByRole("button", { name: "Apply", exact: true }).click();
|
||||
await expect
|
||||
.poll(async () => (await ipcCalls(page, "settings_set")).sort((a, b) => String(a.key).localeCompare(String(b.key))))
|
||||
.toEqual([
|
||||
{ scope: "project", key: "languages.java.gradle.distribution", value: JSON.stringify("local") },
|
||||
{ scope: "project", key: "languages.java.gradle.home", value: JSON.stringify(gradleHome) },
|
||||
{ scope: "project", key: "languages.java.gradle.userHome", value: JSON.stringify("C:/Build Cache/Gradle") },
|
||||
]);
|
||||
});
|
||||
@@ -1,95 +0,0 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
|
||||
|
||||
async function openProxySettings(page: Page) {
|
||||
await page.keyboard.press("Meta+,");
|
||||
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
|
||||
const search = dialog.getByRole("textbox", { name: "Search settings" });
|
||||
await search.fill("HTTP Proxy");
|
||||
await dialog.getByRole("treeitem", { name: "HTTP Proxy", exact: true }).click();
|
||||
await search.clear();
|
||||
return dialog;
|
||||
}
|
||||
|
||||
test("HTTP Proxy keeps server and authentication fields aligned in narrow settings", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 1120, height: 740 });
|
||||
const dialog = await openProxySettings(page);
|
||||
const auto = dialog.getByRole("radio", { name: "Auto-detect proxy settings", exact: true });
|
||||
const manual = dialog.getByRole("radio", { name: "Manual proxy configuration", exact: true });
|
||||
const host = dialog.getByRole("textbox", { name: "Host name:", exact: true });
|
||||
const port = dialog.getByRole("textbox", { name: /^Port number:?$/ });
|
||||
const exceptions = dialog.getByRole("textbox", { name: "No proxy for:", exact: true });
|
||||
const auth = dialog.getByRole("checkbox", { name: "Proxy authentication", exact: true });
|
||||
const login = dialog.getByRole("textbox", { name: "Login:", exact: true });
|
||||
const password = dialog.getByLabel("Password", { exact: true });
|
||||
await expect(auto).toBeChecked();
|
||||
for (const control of [host, port, exceptions, auth, login, password]) await expect(control).toBeDisabled();
|
||||
|
||||
await auto.press("ArrowDown");
|
||||
await expect(manual).toBeChecked();
|
||||
await host.fill("127.0.0.1");
|
||||
await expect(login).toBeDisabled();
|
||||
await auth.check();
|
||||
await login.fill("layout-user");
|
||||
await password.fill("layout-password");
|
||||
|
||||
for (const width of [1120, 580, 520]) {
|
||||
await page.setViewportSize({ width, height: 740 });
|
||||
for (const control of [host, port, exceptions, login, password]) {
|
||||
await expect(control).toBeInViewport({ ratio: 1 });
|
||||
}
|
||||
const [hostBox, portBox, exceptionsBox, loginBox, passwordBox] = await Promise.all(
|
||||
[host, port, exceptions, login, password].map((control) => control.boundingBox()),
|
||||
);
|
||||
if (!hostBox || !portBox || !exceptionsBox || !loginBox || !passwordBox) {
|
||||
throw new Error("Missing HTTP Proxy field bounds");
|
||||
}
|
||||
expect(hostBox.y).toBeLessThan(portBox.y);
|
||||
expect(portBox.y).toBeLessThan(exceptionsBox.y);
|
||||
expect(hostBox.x).toBeCloseTo(portBox.x, 0);
|
||||
expect(hostBox.x).toBeCloseTo(exceptionsBox.x, 0);
|
||||
expect(hostBox.width).toBeCloseTo(exceptionsBox.width, 0);
|
||||
expect(loginBox.x).toBeCloseTo(passwordBox.x, 0);
|
||||
expect(loginBox.width).toBeCloseTo(passwordBox.width, 0);
|
||||
}
|
||||
|
||||
await auto.check();
|
||||
await expect(password).toBeDisabled();
|
||||
await manual.check();
|
||||
await expect(host).toHaveValue("127.0.0.1");
|
||||
await expect(login).toHaveValue("layout-user");
|
||||
await expect(password).toHaveValue("layout-password");
|
||||
});
|
||||
|
||||
test("HTTP Proxy checks a URL with the staged manual settings in a narrow window", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 540, height: 680 });
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(() => {
|
||||
window.__ipc.handlers.proxy_check_connection = () => "200 OK";
|
||||
});
|
||||
const dialog = await openProxySettings(page);
|
||||
const check = dialog.getByRole("button", { name: "Check connection…", exact: true });
|
||||
const manual = dialog.getByRole("radio", { name: "Manual proxy configuration", exact: true });
|
||||
await manual.check();
|
||||
await expect(check).toBeDisabled();
|
||||
await dialog.getByRole("textbox", { name: "Host name:", exact: true }).fill("proxy.example.test");
|
||||
const port = dialog.getByRole("textbox", { name: /^Port number:?$/ });
|
||||
await port.fill("8079");
|
||||
await port.press("ArrowUp");
|
||||
await expect(port).toHaveValue("8080");
|
||||
await check.click();
|
||||
const target = page.getByRole("textbox", { name: "Enter any URL to check connection to:", exact: true });
|
||||
const submit = page.getByRole("button", { name: "Check", exact: true });
|
||||
await target.fill("http://example.test/health");
|
||||
await expect(target).toBeInViewport({ ratio: 1 });
|
||||
await expect(submit).toBeInViewport({ ratio: 1 });
|
||||
await submit.click();
|
||||
await expect(page.getByRole("status").filter({ hasText: "Connection successful: 200 OK" })).toBeVisible();
|
||||
expect(await ipcCalls(page, "proxy_check_connection")).toEqual([
|
||||
{
|
||||
proxy: expect.objectContaining({ mode: "manual", kind: "http", host: "proxy.example.test", port: 8080 }),
|
||||
url: "http://example.test/health",
|
||||
},
|
||||
]);
|
||||
expect(await ipcCalls(page, "settings_set")).toEqual([]);
|
||||
});
|
||||
@@ -1,87 +0,0 @@
|
||||
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
|
||||
|
||||
test("Maven groups environment and runner settings while keeping paths and thread count editable", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 1120, height: 900 });
|
||||
await stubDesktop(page);
|
||||
const settingsPath = "C:/Build Config/settings.xml";
|
||||
const jdk = "C:/SDKs/jdk-21";
|
||||
await page.evaluate(
|
||||
({ settingsPath, jdk }) => {
|
||||
window.__ipc.handlers.settings_get_global = () => ({});
|
||||
window.__ipc.handlers.settings_get = () => ({});
|
||||
window.__ipc.handlers.settings_set = () => ({});
|
||||
window.__ipc.handlers.sdk_detect = ({ kind }) =>
|
||||
kind === "jdk" ? [{ path: jdk, home: jdk, name: "JDK 21", version: "21", source: "system", extra: null }] : [];
|
||||
window.__ipc.handlers["plugin:dialog|open"] = () => settingsPath;
|
||||
},
|
||||
{ settingsPath, jdk },
|
||||
);
|
||||
|
||||
await page.keyboard.press("Meta+,");
|
||||
const settings = page.getByRole("dialog", { name: "Settings", exact: true });
|
||||
const search = settings.getByRole("textbox", { name: "Search settings" });
|
||||
await search.fill("thread count");
|
||||
await settings.getByRole("treeitem", { name: "Maven", exact: true }).click();
|
||||
await search.clear();
|
||||
|
||||
const threads = settings.getByRole("textbox", { name: "Thread count", exact: true });
|
||||
const maven = settings.getByRole("button", { name: "Maven home path", exact: true });
|
||||
const user = settings.getByRole("textbox", { name: /^User settings file:?$/ });
|
||||
const repository = settings.getByRole("textbox", { name: /^Local repository:?$/ });
|
||||
const userBrowse = user.locator("..").getByRole("button", { name: /^Browse/ });
|
||||
const repoBrowse = repository.locator("..").getByRole("button", { name: /^Browse/ });
|
||||
const java = settings.getByRole("button", { name: "JRE", exact: true });
|
||||
const download = settings.getByRole("checkbox", { name: "Automatically download sources", exact: true });
|
||||
const [count, home] = await Promise.all([threads.boundingBox(), maven.boundingBox()]);
|
||||
if (!count || !home) throw new Error("Missing Maven controls");
|
||||
expect(count.y).toBeLessThan(home.y);
|
||||
|
||||
const environment = settings.getByRole("region", { name: "Environment", exact: true });
|
||||
const importing = settings.getByRole("region", { name: "Importing", exact: true });
|
||||
const runner = settings.getByRole("region", { name: "Runner", exact: true });
|
||||
await expect(environment.getByRole("button", { name: "Maven home path", exact: true })).toBeVisible();
|
||||
await expect(importing.getByRole("checkbox", { name: "Automatically download sources", exact: true })).toBeVisible();
|
||||
await expect(runner.getByRole("button", { name: "JRE", exact: true })).toBeVisible();
|
||||
for (const width of [1120, 580, 520]) {
|
||||
await page.setViewportSize({ width, height: 900 });
|
||||
await threads.scrollIntoViewIfNeeded();
|
||||
const [threadBox, mavenBox, userBox, userButton, repoBox, repoButton, importBox, javaBox] = await Promise.all(
|
||||
[threads, maven, user, userBrowse, repository, repoBrowse, download, java].map((control) =>
|
||||
control.boundingBox(),
|
||||
),
|
||||
);
|
||||
if (!threadBox || !mavenBox || !userBox || !userButton || !repoBox || !repoButton || !importBox || !javaBox)
|
||||
throw new Error("Missing Maven layout bounds");
|
||||
expect(threadBox.width).toBeLessThan(121);
|
||||
expect(mavenBox.x).toBeCloseTo(userBox.x, 0);
|
||||
expect(userBox.x).toBeCloseTo(repoBox.x, 0);
|
||||
expect(userBox.width).toBeGreaterThan(120);
|
||||
expect(userBox.y + userBox.height / 2).toBeCloseTo(userButton.y + userButton.height / 2, 0);
|
||||
expect(userButton.x + userButton.width).toBeCloseTo(repoButton.x + repoButton.width, 0);
|
||||
expect(repoBox.y + repoBox.height).toBeLessThan(importBox.y);
|
||||
expect(importBox.y).toBeLessThan(javaBox.y);
|
||||
await expect(userBrowse).toBeInViewport({ ratio: 1 });
|
||||
}
|
||||
|
||||
await userBrowse.click();
|
||||
await expect(user).toHaveValue(settingsPath);
|
||||
await java.click();
|
||||
await page.getByRole("option", { name: /JDK 21/ }).click();
|
||||
await expect(java).toHaveText("JDK 21");
|
||||
await threads.fill("2X");
|
||||
await expect(threads).toHaveAttribute("aria-invalid", "true");
|
||||
await expect(settings.getByRole("alert")).toContainText("Not a thread count Maven accepts");
|
||||
await threads.fill("2.5C");
|
||||
await expect(settings.getByRole("alert")).toHaveCount(0);
|
||||
expect(await ipcCalls(page, "settings_set")).toEqual([]);
|
||||
await settings.getByRole("button", { name: "Apply", exact: true }).click();
|
||||
await expect
|
||||
.poll(async () => (await ipcCalls(page, "settings_set")).sort((a, b) => String(a.key).localeCompare(String(b.key))))
|
||||
.toEqual([
|
||||
{ scope: "project", key: "languages.java.maven.runnerJre", value: JSON.stringify(jdk) },
|
||||
{ scope: "project", key: "languages.java.maven.threads", value: JSON.stringify("2.5C") },
|
||||
{ scope: "project", key: "languages.java.maven.userSettings", value: JSON.stringify(settingsPath) },
|
||||
]);
|
||||
});
|
||||
@@ -1,58 +0,0 @@
|
||||
import { expect, openFromTree, test } from "./fixtures";
|
||||
|
||||
test("Quick Definition keeps the source font and toolbar while switching previews", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 1120, height: 780 });
|
||||
await openFromTree(page, "App.tsx");
|
||||
await page.evaluate(async () => {
|
||||
const path = "/src/editor/lsp/popupStore.ts";
|
||||
const { openPopup } = await import(/* @vite-ignore */ path);
|
||||
const editor = document.querySelector<HTMLElement>(".cm-editor")!;
|
||||
const content = editor.querySelector<HTMLElement>(".cm-content")!;
|
||||
content.style.fontSize = "19px";
|
||||
content.style.lineHeight = "27px";
|
||||
const { fontFamily, fontSize, fontWeight, lineHeight, tabSize } = getComputedStyle(content);
|
||||
openPopup({
|
||||
kind: "definition",
|
||||
anchor: { x: 320, y: 160 },
|
||||
targets: ["shipping", "billing"].map((group) => ({
|
||||
name: "formatTotal",
|
||||
firstLine: 2,
|
||||
location: {
|
||||
path: `/work/acme-api/src/${group}/totals.ts`,
|
||||
range: { start: { line: 2, col: 0 }, end: { line: 2, col: 11 } },
|
||||
},
|
||||
text: `export const formatTotal = "${group}";`,
|
||||
language: "typescript",
|
||||
})),
|
||||
index: 0,
|
||||
themeClasses: editor.className,
|
||||
codeStyle: { fontFamily, fontSize, fontWeight, lineHeight, tabSize },
|
||||
});
|
||||
});
|
||||
|
||||
const popup = page.getByRole("dialog", { name: "Definition", exact: true });
|
||||
const code = popup.locator("pre");
|
||||
await expect(code).toContainText("shipping");
|
||||
await expect(code).toHaveCSS("font-size", "19px");
|
||||
await expect(code).toHaveCSS("line-height", "27px");
|
||||
await expect(popup).toHaveCSS("height", "400px");
|
||||
const header = popup.locator("button").filter({ hasText: "formatTotal" });
|
||||
await expect(header).toBeVisible();
|
||||
await expect(popup.getByText(/shipping[/]totals\.ts:3/)).toBeVisible();
|
||||
|
||||
await popup.getByRole("button", { name: "Next Definition" }).click();
|
||||
await expect(code).toContainText("billing");
|
||||
await expect(popup.getByText(/billing[/]totals\.ts:3/)).toBeVisible();
|
||||
await expect(popup.getByText("2/2")).toBeVisible();
|
||||
await page.keyboard.press("ArrowRight");
|
||||
await expect(code).toContainText("shipping");
|
||||
|
||||
const handle = popup.getByRole("separator", { name: "Resize" });
|
||||
const bounds = (await handle.boundingBox())!;
|
||||
await page.mouse.move(bounds.x + bounds.width / 2, bounds.y + bounds.height / 2);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(bounds.x + 56, bounds.y + 50, { steps: 4 });
|
||||
await page.mouse.up();
|
||||
expect((await popup.boundingBox())!.height).toBeGreaterThan(430);
|
||||
await expect(popup.getByRole("button", { name: "Edit Source" })).toBeInViewport({ ratio: 1 });
|
||||
});
|
||||
@@ -1,41 +0,0 @@
|
||||
import { expect, openFromTree, test } from "./fixtures";
|
||||
|
||||
test("Quick Switch Scheme stays centered and opens its numbered choices without leaving the editor", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
const editor = await openFromTree(page, "build.gradle.kts");
|
||||
const content = editor.locator(".cm-content");
|
||||
await content.focus();
|
||||
const root = page.locator("html");
|
||||
const theme = await root.getAttribute("data-theme");
|
||||
const colorTheme = await root.getAttribute("data-color-theme");
|
||||
await page.keyboard.press("Control+Backquote");
|
||||
const menu = page.getByRole("menu", { name: /^(Switch Scheme|Context menu)$/ });
|
||||
await expect(menu).toBeVisible();
|
||||
for (const { width, height } of [
|
||||
{ width: 1120, height: 680 },
|
||||
{ width: 620, height: 540 },
|
||||
]) {
|
||||
await page.setViewportSize({ width, height });
|
||||
await expect(async () => {
|
||||
const bounds = await menu.locator("xpath=..").boundingBox();
|
||||
expect(Math.abs(bounds!.x + bounds!.width / 2 - width / 2)).toBeLessThan(1);
|
||||
expect(Math.abs(bounds!.y + bounds!.height / 2 - height / 2)).toBeLessThan(1);
|
||||
}).toPass({ timeout: 3000 });
|
||||
}
|
||||
await expect(menu.getByText("Switch Scheme", { exact: true })).toBeVisible();
|
||||
await expect(menu.getByRole("menuitem", { name: "Editor Color Scheme" })).toBeFocused();
|
||||
await expect(menu.locator("[data-menu-number]")).toHaveText(["1", "2", "3", "4"]);
|
||||
await page.keyboard.press("4");
|
||||
const light = page.getByRole("menuitemcheckbox", { name: "Solarized Light" });
|
||||
await light.hover();
|
||||
await expect(root).toHaveAttribute("data-color-theme", "solarized-light");
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(light).toBeHidden();
|
||||
await expect(menu).toBeVisible();
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(menu).toBeHidden();
|
||||
await expect(content).toBeFocused();
|
||||
await expect.poll(() => root.getAttribute("data-theme")).toBe(theme);
|
||||
await expect.poll(() => root.getAttribute("data-color-theme")).toBe(colorTheme);
|
||||
});
|
||||
@@ -1,71 +0,0 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import { expect, test } from "./fixtures";
|
||||
|
||||
async function openRefactorList(page: Page) {
|
||||
await page.evaluate(async () => {
|
||||
const path = "/src/editor/lsp/popupStore.ts";
|
||||
const { openPopup } = await import(/* @vite-ignore */ path);
|
||||
const run = (action: string) => () => {
|
||||
document.body.dataset.selectedRefactoring = action;
|
||||
};
|
||||
openPopup({
|
||||
kind: "list",
|
||||
title: "Refactor This",
|
||||
anchor: { x: 300, y: 140 },
|
||||
compact: true,
|
||||
numbered: true,
|
||||
items: [
|
||||
{ id: "rename", label: "Rename…", shortcut: "Shift+F6", run: run("rename") },
|
||||
{
|
||||
id: "extractVariable",
|
||||
label: "Introduce Variable…",
|
||||
shortcut: "Ctrl+Alt+V",
|
||||
section: { id: "extract", label: "Extract/Introduce" },
|
||||
run: run("extractVariable"),
|
||||
},
|
||||
{ id: "inline", label: "Inline…", section: { id: "inline" }, run: run("inline") },
|
||||
],
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
test("the compact Refactor This list groups actions without numbering or selecting its captions", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await openRefactorList(page);
|
||||
const popup = page.getByRole("dialog", { name: "Refactor This", exact: true });
|
||||
const group = popup.getByText("Extract/Introduce", { exact: true });
|
||||
await expect(group).toBeVisible();
|
||||
expect((await popup.boundingBox())!.width).toBeLessThan(360);
|
||||
await expect(popup.getByRole("option")).toHaveCount(3);
|
||||
const introduce = popup.getByRole("option", { name: /Introduce Variable/ });
|
||||
await expect(introduce.getByText("2", { exact: true })).toBeVisible();
|
||||
|
||||
await page.keyboard.press("ArrowDown");
|
||||
await expect(introduce).toHaveAttribute("aria-selected", "true");
|
||||
await page.keyboard.press("2");
|
||||
await expect(popup).toBeHidden();
|
||||
await expect(page.locator("body")).toHaveAttribute("data-selected-refactoring", "extractVariable");
|
||||
});
|
||||
|
||||
test("filtering keeps captions only for groups with a matching action", async ({ workbench: page }) => {
|
||||
await openRefactorList(page);
|
||||
const popup = page.getByRole("dialog", { name: "Refactor This", exact: true });
|
||||
const list = popup.getByRole("listbox");
|
||||
const group = popup.getByText("Extract/Introduce", { exact: true });
|
||||
await expect(list).toBeFocused();
|
||||
await expect(group).toBeVisible();
|
||||
|
||||
await page.keyboard.type("variable");
|
||||
await expect(group).toBeVisible();
|
||||
await expect(popup.getByRole("option")).toHaveCount(1);
|
||||
await expect(popup.getByRole("option")).toHaveAttribute("aria-selected", "true");
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(page.locator("body")).toHaveAttribute("data-selected-refactoring", "extractVariable");
|
||||
|
||||
await openRefactorList(page);
|
||||
await expect(list).toBeFocused();
|
||||
await page.keyboard.type("rename");
|
||||
await expect(group).toBeHidden();
|
||||
await expect(popup.getByRole("option", { name: /Rename/ })).toHaveAttribute("aria-selected", "true");
|
||||
});
|
||||
@@ -1,77 +0,0 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import { expect, test } from "./fixtures";
|
||||
|
||||
const primary = "Prepare invoices for the payments staging environment";
|
||||
|
||||
async function seedConfigurations(page: Page, mode: "select" | "run") {
|
||||
await page.evaluate(
|
||||
async ({ name, mode }) => {
|
||||
const path = "/src/features/run/store.ts";
|
||||
const { useRun } = await import(/* @vite-ignore */ path);
|
||||
const configs = [name, ...Array.from({ length: 19 }, (_, i) => `Payments check ${i + 1}`)].map((label, i) => ({
|
||||
id: `user:chooser-${i}`,
|
||||
name: label,
|
||||
kind: "shell",
|
||||
command: "node",
|
||||
args: ["src/index.ts"],
|
||||
cwd: null,
|
||||
env: {},
|
||||
detected: false,
|
||||
isTest: false,
|
||||
debugAdapter: null,
|
||||
}));
|
||||
useRun.setState({ configs, selectedId: configs[0]!.id, chooserMode: mode, chooserOpen: true, loaded: true });
|
||||
},
|
||||
{ name: primary, mode },
|
||||
);
|
||||
}
|
||||
|
||||
test("the run chooser fits a long name beside its inline actions and keeps its width while filtering", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 1120, height: 680 });
|
||||
await seedConfigurations(page, "select");
|
||||
const chooser = page.getByRole("dialog", { name: "Run/Debug Configurations", exact: true });
|
||||
const label = chooser.getByText(primary, { exact: true });
|
||||
await expect(label).toBeVisible();
|
||||
const width = (await chooser.boundingBox())!.width;
|
||||
expect(width).toBeGreaterThan(340);
|
||||
expect(width).toBeLessThanOrEqual(500);
|
||||
await expect(chooser.getByRole("button", { name: `Run '${primary}'`, exact: true })).toBeVisible();
|
||||
const nameOverflow = await label.evaluate(async (el) => {
|
||||
await document.fonts.ready;
|
||||
const text = document.createRange();
|
||||
text.selectNodeContents(el);
|
||||
return text.getBoundingClientRect().width - el.getBoundingClientRect().width;
|
||||
});
|
||||
expect(nameOverflow).toBeLessThanOrEqual(0);
|
||||
|
||||
const search = chooser.getByRole("textbox", { name: "Search configurations" });
|
||||
await search.fill("Payments check 19");
|
||||
await expect(chooser.getByText("Payments check 19", { exact: true })).toBeVisible();
|
||||
expect((await chooser.boundingBox())!.width).toBeCloseTo(width);
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(chooser).toBeHidden();
|
||||
await expect(page.locator("[data-run-chooser]")).toContainText("Payments check 19");
|
||||
});
|
||||
|
||||
test("in a short window only the list scrolls, leaving the search and shortcuts visible", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 780, height: 280 });
|
||||
await seedConfigurations(page, "run");
|
||||
const chooser = page.getByRole("dialog", { name: "Run/Debug Configurations", exact: true });
|
||||
const list = chooser.getByRole("listbox", { name: "Configurations" });
|
||||
const search = chooser.getByRole("textbox", { name: "Search configurations" });
|
||||
const hint = chooser.getByText("Hold Shift to Debug, F4 to edit, Delete to remove", { exact: true });
|
||||
await expect(search).toBeFocused();
|
||||
await expect(hint).toBeInViewport({ ratio: 1 });
|
||||
expect(await chooser.evaluate((el) => el.scrollHeight - el.clientHeight)).toBeLessThanOrEqual(1);
|
||||
expect(await list.evaluate((el) => el.scrollHeight - el.clientHeight)).toBeGreaterThan(0);
|
||||
|
||||
await page.keyboard.press("End");
|
||||
await expect(chooser.getByRole("option", { name: /Edit Configurations/ })).toBeInViewport({ ratio: 1 });
|
||||
await expect.poll(() => list.evaluate((el) => el.scrollTop)).toBeGreaterThan(0);
|
||||
await expect(search).toBeInViewport({ ratio: 1 });
|
||||
await expect(hint).toBeInViewport({ ratio: 1 });
|
||||
});
|
||||
@@ -1,50 +0,0 @@
|
||||
import { expect, test } from "./fixtures";
|
||||
|
||||
test("Select In names the chooser and reveals the file in the requested project view", async ({ workbench: page }) => {
|
||||
const tree = page.getByRole("tree", { name: "Project", exact: true });
|
||||
await tree.getByRole("treeitem", { name: "settings.gradle.kts", exact: true }).dblclick();
|
||||
await expect(page.locator(".cm-content")).toBeVisible();
|
||||
|
||||
const openChooser = () =>
|
||||
page.evaluate(async () => {
|
||||
const actions = "/src/platform/actions.ts";
|
||||
await (await import(/* @vite-ignore */ actions)).executeAction("navigate.selectIn");
|
||||
});
|
||||
await openChooser();
|
||||
const menu = page.getByRole("menu", { name: "Select In", exact: true });
|
||||
await expect(menu.getByText("Select In", { exact: true })).toBeVisible();
|
||||
const project = menu.getByRole("menuitem", { name: "Project View", exact: true });
|
||||
await expect(project).toBeFocused();
|
||||
await expect(project.locator('[data-menu-number="1"]')).toBeVisible();
|
||||
|
||||
await page.keyboard.press("ArrowRight");
|
||||
const projectFiles = page.getByRole("menuitem", { name: "Project Files", exact: true });
|
||||
await expect(project).toHaveAttribute("aria-expanded", "true");
|
||||
await expect(projectFiles).toBeVisible();
|
||||
await expect(page.getByRole("menuitem", { name: "Open Files", exact: true })).toBeEnabled();
|
||||
await expect(page.getByRole("menuitem", { name: "All Changed Files", exact: true })).toBeDisabled();
|
||||
await page.keyboard.press("ArrowLeft");
|
||||
await expect(projectFiles).toBeHidden();
|
||||
await expect(project).toBeFocused();
|
||||
await page.keyboard.press("ArrowRight");
|
||||
await page.keyboard.press("ArrowDown");
|
||||
await expect(projectFiles).toBeFocused();
|
||||
await page.keyboard.press("Enter");
|
||||
|
||||
await expect(menu).toBeHidden();
|
||||
await expect(page.getByRole("button", { name: "Project Files", exact: true })).toBeVisible();
|
||||
const file = tree.getByRole("treeitem", { name: "settings.gradle.kts", exact: true });
|
||||
await expect(file).toHaveAttribute("aria-selected", "true");
|
||||
|
||||
await page.locator(".cm-content").focus();
|
||||
await openChooser();
|
||||
await expect(project).toBeFocused();
|
||||
await project.locator("[data-menu-submenu-arrow]").click();
|
||||
await expect(projectFiles).toBeVisible();
|
||||
await page.keyboard.press("ArrowLeft");
|
||||
await expect(project).toBeFocused();
|
||||
await page.keyboard.press("1");
|
||||
await expect(menu).toBeHidden();
|
||||
await expect(page.getByRole("button", { name: "Project Files", exact: true })).toBeVisible();
|
||||
await expect(file).toHaveAttribute("aria-selected", "true");
|
||||
});
|
||||
+5
-97
@@ -1,59 +1,5 @@
|
||||
import { expect, stubDesktop, test } from "./fixtures";
|
||||
|
||||
test("System Settings groups file controls before caches and keeps the idle timeout unit beside its field", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.keyboard.press("Meta+,");
|
||||
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
|
||||
const system = dialog.getByRole("treeitem", { name: "System Settings", exact: true });
|
||||
const search = dialog.getByRole("textbox", { name: "Search settings" });
|
||||
await search.fill("Autosave");
|
||||
await expect(system).toBeVisible();
|
||||
await search.clear();
|
||||
await system.click();
|
||||
const exit = dialog.getByRole("checkbox", { name: "Confirm before exiting the IDE" });
|
||||
const reopen = dialog.getByRole("checkbox", { name: "Reopen projects on startup" });
|
||||
const project = dialog.getByRole("region", { name: "Project", exact: true });
|
||||
const directory = project.getByRole("textbox", { name: /^Default directory/ });
|
||||
const browse = project.getByRole("button", { name: "Browse", exact: true });
|
||||
const idle = dialog.getByRole("checkbox", { name: "Save files if the IDE is idle for" });
|
||||
const timeout = dialog.getByRole("textbox", { name: "Idle seconds" });
|
||||
const unit = dialog.getByText("seconds", { exact: true });
|
||||
const caches = dialog.getByRole("region", { name: "Caches", exact: true });
|
||||
for (const width of [1120, 580]) {
|
||||
await page.setViewportSize({ width, height: 760 });
|
||||
await expect(async () => {
|
||||
const [exitBox, projectBox, idleBox, timeoutBox, unitBox, cacheBox] = await Promise.all(
|
||||
[exit, reopen, idle, timeout, unit, caches].map((item) => item.boundingBox()),
|
||||
);
|
||||
expect(exitBox!.y).toBeLessThan(projectBox!.y);
|
||||
expect(projectBox!.y).toBeLessThan(idleBox!.y);
|
||||
expect(idleBox!.y).toBeLessThan(cacheBox!.y);
|
||||
expect(unitBox!.x).toBeGreaterThanOrEqual(timeoutBox!.x + timeoutBox!.width);
|
||||
expect(unitBox!.y).toBeGreaterThan(timeoutBox!.y);
|
||||
expect(unitBox!.y + unitBox!.height).toBeLessThanOrEqual(timeoutBox!.y + timeoutBox!.height + 1);
|
||||
const [directoryBox, browseBox] = await Promise.all([directory.boundingBox(), browse.boundingBox()]);
|
||||
expect(browseBox!.x).toBeGreaterThanOrEqual(directoryBox!.x + directoryBox!.width);
|
||||
expect(browseBox!.y).toBeGreaterThanOrEqual(directoryBox!.y);
|
||||
expect(browseBox!.y + browseBox!.height).toBeLessThanOrEqual(directoryBox!.y + directoryBox!.height + 1);
|
||||
}).toPass({ timeout: 3000 });
|
||||
}
|
||||
|
||||
const files = dialog.getByRole("region", { name: "Files", exact: true });
|
||||
const sync = files
|
||||
.getByRole("group", { name: "Synchronization", exact: true })
|
||||
.getByRole("checkbox", { name: "Synchronize external changes when switching to the IDE window" });
|
||||
await idle.check();
|
||||
await timeout.fill("22");
|
||||
await sync.uncheck();
|
||||
await dialog.getByRole("button", { name: "OK", exact: true }).click();
|
||||
await page.keyboard.press("Meta+,");
|
||||
await system.click();
|
||||
await expect(idle).toBeChecked();
|
||||
await expect(timeout).toHaveValue("22");
|
||||
await expect(sync).not.toBeChecked();
|
||||
});
|
||||
|
||||
test("Add Python Interpreter keeps environment labels and fields inside their rows", async ({ workbench: page }) => {
|
||||
await page.keyboard.press("Meta+,");
|
||||
const settings = page.getByRole("dialog", { name: "Settings", exact: true });
|
||||
@@ -174,53 +120,15 @@ test("Directory Mappings keeps the controls and headers visible while scrolling
|
||||
name: "VCS of integrations/finance-and-order-reconciliation/ledger-adapter-32",
|
||||
exact: true,
|
||||
});
|
||||
await name.click();
|
||||
const remove = toolbar.getByRole("button", { name: "Remove", exact: true });
|
||||
await expect(remove).toBeEnabled();
|
||||
await remove.click();
|
||||
const unregistered = table.getByRole("rowgroup", { name: "Unregistered roots" });
|
||||
await expect(unregistered.getByRole("row").last()).toContainText("ledger-adapter-32");
|
||||
await expect(repo).toHaveAttribute("aria-selected", "true");
|
||||
await expect(repo.getByRole("cell", { name: "Git", exact: true })).toBeVisible();
|
||||
await expect(remove).toBeDisabled();
|
||||
await vcs.click();
|
||||
await page.getByRole("option", { name: "<none>", exact: true }).click();
|
||||
await expect(vcs).toHaveText("<none>");
|
||||
|
||||
const add = toolbar.getByRole("button", { name: "Add", exact: true });
|
||||
await add.click();
|
||||
await expect(vcs).toHaveText("Git");
|
||||
await expect(unregistered).toHaveCount(0);
|
||||
await expect(table.getByText("billing-audit-adapter", { exact: true })).toHaveCount(0);
|
||||
|
||||
const ledger = (n: number) => table.getByText(`ledger-adapter-${n}`, { exact: true });
|
||||
const selectedNames = () => table.locator("tr[aria-selected=true] td:first-child").allTextContents();
|
||||
await ledger(29).click();
|
||||
await ledger(31).click({ modifiers: ["Meta"] });
|
||||
expect(await selectedNames()).toEqual([
|
||||
"integrations/finance-and-order-reconciliation/ledger-adapter-29",
|
||||
"integrations/finance-and-order-reconciliation/ledger-adapter-31",
|
||||
]);
|
||||
await ledger(29).click();
|
||||
await ledger(31).click({ modifiers: ["Shift"] });
|
||||
await expect(table.locator("tr[aria-selected=true]")).toHaveCount(3);
|
||||
expect(await page.evaluate(() => window.getSelection()?.toString())).toBe("");
|
||||
await remove.click();
|
||||
await expect(unregistered.getByRole("row")).toHaveCount(4);
|
||||
await expect(unregistered.locator("tr[aria-selected=true]")).toHaveCount(3);
|
||||
await expect(unregistered.getByText("ledger-adapter-29", { exact: true })).toBeVisible();
|
||||
await expect(unregistered.getByText("ledger-adapter-30", { exact: true })).toBeVisible();
|
||||
await expect(unregistered.getByText("ledger-adapter-31", { exact: true })).toBeVisible();
|
||||
await ledger(32).click({ modifiers: ["Meta"] });
|
||||
await expect(remove).toBeDisabled();
|
||||
await expect(add).toBeDisabled();
|
||||
await ledger(32).click({ modifiers: ["Meta"] });
|
||||
await add.click();
|
||||
await expect(unregistered).toHaveCount(0);
|
||||
await expect(table.locator("tr[aria-selected=true]")).toHaveCount(3);
|
||||
|
||||
await add.click();
|
||||
await toolbar.getByRole("button", { name: "Add", exact: true }).click();
|
||||
const added = table.getByRole("row").filter({ hasText: "billing-audit-adapter" });
|
||||
await expect(added.getByText("billing-audit-adapter", { exact: true })).toBeInViewport({ ratio: 1 });
|
||||
await expect(added).toHaveAttribute("aria-selected", "true");
|
||||
await remove.click();
|
||||
await toolbar.getByRole("button", { name: "Remove", exact: true }).click();
|
||||
await expect(added).toHaveCount(0);
|
||||
|
||||
await settings.getByRole("button", { name: "Cancel", exact: true }).click();
|
||||
|
||||
@@ -65,26 +65,6 @@ for (const locale of ["en", "zh"]) {
|
||||
});
|
||||
}
|
||||
|
||||
test("keeps Open project in options within narrow System Settings", async ({ workbench: page }) => {
|
||||
await page.keyboard.press("Meta+,");
|
||||
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
|
||||
await expect(dialog).toBeVisible();
|
||||
await selectPage(page, "general");
|
||||
const group = dialog.getByRole("radiogroup", { name: "Open project in", exact: true });
|
||||
const longest = group.getByRole("radio", { name: "New tab in current window", exact: true });
|
||||
await expect(longest).toBeVisible();
|
||||
await page.setViewportSize({ width: 520, height: 760 });
|
||||
const overflow = await longest.evaluate(async (radio) => {
|
||||
await new Promise<void>((resolve) => requestAnimationFrame(() => requestAnimationFrame(() => resolve())));
|
||||
const label = radio.closest("label")!;
|
||||
const group = radio.closest('[role="radiogroup"]')!;
|
||||
const text = document.createRange();
|
||||
text.selectNodeContents(label);
|
||||
return text.getBoundingClientRect().right - group.getBoundingClientRect().right;
|
||||
});
|
||||
expect(overflow).toBeLessThanOrEqual(1);
|
||||
});
|
||||
|
||||
test("settings sidebar resizes with mouse and keyboard and remembers its width", async ({ workbench: page }) => {
|
||||
await page.keyboard.press("Meta+,");
|
||||
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
|
||||
|
||||
@@ -1,59 +1,5 @@
|
||||
import { expect, test } from "./fixtures";
|
||||
|
||||
test("External Tools pairs metadata and separates command fields from advanced options", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.keyboard.press("Meta+,");
|
||||
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
|
||||
const search = dialog.getByRole("textbox", { name: "Search settings" });
|
||||
const openPage = async () => {
|
||||
await search.fill("External Tools");
|
||||
await dialog.getByRole("treeitem", { name: "External Tools", exact: true }).click();
|
||||
await search.clear();
|
||||
};
|
||||
await openPage();
|
||||
await dialog.getByRole("toolbar", { name: "External tools actions" }).getByRole("button", { name: "Add" }).click();
|
||||
const name = dialog.getByRole("textbox", { name: /^Name/ });
|
||||
const group = dialog.getByRole("textbox", { name: /^Group/ });
|
||||
const description = dialog.getByRole("textbox", { name: /^Description/ });
|
||||
for (const width of [1120, 580, 520]) {
|
||||
await page.setViewportSize({ width, height: 760 });
|
||||
await expect(async () => {
|
||||
const [nameBox, groupBox, descriptionBox] = await Promise.all(
|
||||
[name, group, description].map((field) => field.boundingBox()),
|
||||
);
|
||||
if (width === 1120) {
|
||||
expect(groupBox!.y).toBe(nameBox!.y);
|
||||
expect(groupBox!.x).toBeGreaterThan(nameBox!.x + nameBox!.width);
|
||||
} else {
|
||||
expect(groupBox!.y).toBeGreaterThan(nameBox!.y);
|
||||
}
|
||||
expect(descriptionBox!.x).toBe(nameBox!.x);
|
||||
expect(descriptionBox!.y).toBeGreaterThan(groupBox!.y);
|
||||
}).toPass({ timeout: 3000 });
|
||||
}
|
||||
const command = dialog.getByRole("region", { name: "Tool Settings", exact: true });
|
||||
await expect(command.getByRole("textbox", { name: /^Program/ })).toBeVisible();
|
||||
await expect(command.getByRole("textbox", { name: /^Arguments/ })).toBeVisible();
|
||||
await expect(command.getByRole("textbox", { name: /^Working directory/ })).toBeVisible();
|
||||
const sync = dialog.getByRole("checkbox", { name: "Synchronize files after execution" });
|
||||
await expect(sync).toBeHidden();
|
||||
await search.fill("Synchronize files after execution");
|
||||
await expect(sync).toBeVisible();
|
||||
await search.clear();
|
||||
await expect(sync).toBeHidden();
|
||||
await dialog.getByText("Advanced options", { exact: true }).click();
|
||||
await name.fill("Validate project");
|
||||
await sync.setChecked(!(await sync.isChecked()));
|
||||
const enabled = await sync.isChecked();
|
||||
await dialog.getByRole("button", { name: "OK", exact: true }).click();
|
||||
await page.keyboard.press("Meta+,");
|
||||
await openPage();
|
||||
await expect(name).toHaveValue("Validate project");
|
||||
await dialog.getByText("Advanced options", { exact: true }).click();
|
||||
await expect(sync).toBeChecked({ checked: enabled });
|
||||
});
|
||||
|
||||
for (const kind of ["external", "ssh", "target"] as const) {
|
||||
test(`${kind} settings keep long names and details inside their selection row`, async ({ workbench: page }) => {
|
||||
await page.keyboard.press("Meta+,");
|
||||
|
||||
@@ -1,76 +0,0 @@
|
||||
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
|
||||
|
||||
test("Spelling puts dictionary files first and keeps accepted words in separate scopes", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 1120, height: 820 });
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(() => {
|
||||
window.__ipc.handlers.settings_get_global = () => ({});
|
||||
window.__ipc.handlers.settings_get = () => ({});
|
||||
window.__ipc.handlers.settings_set = () => ({});
|
||||
});
|
||||
await page.keyboard.press("Meta+,");
|
||||
const settings = page.getByRole("dialog", { name: "Settings", exact: true });
|
||||
const search = settings.getByRole("textbox", { name: "Search settings" });
|
||||
await search.fill("Spelling");
|
||||
await settings.getByRole("treeitem", { name: "Spelling", exact: true }).click();
|
||||
await search.clear();
|
||||
|
||||
const files = settings.getByRole("region", { name: "Custom dictionaries", exact: true });
|
||||
const words = settings.getByRole("region", { name: "Accepted words", exact: true });
|
||||
const filesList = files.getByRole("listbox", { name: "Custom dictionaries", exact: true });
|
||||
const project = words.getByRole("tab", { name: "Project dictionary", exact: true });
|
||||
const application = words.getByRole("tab", { name: "Application dictionary", exact: true });
|
||||
for (const width of [1120, 580, 520]) {
|
||||
await page.setViewportSize({ width, height: 820 });
|
||||
const [filesBox, wordsBox] = await Promise.all([files.boundingBox(), words.boundingBox()]);
|
||||
if (!filesBox || !wordsBox) throw new Error("Missing Spelling sections");
|
||||
expect(filesBox.y + filesBox.height).toBeLessThan(wordsBox.y);
|
||||
const [paths, accepted] = await Promise.all([filesList.boundingBox(), words.getByRole("listbox").boundingBox()]);
|
||||
if (!paths || !accepted) throw new Error("Missing dictionary lists");
|
||||
expect(paths.width).toBeCloseTo(accepted.width, 0);
|
||||
if (width === 1120) expect(paths.width).toBeGreaterThan(480);
|
||||
await expect(project).toBeInViewport({ ratio: 1 });
|
||||
await expect(application).toBeInViewport({ ratio: 1 });
|
||||
}
|
||||
|
||||
await files.getByRole("button", { name: "Add", exact: true }).click();
|
||||
await files.getByRole("textbox", { name: "Dictionary path" }).fill("dictionaries/team.dic");
|
||||
await files.getByRole("textbox", { name: "Dictionary path" }).press("Enter");
|
||||
await expect(filesList.getByRole("option", { name: "dictionaries/team.dic" })).toBeVisible();
|
||||
|
||||
await expect(project).toHaveAttribute("aria-selected", "true");
|
||||
await words.getByRole("button", { name: "Add", exact: true }).click();
|
||||
await words.getByRole("textbox", { name: "Word", exact: true }).fill("checkoutable");
|
||||
await words.getByRole("textbox", { name: "Word", exact: true }).press("Enter");
|
||||
await project.press("ArrowRight");
|
||||
await expect(application).toHaveAttribute("aria-selected", "true");
|
||||
await expect(words.getByRole("option", { name: "checkoutable" })).toHaveCount(0);
|
||||
await words.getByRole("button", { name: "Add", exact: true }).click();
|
||||
await words.getByRole("textbox", { name: "Word", exact: true }).fill("worktree");
|
||||
await words.getByRole("textbox", { name: "Word", exact: true }).press("Enter");
|
||||
|
||||
await project.click();
|
||||
await expect(words.getByRole("option", { name: "checkoutable" })).toBeVisible();
|
||||
await expect(words.getByRole("option", { name: "worktree" })).toHaveCount(0);
|
||||
expect(await ipcCalls(page, "settings_set")).toEqual([]);
|
||||
await settings.getByRole("button", { name: "Apply", exact: true }).click();
|
||||
await expect
|
||||
.poll(async () => (await ipcCalls(page, "settings_set")).sort((a, b) => String(a.key).localeCompare(String(b.key))))
|
||||
.toEqual([
|
||||
{ scope: "global", key: "spelling.customDictionaries", value: JSON.stringify(["dictionaries/team.dic"]) },
|
||||
{ scope: "global", key: "spelling.ideWords", value: JSON.stringify(["worktree"]) },
|
||||
{ scope: "project", key: "spelling.projectWords", value: JSON.stringify(["checkoutable"]) },
|
||||
]);
|
||||
await settings.getByRole("button", { name: "Cancel", exact: true }).click();
|
||||
await page.evaluate(async () => {
|
||||
const actionModule = "/src/platform/actions.ts";
|
||||
const { executeAction } = await import(/* @vite-ignore */ actionModule);
|
||||
await executeAction("file.newProjectsSettings", "editor.naturalLanguages.spelling");
|
||||
});
|
||||
const defaults = page.getByRole("dialog", { name: "Settings for New Projects", exact: true });
|
||||
await expect(defaults.getByRole("listbox", { name: "Application dictionary", exact: true })).toBeVisible();
|
||||
await expect(defaults.getByRole("tablist", { name: "Accepted words" })).toHaveCount(0);
|
||||
await expect(defaults.getByRole("listbox", { name: "Project dictionary", exact: true })).toHaveCount(0);
|
||||
});
|
||||
@@ -1,92 +0,0 @@
|
||||
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
|
||||
|
||||
test("Terminal settings keep shell controls and font groups readable as the window narrows", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 1120, height: 900 });
|
||||
await stubDesktop(page);
|
||||
const shellPath = "C:/Program Files/Shell/bin/bash.exe";
|
||||
await page.evaluate((path) => {
|
||||
window.__ipc.handlers.settings_get_global = () => ({});
|
||||
window.__ipc.handlers.term_default_shell = () => "/bin/zsh";
|
||||
window.__ipc.handlers.term_available_shells = () => ["/bin/zsh", path];
|
||||
}, shellPath);
|
||||
await page.keyboard.press("Meta+,");
|
||||
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
|
||||
const search = dialog.getByRole("textbox", { name: "Search settings" });
|
||||
await search.fill("Shell path");
|
||||
await dialog.getByRole("treeitem", { name: "Terminal", exact: true }).click();
|
||||
await search.clear();
|
||||
|
||||
const directory = dialog.getByRole("textbox", { name: /^Start directory:?$/ });
|
||||
const shell = dialog.getByRole("textbox", { name: /^Shell path:?$/ });
|
||||
const tab = dialog.getByRole("textbox", { name: /^Default Tab name:?$/ });
|
||||
const shells = dialog.getByRole("button", { name: "Installed Shells", exact: true });
|
||||
const browse = dialog.getByRole("button", { name: "Browse", exact: true });
|
||||
const font = dialog.getByRole("combobox", { name: "Terminal font", exact: true });
|
||||
const fallback = dialog.getByRole("combobox", { name: "Terminal fallback font", exact: true });
|
||||
const size = dialog.getByRole("textbox", { name: "Terminal font size", exact: true });
|
||||
const lineHeight = dialog.getByRole("textbox", { name: "Terminal line height", exact: true });
|
||||
const column = dialog.getByRole("textbox", { name: "Terminal column width", exact: true });
|
||||
const bell = dialog.getByRole("checkbox", { name: "Audible bell", exact: true });
|
||||
const shortcuts = dialog.getByRole("checkbox", { name: "Override IDE shortcuts", exact: true });
|
||||
await expect(shell).toHaveAttribute("placeholder", "/bin/zsh");
|
||||
|
||||
for (const width of [1120, 580, 520]) {
|
||||
await page.setViewportSize({ width, height: 900 });
|
||||
await shell.scrollIntoViewIfNeeded();
|
||||
await expect(shells).toBeInViewport({ ratio: 1 });
|
||||
await expect(browse).toBeInViewport({ ratio: 1 });
|
||||
const [dir, command, name, menu, chooseFile, main, secondary, fontSize, line, col, left, right] = await Promise.all(
|
||||
[directory, shell, tab, shells, browse, font, fallback, size, lineHeight, column, bell, shortcuts].map(
|
||||
(control) => control.boundingBox(),
|
||||
),
|
||||
);
|
||||
if (
|
||||
!dir ||
|
||||
!command ||
|
||||
!name ||
|
||||
!menu ||
|
||||
!chooseFile ||
|
||||
!main ||
|
||||
!secondary ||
|
||||
!fontSize ||
|
||||
!line ||
|
||||
!col ||
|
||||
!left ||
|
||||
!right
|
||||
)
|
||||
throw new Error("Missing Terminal settings bounds");
|
||||
expect(command.y + command.height / 2).toBeCloseTo(menu.y + menu.height / 2, 0);
|
||||
expect(menu.y).toBeCloseTo(chooseFile.y, 0);
|
||||
expect(command.width).toBeGreaterThan(100);
|
||||
expect(command.x).toBeCloseTo(name.x, 0);
|
||||
expect(chooseFile.x + chooseFile.width).toBeCloseTo(name.x + name.width, 0);
|
||||
expect(dir.x + dir.width).toBeCloseTo(name.x + name.width, 0);
|
||||
expect(main.y).toBeLessThan(command.y);
|
||||
if (width === 1120) {
|
||||
expect(main.y).toBeCloseTo(secondary.y, 0);
|
||||
expect(fontSize.y).toBeCloseTo(line.y, 0);
|
||||
expect(fontSize.y).toBeCloseTo(col.y, 0);
|
||||
expect(right.x).toBeGreaterThan(left.x);
|
||||
} else {
|
||||
expect(command.x).toBeCloseTo(dir.x, 0);
|
||||
expect(secondary.y).toBeGreaterThan(main.y);
|
||||
expect(right.x).toBeCloseTo(left.x, 0);
|
||||
expect(right.y).toBeGreaterThan(left.y);
|
||||
}
|
||||
}
|
||||
|
||||
await shells.click();
|
||||
await page.getByRole("menuitemcheckbox", { name: shellPath, exact: true }).click();
|
||||
await expect(shell).toHaveValue(`"${shellPath}"`);
|
||||
await expect(font).toBeDisabled();
|
||||
await dialog.getByRole("checkbox", { name: "Use editor font", exact: true }).uncheck();
|
||||
await font.fill("Cascadia Mono");
|
||||
await size.fill("15");
|
||||
await expect(font).toHaveValue("Cascadia Mono");
|
||||
await expect(size).toHaveValue("15");
|
||||
await dialog.getByRole("button", { name: "Cancel", exact: true }).click();
|
||||
await expect(dialog).toBeHidden();
|
||||
expect(await ipcCalls(page, "settings_set")).toEqual([]);
|
||||
});
|
||||
@@ -1,61 +0,0 @@
|
||||
import { expect, test } from "./fixtures";
|
||||
|
||||
test("Customize Main Toolbar keeps layout actions above the groups and stacks them in a narrow window", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
const open = () =>
|
||||
page.evaluate(async () => {
|
||||
const path = "/src/platform/actions.ts";
|
||||
await (await import(/* @vite-ignore */ path)).executeAction("toolbar.customize");
|
||||
});
|
||||
await open();
|
||||
const dialog = page.getByRole("dialog", { name: "Customize Main Toolbar", exact: true });
|
||||
const left = dialog.getByRole("listbox", { name: "Left group" });
|
||||
const right = dialog.getByRole("listbox", { name: "Right group" });
|
||||
const add = dialog.getByRole("button", { name: "Add…", exact: true });
|
||||
const restore = dialog.getByRole("button", { name: "Restore Defaults", exact: true });
|
||||
await expect(left).toBeFocused();
|
||||
|
||||
for (const width of [1120, 460]) {
|
||||
await page.setViewportSize({ width, height: 620 });
|
||||
await expect(async () => {
|
||||
const [addBox, restoreBox, leftBox, rightBox] = await Promise.all(
|
||||
[add, restore, left, right].map((el) => el.boundingBox()),
|
||||
);
|
||||
expect(addBox!.y + addBox!.height).toBeLessThan(leftBox!.y);
|
||||
expect(restoreBox!.y).toBe(addBox!.y);
|
||||
if (width === 1120) {
|
||||
expect(rightBox!.y).toBe(leftBox!.y);
|
||||
expect(rightBox!.x).toBeGreaterThan(leftBox!.x + leftBox!.width);
|
||||
} else {
|
||||
expect(rightBox!.y).toBeGreaterThan(leftBox!.y + leftBox!.height);
|
||||
expect(rightBox!.width).toBe(leftBox!.width);
|
||||
}
|
||||
}).toPass({ timeout: 3000 });
|
||||
}
|
||||
|
||||
const actions = dialog.getByRole("toolbar", { name: "Toolbar actions" });
|
||||
const project = (group: typeof left) => group.getByRole("option", { name: "Project Widget", exact: true });
|
||||
await expect(project(left)).toHaveAttribute("aria-selected", "true");
|
||||
await actions.getByRole("button", { name: "Move Down" }).click();
|
||||
await expect(left.getByRole("option").nth(1)).toHaveText("Project Widget");
|
||||
await actions.getByRole("button", { name: "Move to Right" }).click();
|
||||
await expect(project(right)).toBeVisible();
|
||||
await actions.getByRole("button", { name: "Remove", exact: true }).click();
|
||||
await expect(project(right)).toHaveCount(0);
|
||||
|
||||
await add.click();
|
||||
const search = dialog.getByRole("textbox", { name: "Search actions" });
|
||||
await expect(search).toBeFocused();
|
||||
await search.fill("Project Widget");
|
||||
const available = dialog.getByRole("listbox", { name: "Actions and widgets to add" });
|
||||
await available.getByRole("option", { name: /Project Widget/ }).click();
|
||||
await expect(project(right)).toBeVisible();
|
||||
await expect(search).toHaveCount(0);
|
||||
|
||||
await restore.click();
|
||||
await expect(left.getByRole("option").first()).toHaveText("Project Widget");
|
||||
await expect(project(right)).toHaveCount(0);
|
||||
await dialog.getByRole("button", { name: "Cancel", exact: true }).click();
|
||||
await expect(dialog).toBeHidden();
|
||||
});
|
||||
@@ -71,17 +71,12 @@ test("⌘1 focuses, hides and re-shows the Project tool window", async ({ workbe
|
||||
|
||||
test("⌘4 toggles Run; Shift+Escape hides the active tool window", async ({ workbench: page }) => {
|
||||
const run = page.getByRole("region", { name: "Run" });
|
||||
// The shortcut hides the window only once it is active: activation focuses it a frame after it shows.
|
||||
const focusedInRun = () =>
|
||||
expect.poll(() => page.evaluate(() => !!document.activeElement?.closest('[data-toolwindow="run"]'))).toBe(true);
|
||||
await page.keyboard.press("Meta+4");
|
||||
await expect(run).toBeVisible();
|
||||
await focusedInRun();
|
||||
await page.keyboard.press("Meta+4");
|
||||
await expect(run).toBeHidden();
|
||||
await page.keyboard.press("Meta+4");
|
||||
await expect(run).toBeVisible();
|
||||
await focusedInRun();
|
||||
await page.keyboard.press("Shift+Escape");
|
||||
await expect(run).toBeHidden();
|
||||
});
|
||||
|
||||
+1
-24
@@ -39,7 +39,6 @@ for (const windowKind of ["project", "welcome", "lightEdit"]) {
|
||||
test("Updates shows check status and keeps manual checks available when automatic checks are off", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 1120, height: 680 });
|
||||
await page.evaluate(async () => {
|
||||
const ipcPath = "/src/platform/ipc.ts";
|
||||
const actionsPath = "/src/platform/actions.ts";
|
||||
@@ -63,33 +62,11 @@ test("Updates shows check status and keeps manual checks available when automati
|
||||
await expect(dialog.getByText("0.1.39", { exact: true })).toBeVisible();
|
||||
await expect(dialog.getByText("Never", { exact: true })).toBeVisible();
|
||||
const automatic = dialog.getByRole("checkbox", { name: "Check for updates automatically" });
|
||||
const source = dialog.getByRole("button", { name: "Update source", exact: true });
|
||||
const check = dialog.getByRole("button", { name: "Check Now", exact: true });
|
||||
const checked = dialog.getByText("Never", { exact: true });
|
||||
const whatsNew = dialog.getByRole("checkbox", { name: "Show What's New after an update", exact: true });
|
||||
for (const width of [1120, 580, 520]) {
|
||||
await page.setViewportSize({ width, height: 680 });
|
||||
const [automaticBox, sourceBox, checkBox, statusBox, whatsNewBox] = await Promise.all(
|
||||
[automatic, source, check, checked, whatsNew].map((item) => item.boundingBox()),
|
||||
);
|
||||
if (!automaticBox || !sourceBox || !checkBox || !statusBox || !whatsNewBox)
|
||||
throw new Error("Missing Updates controls");
|
||||
expect(checkBox.y).toBeGreaterThan(sourceBox.y + sourceBox.height);
|
||||
expect(sourceBox.y).toBeGreaterThan(automaticBox.y + automaticBox.height);
|
||||
expect(whatsNewBox.y).toBeGreaterThan(checkBox.y + checkBox.height);
|
||||
expect(statusBox.x).toBeGreaterThan(checkBox.x + checkBox.width);
|
||||
expect(Math.abs(statusBox.y + statusBox.height / 2 - checkBox.y - checkBox.height / 2)).toBeLessThan(1.5);
|
||||
await expect(check).toBeInViewport({ ratio: 1 });
|
||||
}
|
||||
await expect(automatic).toBeChecked();
|
||||
await automatic.uncheck();
|
||||
await expect(source).toBeEnabled();
|
||||
await source.click();
|
||||
await page.getByRole("option", { name: "CNB (China mirror)", exact: true }).click();
|
||||
await dialog.getByRole("button", { name: "Apply", exact: true }).click();
|
||||
await expect(automatic).not.toBeChecked();
|
||||
await expect(source).toHaveText("CNB (China mirror)");
|
||||
await check.click();
|
||||
await dialog.getByRole("button", { name: "Check Now", exact: true }).click();
|
||||
await expect(page.locator("body")).toHaveAttribute("data-update-checked", "true");
|
||||
});
|
||||
|
||||
|
||||
@@ -1,95 +0,0 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
|
||||
|
||||
async function openConfirmation(page: Page) {
|
||||
await page.keyboard.press("Meta+,");
|
||||
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
|
||||
const search = dialog.getByRole("textbox", { name: "Search settings" });
|
||||
await search.fill("Remove silently");
|
||||
await dialog.getByRole("treeitem", { name: "Confirmation", exact: true }).click();
|
||||
await search.clear();
|
||||
return dialog;
|
||||
}
|
||||
|
||||
test("VCS confirmation aligns the file policy selectors and keeps edits scoped", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 1120, height: 740 });
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(() => {
|
||||
const global = { onCreate: "ask", onDelete: "ask" };
|
||||
const project: Partial<typeof global> = {};
|
||||
const effective = () => ({ vcs: { confirmation: { ...global, ...project } } });
|
||||
const handlers = window.__ipc.handlers;
|
||||
handlers.settings_get_global = () => ({ vcs: { confirmation: global } });
|
||||
handlers.settings_get = effective;
|
||||
handlers.settings_set = ({ scope, key, value }) => {
|
||||
const policy = String(key).split(".").at(-1);
|
||||
if (policy !== "onCreate" && policy !== "onDelete") throw new Error("Unexpected confirmation setting");
|
||||
const layer = scope === "project" ? project : global;
|
||||
layer[policy] = JSON.parse(String(value));
|
||||
return effective();
|
||||
};
|
||||
});
|
||||
const dialog = await openConfirmation(page);
|
||||
const create = dialog.getByRole("button", { name: "When files are created", exact: true });
|
||||
const remove = dialog.getByRole("button", { name: "When files are deleted", exact: true });
|
||||
const global = dialog.getByRole("radio", { name: "Global", exact: true });
|
||||
const project = dialog.getByRole("radio", { name: "This project", exact: true });
|
||||
const apply = dialog.getByRole("button", { name: "Apply", exact: true });
|
||||
const cancel = dialog.getByRole("button", { name: "Cancel", exact: true });
|
||||
await expect(create).toHaveText("Ask");
|
||||
await expect(remove).toHaveText("Ask");
|
||||
for (const width of [1120, 580, 520]) {
|
||||
await page.setViewportSize({ width, height: 740 });
|
||||
await expect(create).toBeInViewport({ ratio: 1 });
|
||||
await expect(remove).toBeInViewport({ ratio: 1 });
|
||||
const [createBox, removeBox] = await Promise.all([create.boundingBox(), remove.boundingBox()]);
|
||||
if (!createBox || !removeBox) throw new Error("Missing confirmation selector bounds");
|
||||
expect(createBox.y).toBeLessThan(removeBox.y);
|
||||
expect(createBox.x).toBeCloseTo(removeBox.x, 0);
|
||||
expect(createBox.width).toBeCloseTo(removeBox.width, 0);
|
||||
}
|
||||
|
||||
await create.press("Enter");
|
||||
await expect(page.getByRole("listbox", { name: "When files are created", exact: true })).toBeVisible();
|
||||
await page.keyboard.press("ArrowDown");
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(create).toHaveText("Add silently");
|
||||
await remove.click();
|
||||
await page.getByRole("option", { name: "Remove silently", exact: true }).click();
|
||||
await expect(remove).toHaveText("Remove silently");
|
||||
|
||||
await project.click();
|
||||
await create.click();
|
||||
await page.getByRole("option", { name: "Do not add", exact: true }).click();
|
||||
await remove.click();
|
||||
await page.getByRole("option", { name: "Do not remove", exact: true }).click();
|
||||
await expect(create).toHaveText("Do not add");
|
||||
await expect(remove).toHaveText("Do not remove");
|
||||
await global.click();
|
||||
await expect(create).toHaveText("Add silently");
|
||||
await expect(remove).toHaveText("Remove silently");
|
||||
|
||||
expect(await ipcCalls(page, "settings_set")).toEqual([]);
|
||||
await apply.click();
|
||||
await expect(apply).toBeDisabled();
|
||||
expect(await ipcCalls(page, "settings_set")).toEqual([
|
||||
{ scope: "global", key: "vcs.confirmation.onCreate", value: '"silently"' },
|
||||
{ scope: "global", key: "vcs.confirmation.onDelete", value: '"silently"' },
|
||||
{ scope: "project", key: "vcs.confirmation.onCreate", value: '"never"' },
|
||||
{ scope: "project", key: "vcs.confirmation.onDelete", value: '"never"' },
|
||||
]);
|
||||
await cancel.click();
|
||||
await openConfirmation(page);
|
||||
await global.click();
|
||||
await expect(create).toHaveText("Add silently");
|
||||
await expect(remove).toHaveText("Remove silently");
|
||||
await project.click();
|
||||
await expect(create).toHaveText("Do not add");
|
||||
await expect(remove).toHaveText("Do not remove");
|
||||
await remove.click();
|
||||
await page.getByRole("option", { name: "Ask", exact: true }).click();
|
||||
await cancel.click();
|
||||
await openConfirmation(page);
|
||||
await project.click();
|
||||
await expect(remove).toHaveText("Do not remove");
|
||||
});
|
||||
+33
-170
@@ -22,7 +22,7 @@ use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::Path;
|
||||
use tauri::menu::{CheckMenuItem, IsMenuItem, Menu, MenuItem, MenuItemKind, NativeIcon, PredefinedMenuItem, Submenu};
|
||||
use tauri::menu::{CheckMenuItem, IsMenuItem, Menu, MenuItem, MenuItemKind, PredefinedMenuItem, Submenu};
|
||||
use tauri::{AppHandle, Runtime};
|
||||
|
||||
/// Event emitted to the focused window when an IDE menu item is clicked.
|
||||
@@ -805,12 +805,16 @@ pub fn spec(os: Os) -> Vec<Entry> {
|
||||
"toolWindowLayouts",
|
||||
"Tool Window Layouts",
|
||||
vec![
|
||||
toggle("layout.restoreDefault", "Restore Default Layout"),
|
||||
act("layout.saveCurrent", "Save Changes in Current Layout"),
|
||||
act("layout.restoreCurrent", "Restore Current Layout"),
|
||||
SEP,
|
||||
act("layout.save", "Save Current Layout as…"),
|
||||
act("layout.restoreDefault", "Restore Default Layout"),
|
||||
SEP,
|
||||
Entry::Dynamic(DYNAMIC_LAYOUTS),
|
||||
SEP,
|
||||
act("layout.restoreCurrent", "Restore Current Layout"),
|
||||
act("layout.saveCurrent", "Save Changes in Current Layout"),
|
||||
act("layout.save", "Save Current Layout as…"),
|
||||
act("layout.rename", "Rename Layout…"),
|
||||
act("layout.delete", "Delete Layout…"),
|
||||
],
|
||||
),
|
||||
SEP,
|
||||
@@ -1004,32 +1008,6 @@ impl DynamicItem {
|
||||
None => format!("{DYNAMIC_PREFIX}{}", self.action),
|
||||
}
|
||||
}
|
||||
|
||||
fn model(&self) -> MenuNode {
|
||||
MenuNode::Action {
|
||||
id: self.action.clone(),
|
||||
label: self.label.clone(),
|
||||
hint: None,
|
||||
arg: self.arg.clone(),
|
||||
checked: self.checked,
|
||||
}
|
||||
}
|
||||
|
||||
fn render(&self, config: &MenuConfig) -> RenderedItem {
|
||||
RenderedItem::Action {
|
||||
id: self.item_id(),
|
||||
text: self.label.clone(),
|
||||
accel: config.dynamic_accelerator(self).map(Into::into),
|
||||
checked: self.checked,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct LayoutMenu<'a> {
|
||||
id: String,
|
||||
name: &'a str,
|
||||
current: bool,
|
||||
items: Vec<Option<DynamicItem>>,
|
||||
}
|
||||
|
||||
impl MenuConfig {
|
||||
@@ -1041,38 +1019,6 @@ impl MenuConfig {
|
||||
self.dynamic.get(slot).map(Vec::as_slice).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn layout_menus(&self) -> Vec<LayoutMenu<'_>> {
|
||||
self.dynamic_items(DYNAMIC_LAYOUTS)
|
||||
.iter()
|
||||
.filter_map(|layout| {
|
||||
let name = layout.arg.as_deref()?;
|
||||
let current = layout.checked.unwrap_or_default();
|
||||
let command = |action: &str, label_key, fallback| {
|
||||
Some(DynamicItem {
|
||||
action: action.into(),
|
||||
arg: Some(name.into()),
|
||||
label: self.label(label_key, fallback),
|
||||
checked: None,
|
||||
})
|
||||
};
|
||||
let mut items = if current {
|
||||
vec![
|
||||
command("layout.restore", "layout.restoreNamed", "Restore"),
|
||||
command("layout.saveCurrent", "layout.saveNamed", "Save Changes"),
|
||||
]
|
||||
} else {
|
||||
vec![command("layout.restore", "layout.applyNamed", "Apply")]
|
||||
};
|
||||
items.extend([
|
||||
command("layout.rename", "layout.renameNamed", "Rename…"),
|
||||
None,
|
||||
command("layout.delete", "layout.deleteNamed", "Delete…"),
|
||||
]);
|
||||
Some(LayoutMenu { id: format!("layout:{name}"), name, current, items })
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The keymap accelerator shown on the item of action `id`.
|
||||
fn accelerator(&self, id: &str) -> Option<&str> {
|
||||
self.accelerators.get(id).map(String::as_str).filter(|a| !a.is_empty())
|
||||
@@ -1203,9 +1149,8 @@ struct RenderedMenu {
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
enum RenderedItem {
|
||||
Submenu {
|
||||
id: String,
|
||||
id: &'static str,
|
||||
title: String,
|
||||
current: bool,
|
||||
items: Vec<RenderedItem>,
|
||||
},
|
||||
/// `accel` is the spec's accelerator, or else the keymap's from [`MenuConfig::accelerators`].
|
||||
@@ -1254,9 +1199,8 @@ fn render_items(entries: &[Entry], config: &MenuConfig, recent: &[RecentItem]) -
|
||||
for entry in entries {
|
||||
match entry {
|
||||
Entry::Submenu { id, label, children } => out.push(RenderedItem::Submenu {
|
||||
id: (*id).into(),
|
||||
id,
|
||||
title: config.label(id, label),
|
||||
current: false,
|
||||
items: render_items(children, config, recent),
|
||||
}),
|
||||
Entry::Action { id, label, accel, hint, check } => out.push(RenderedItem::Action {
|
||||
@@ -1265,25 +1209,16 @@ fn render_items(entries: &[Entry], config: &MenuConfig, recent: &[RecentItem]) -
|
||||
accel: accel.or_else(|| config.accelerator(id)).map(Into::into),
|
||||
checked: check.then(|| config.checked.iter().any(|c| c == id)),
|
||||
}),
|
||||
Entry::Dynamic(DYNAMIC_LAYOUTS) => {
|
||||
let layouts = config.layout_menus();
|
||||
if !layouts.is_empty() {
|
||||
out.push(RenderedItem::Separator);
|
||||
Entry::Dynamic(slot) => {
|
||||
for item in config.dynamic_items(slot) {
|
||||
out.push(RenderedItem::Action {
|
||||
id: item.item_id(),
|
||||
text: item.label.clone(),
|
||||
accel: config.dynamic_accelerator(item).map(Into::into),
|
||||
checked: item.checked,
|
||||
});
|
||||
}
|
||||
out.extend(layouts.into_iter().map(|layout| {
|
||||
RenderedItem::Submenu {
|
||||
id: layout.id,
|
||||
title: layout.name.replace('&', "&&"),
|
||||
current: layout.current,
|
||||
items: layout
|
||||
.items
|
||||
.into_iter()
|
||||
.map(|item| item.map_or(RenderedItem::Separator, |item| item.render(config)))
|
||||
.collect(),
|
||||
}
|
||||
}));
|
||||
}
|
||||
Entry::Dynamic(slot) => out.extend(config.dynamic_items(slot).iter().map(|item| item.render(config))),
|
||||
Entry::Native(kind) => {
|
||||
out.push(RenderedItem::Native { kind: *kind, text: config.label(kind.key(), kind.default_label()) })
|
||||
}
|
||||
@@ -1309,7 +1244,7 @@ fn render_items(entries: &[Entry], config: &MenuConfig, recent: &[RecentItem]) -
|
||||
|
||||
fn structure_key(item: &RenderedItem) -> (u8, &str) {
|
||||
match item {
|
||||
RenderedItem::Submenu { id, .. } => (0, id.as_str()),
|
||||
RenderedItem::Submenu { id, .. } => (0, *id),
|
||||
RenderedItem::Action { id, checked: None, .. } => (1, id.as_str()),
|
||||
RenderedItem::Action { id, checked: Some(_), .. } => (5, id.as_str()),
|
||||
RenderedItem::Placeholder { id, .. } => (2, id.as_str()),
|
||||
@@ -1366,14 +1301,8 @@ fn append_rendered<R: Runtime>(
|
||||
) -> tauri::Result<()> {
|
||||
for item in items {
|
||||
match item {
|
||||
RenderedItem::Submenu { id, title, current, items } => {
|
||||
let child = Submenu::with_id_and_native_icon(
|
||||
app,
|
||||
format!("submenu:{id}"),
|
||||
title,
|
||||
true,
|
||||
current.then_some(NativeIcon::MenuOnState),
|
||||
)?;
|
||||
RenderedItem::Submenu { id, title, items } => {
|
||||
let child = Submenu::with_id(app, format!("submenu:{id}"), title, true)?;
|
||||
append_rendered(app, &child, items, disabled)?;
|
||||
parent.append(&child)?;
|
||||
}
|
||||
@@ -1491,17 +1420,12 @@ fn sync_item<R: Runtime>(
|
||||
match (existing, previous, next) {
|
||||
(
|
||||
MenuItemKind::Submenu(submenu),
|
||||
RenderedItem::Submenu { title: previous_title, current: previous_current, items: previous_items, .. },
|
||||
RenderedItem::Submenu { title, current, items, .. },
|
||||
RenderedItem::Submenu { title: previous_title, items: previous_items, .. },
|
||||
RenderedItem::Submenu { title, items, .. },
|
||||
) => {
|
||||
if previous_title != title && submenu.set_text(title).is_err() {
|
||||
return false;
|
||||
}
|
||||
if previous_current != current
|
||||
&& submenu.set_native_icon(current.then_some(NativeIcon::MenuOnState)).is_err()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
sync_children(app, submenu, previous_items, items, disabled, true)
|
||||
}
|
||||
(
|
||||
@@ -1572,9 +1496,6 @@ pub enum MenuNode {
|
||||
Submenu {
|
||||
id: String,
|
||||
label: String,
|
||||
/// Saved layout selection, unset for ordinary submenus.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
current: Option<bool>,
|
||||
children: Vec<MenuNode>,
|
||||
},
|
||||
/// Runs `id` with `arg`. Items with an `arg` (Open Recent) carry their final label.
|
||||
@@ -1604,28 +1525,15 @@ pub fn model(spec: &[Entry], recent: &[RecentItem], config: &MenuConfig) -> Vec<
|
||||
Entry::Submenu { id, label, children } => out.push(MenuNode::Submenu {
|
||||
id: (*id).into(),
|
||||
label: (*label).into(),
|
||||
current: None,
|
||||
children: model(children, recent, config),
|
||||
}),
|
||||
Entry::Dynamic(DYNAMIC_LAYOUTS) => {
|
||||
let layouts = config.layout_menus();
|
||||
if !layouts.is_empty() {
|
||||
out.push(MenuNode::Separator);
|
||||
}
|
||||
out.extend(layouts.into_iter().map(|layout| {
|
||||
MenuNode::Submenu {
|
||||
id: layout.id,
|
||||
label: layout.name.into(),
|
||||
current: Some(layout.current),
|
||||
children: layout
|
||||
.items
|
||||
.into_iter()
|
||||
.map(|item| item.map_or(MenuNode::Separator, |item| item.model()))
|
||||
.collect(),
|
||||
}
|
||||
}));
|
||||
}
|
||||
Entry::Dynamic(slot) => out.extend(config.dynamic_items(slot).iter().map(DynamicItem::model)),
|
||||
Entry::Dynamic(slot) => out.extend(config.dynamic_items(slot).iter().map(|d| MenuNode::Action {
|
||||
id: d.action.clone(),
|
||||
label: d.label.clone(),
|
||||
hint: None,
|
||||
arg: d.arg.clone(),
|
||||
checked: d.checked,
|
||||
})),
|
||||
Entry::Action { id, label, hint, .. } => out.push(MenuNode::Action {
|
||||
id: (*id).into(),
|
||||
label: (*label).into(),
|
||||
@@ -2314,53 +2222,6 @@ mod tests {
|
||||
assert_eq!(route(&spec, "dyn:"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saved_layout_submenus_group_commands_by_selection() {
|
||||
let mut config = MenuConfig::default();
|
||||
let mut review = dynamic_item("layout.restore", Some("Review | wide"), "Review | wide");
|
||||
review.checked = Some(true);
|
||||
config
|
||||
.dynamic
|
||||
.insert(DYNAMIC_LAYOUTS.into(), vec![dynamic_item("layout.restore", Some("Focus"), "Focus"), review]);
|
||||
config.labels.insert("menu.layout.applyNamed".into(), "Apply layout".into());
|
||||
let layout_spec = [act("layout.restoreDefault", "Restore Default Layout"), Entry::Dynamic(DYNAMIC_LAYOUTS)];
|
||||
let nodes = model(&layout_spec, &[], &config);
|
||||
assert!(matches!(&nodes[0], MenuNode::Action { id, .. } if id == "layout.restoreDefault"));
|
||||
assert!(matches!(&nodes[1], MenuNode::Separator));
|
||||
let MenuNode::Submenu { label, current: Some(false), children, .. } = &nodes[2] else {
|
||||
panic!("expected an inactive named layout");
|
||||
};
|
||||
assert_eq!(label, "Focus");
|
||||
assert!(matches!(&children[0], MenuNode::Action { label, .. } if label == "Apply layout"));
|
||||
assert_eq!(children.len(), 4);
|
||||
let MenuNode::Submenu { label, current: Some(true), children, .. } = &nodes[3] else {
|
||||
panic!("expected an active named layout");
|
||||
};
|
||||
assert_eq!(label, "Review | wide");
|
||||
let ids: Vec<_> = children
|
||||
.iter()
|
||||
.filter_map(|node| match node {
|
||||
MenuNode::Action { id, arg: Some(name), .. } => {
|
||||
assert_eq!(name, "Review | wide");
|
||||
Some(id.as_str())
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(ids, ["layout.restore", "layout.saveCurrent", "layout.rename", "layout.delete"]);
|
||||
|
||||
let rendered = render_items(&layout_spec, &config, &[]);
|
||||
let RenderedItem::Submenu { current: true, items, .. } = &rendered[3] else {
|
||||
panic!("expected an active native named layout");
|
||||
};
|
||||
let RenderedItem::Action { id, .. } = &items[2] else { panic!("expected Rename") };
|
||||
assert_eq!(
|
||||
route(&layout_spec, id),
|
||||
Some(MenuRoute { action: "layout.rename".into(), arg: Some("Review | wide".into()) }),
|
||||
);
|
||||
assert_eq!(model(&layout_spec, &[], &MenuConfig::default()).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tool_windows_and_layouts_are_listed_by_the_frontend() {
|
||||
fn slots(entries: &[Entry], out: &mut Vec<&'static str>) {
|
||||
@@ -2523,6 +2384,8 @@ mod tests {
|
||||
"layout.restoreCurrent",
|
||||
"layout.save",
|
||||
"layout.restoreDefault",
|
||||
"layout.rename",
|
||||
"layout.delete",
|
||||
"toolwindow.hideActive",
|
||||
"editor.closeOtherTabs",
|
||||
"toolbar.customize",
|
||||
|
||||
@@ -137,7 +137,7 @@ pub struct ComparisonLaunch {
|
||||
|
||||
/// One side of a diff window's comparison (the UI's `DiffSide`, `diffInput.ts`).
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, Type)]
|
||||
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
|
||||
#[serde(tag = "type", rename_all = "camelCase")]
|
||||
pub enum DiffSide {
|
||||
/// File content at a Git revision (`HEAD`, `:0` = index, a commit id).
|
||||
Rev {
|
||||
@@ -151,8 +151,6 @@ pub enum DiffSide {
|
||||
Worktree {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
label: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
label_detail: Option<String>,
|
||||
},
|
||||
/// Another file (Compare With…, Compare Files).
|
||||
File {
|
||||
@@ -160,13 +158,8 @@ pub enum DiffSide {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
label: Option<String>,
|
||||
},
|
||||
/// Literal text, such as clipboard contents or an editor selection.
|
||||
Text {
|
||||
text: String,
|
||||
label: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
label_detail: Option<String>,
|
||||
},
|
||||
/// Literal text: a side that does not exist.
|
||||
Text { text: String, label: String },
|
||||
/// A Local History revision.
|
||||
History { id: String, label: String },
|
||||
}
|
||||
@@ -2222,7 +2215,7 @@ mod tests {
|
||||
let mut diff = DiffLaunch {
|
||||
path: "/p/a.txt".into(),
|
||||
left: DiffSide::Rev { rev: "HEAD".into(), path: None, label: None },
|
||||
right: DiffSide::Worktree { label: None, label_detail: None },
|
||||
right: DiffSide::Worktree { label: None },
|
||||
line: None,
|
||||
};
|
||||
let id = diff_window_id(&diff);
|
||||
@@ -2234,18 +2227,6 @@ mod tests {
|
||||
assert_ne!(diff_window_id(&diff), id);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn diff_window_keeps_file_and_selection_label_details() {
|
||||
for side in [
|
||||
serde_json::json!({"type": "worktree", "label": "file.rs", "labelDetail": "src"}),
|
||||
serde_json::json!({"type": "text", "text": "let x = 1;", "label": "Selection from file.rs", "labelDetail": ""}),
|
||||
serde_json::json!({"type": "text", "text": "let x = 2;", "label": "From Clipboard"}),
|
||||
] {
|
||||
let parsed = serde_json::from_value::<DiffSide>(side.clone()).unwrap();
|
||||
assert_eq!(serde_json::to_value(parsed).unwrap(), side);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_project_window_starts_with_the_header_its_page_draws() {
|
||||
let mut a = AppearanceSettings::default();
|
||||
|
||||
@@ -46,10 +46,7 @@ agent_set_command trusted project_host bin
|
||||
agent_set_config trusted project_host bindings async
|
||||
agent_set_env trusted project_host bindings sync
|
||||
agent_set_mcp_overrides always project_host bindings sync
|
||||
agent_set_skill_overrides always project_host bindings sync
|
||||
agent_shell trusted project_host bindings async
|
||||
agent_skills_list always project_host bindings async
|
||||
agent_skills_set_mode always project_host bindings sync
|
||||
agent_stop_background always project_host bindings async
|
||||
agent_subscribe always project_host bindings sync
|
||||
agent_unarchive always project_host bindings sync
|
||||
|
||||
+18
-157
@@ -143,23 +143,11 @@ export const commands = {
|
||||
agentSetEnv: (id: string, env: { [key in string]: string }) => typedError<null, IdeError>(__TAURI_INVOKE("agent_set_env", { id, env })),
|
||||
/** Updates per-session MCP server enable/disable overrides on `task`. */
|
||||
agentSetMcpOverrides: (task: string, overrides: { [key in string]: boolean }) => typedError<AgentTask_Serialize, IdeError>(__TAURI_INVOKE("agent_set_mcp_overrides", { task, overrides })),
|
||||
/** Updates per-session skill modes on `task`. */
|
||||
agentSetSkillOverrides: (task: string, overrides: { [key in string]: AgentSkillMode }) => typedError<AgentTask_Serialize, IdeError>(__TAURI_INVOKE("agent_set_skill_overrides", { task, overrides })),
|
||||
/**
|
||||
* Runs a `!` line of the composer in the task's folder with the user's shell, without
|
||||
* starting a turn; its output goes to the agent with the next message.
|
||||
*/
|
||||
agentShell: (task: string, command: string, request: RequestId) => typedError<null, IdeError>(__TAURI_INVOKE("agent_shell", { task, command, request })),
|
||||
/**
|
||||
* Every skill discovered in the project and the user's folders, with the mode a session
|
||||
* of this project runs it with (without any session's own overrides).
|
||||
*/
|
||||
agentSkillsList: () => typedError<AgentSkillState[], IdeError>(__TAURI_INVOKE("agent_skills_list")),
|
||||
/**
|
||||
* Sets how `name` may run in `scope`, in the settings file of that scope, and returns the
|
||||
* updated list. `SKILL.md` files are never touched; the default `auto` removes the entry.
|
||||
*/
|
||||
agentSkillsSetMode: (name: string, scope: McpScope, mode: AgentSkillMode) => typedError<AgentSkillState[], IdeError>(__TAURI_INVOKE("agent_skills_set_mode", { name, scope, mode })),
|
||||
/** Stops one of the task's background tasks. */
|
||||
agentStopBackground: (task: string, background: string) => typedError<null, IdeError>(__TAURI_INVOKE("agent_stop_background", { task, background })),
|
||||
/**
|
||||
@@ -550,7 +538,7 @@ export const commands = {
|
||||
docOpenVirtual: (uri: string) => typedError<DocumentInfo, IdeError>(__TAURI_INVOKE("doc_open_virtual", { uri })),
|
||||
/**
|
||||
* Structure view: LSP document symbols when available (with tree-sitter
|
||||
* visibility and type-alias kinds), tree-sitter otherwise.
|
||||
* visibility), tree-sitter otherwise.
|
||||
* Tree-sitter answers come from the per-document tree cache (incremental
|
||||
* re-parse); large documents get no syntax structure.
|
||||
*/
|
||||
@@ -1040,7 +1028,7 @@ export const commands = {
|
||||
*/
|
||||
menuConfigure: (config: MenuConfig) => __TAURI_INVOKE<void>("menu_configure", { config }),
|
||||
/** The menu bar for a title bar drawn by the frontend (Windows). */
|
||||
menuModel: () => __TAURI_INVOKE<MenuNode_Serialize[]>("menu_model"),
|
||||
menuModel: () => __TAURI_INVOKE<MenuNode[]>("menu_model"),
|
||||
/**
|
||||
* Updates the menu after the recent-projects list changed. Only the Open Recent
|
||||
* submenu is rewritten when the rest of the menu is unchanged.
|
||||
@@ -2205,8 +2193,6 @@ export type AgentChange = {
|
||||
removed: number,
|
||||
/** Path before a rename; the left side of its diff reads this path. */
|
||||
oldPath: string | null,
|
||||
/** The repository the file is in, when the task's project holds nested repositories. */
|
||||
repo: IpcPath | null,
|
||||
};
|
||||
|
||||
/** A task's uncommitted files and the commits made since it started. */
|
||||
@@ -2702,11 +2688,6 @@ export type AgentSettings_Deserialize = {
|
||||
* keyed by server name (`[agents.mcpServers.<name>]`).
|
||||
*/
|
||||
mcpServers?: { [key in string]: AgentMcpServer_Deserialize },
|
||||
/**
|
||||
* How agent skills may run, keyed by skill name (`[agents.skills.<name>]`); `SKILL.md`
|
||||
* files on disk are never modified.
|
||||
*/
|
||||
skills?: { [key in string]: AgentSkillPolicy_Deserialize },
|
||||
};
|
||||
|
||||
/** Settings › Agents: what the conversation shows and how messages are sent. */
|
||||
@@ -2747,89 +2728,6 @@ export type AgentSettings_Serialize = {
|
||||
* keyed by server name (`[agents.mcpServers.<name>]`).
|
||||
*/
|
||||
mcpServers: { [key in string]: AgentMcpServer_Serialize },
|
||||
/**
|
||||
* How agent skills may run, keyed by skill name (`[agents.skills.<name>]`); `SKILL.md`
|
||||
* files on disk are never modified.
|
||||
*/
|
||||
skills: { [key in string]: AgentSkillPolicy_Serialize },
|
||||
};
|
||||
|
||||
/** One discovered skill: a folder with a `SKILL.md`. */
|
||||
export type AgentSkill = {
|
||||
/** The frontmatter `name`, else the folder's name. */
|
||||
name: string,
|
||||
description: string,
|
||||
/** Canonical folder holding `SKILL.md` (symlinks resolved, so duplicates collapse). */
|
||||
path: IpcPath,
|
||||
source: AgentSkillSource,
|
||||
/** The `SKILL.md` passes validation (`name` matches its folder, `description` present). */
|
||||
valid: boolean,
|
||||
/** What validation found (`name` mismatch, missing or over-long description…). */
|
||||
warnings: string[],
|
||||
};
|
||||
|
||||
/** How an agent skill may run (`[agents.skills.<name>] mode = …`). */
|
||||
export type AgentSkillMode =
|
||||
/** The model decides when to use it. */
|
||||
"auto" |
|
||||
/** Only when the user invokes it with `/name`. */
|
||||
"slashOnly" |
|
||||
/** Never. */
|
||||
"off";
|
||||
|
||||
/** Which layer decided a skill's [`AgentSkillState::mode`]. */
|
||||
export type AgentSkillOrigin = "none" | "session" | "workspace" | "user" |
|
||||
/** An untrusted workspace's skills and policies may only turn skills off. */
|
||||
"trust";
|
||||
|
||||
/** A skill's policy in Settings › Agents › Skills, stored without touching its `SKILL.md`. */
|
||||
export type AgentSkillPolicy = AgentSkillPolicy_Serialize | AgentSkillPolicy_Deserialize;
|
||||
|
||||
/** A skill's policy in Settings › Agents › Skills, stored without touching its `SKILL.md`. */
|
||||
export type AgentSkillPolicy_Deserialize = {
|
||||
mode?: AgentSkillMode,
|
||||
};
|
||||
|
||||
/** A skill's policy in Settings › Agents › Skills, stored without touching its `SKILL.md`. */
|
||||
export type AgentSkillPolicy_Serialize = {
|
||||
mode: AgentSkillMode,
|
||||
};
|
||||
|
||||
/** Which CLI's own folders a skill was discovered in (Settings › Agents › Skills groups by it). */
|
||||
export type AgentSkillSource =
|
||||
/** The project's `.agents/skills` and `.openidea/skills`. */
|
||||
"workspace" |
|
||||
/** The user's `~/.agents/skills` (what `npx skills add` fills). */
|
||||
"user" |
|
||||
/** The project's `.claude/skills`. */
|
||||
"claudeWorkspace" |
|
||||
/** `~/.claude/skills`. */
|
||||
"claudeUser" |
|
||||
/** The project's `.github/skills` (Copilot's repository skills). */
|
||||
"githubWorkspace" |
|
||||
/** `~/.copilot/skills` and `~/.copilot/installed-plugins/*`. */
|
||||
"copilotUser" |
|
||||
/** The project's `.codex/skills`. */
|
||||
"codexWorkspace" |
|
||||
/** `~/.codex/skills`. */
|
||||
"codexUser" |
|
||||
/** The project's `.cursor/skills`. */
|
||||
"cursorWorkspace" |
|
||||
/** `~/.cursor/skills`. */
|
||||
"cursorUser";
|
||||
|
||||
/**
|
||||
* A skill as Settings › Agents › Skills shows it: discovery plus the effective mode and
|
||||
* which layer decided it.
|
||||
*/
|
||||
export type AgentSkillState = {
|
||||
skill: AgentSkill,
|
||||
mode: AgentSkillMode,
|
||||
/**
|
||||
* What set `mode`: a session override, the workspace, the user's settings, workspace
|
||||
* trust, or nothing (the default `auto`).
|
||||
*/
|
||||
origin: AgentSkillOrigin,
|
||||
};
|
||||
|
||||
/** Where an agent comes from. */
|
||||
@@ -2904,8 +2802,6 @@ export type AgentTask_Deserialize = {
|
||||
background?: AgentBackgroundTask[],
|
||||
/** Per-session MCP server enable/disable overrides (`server_name` -> `enabled`), including `"openidea"`. */
|
||||
mcpOverrides?: { [key in string]: boolean },
|
||||
/** Per-session skill modes (`skill name` -> mode), on top of the settings' policies. */
|
||||
skillOverrides?: { [key in string]: AgentSkillMode },
|
||||
/** Token counts of the last turn and context compressions, when the agent reports them. */
|
||||
stats?: AgentSessionStats,
|
||||
};
|
||||
@@ -2956,8 +2852,6 @@ export type AgentTask_Serialize = {
|
||||
background: AgentBackgroundTask[],
|
||||
/** Per-session MCP server enable/disable overrides (`server_name` -> `enabled`), including `"openidea"`. */
|
||||
mcpOverrides?: { [key in string]: boolean },
|
||||
/** Per-session skill modes (`skill name` -> mode), on top of the settings' policies. */
|
||||
skillOverrides?: { [key in string]: AgentSkillMode },
|
||||
/** Token counts of the last turn and context compressions, when the agent reports them. */
|
||||
stats: AgentSessionStats,
|
||||
};
|
||||
@@ -3908,7 +3802,6 @@ export type CommitSettings = {
|
||||
* window and a Commit dialog.
|
||||
*/
|
||||
nonModal?: boolean,
|
||||
includeChangesByDefault?: boolean,
|
||||
/** Start with an empty message instead of the last one / the changelist's. */
|
||||
clearInitialMessage?: boolean,
|
||||
analyzeCode?: boolean,
|
||||
@@ -5283,28 +5176,28 @@ export type DiffSide = DiffSide_Serialize | DiffSide_Deserialize;
|
||||
/** One side of a diff window's comparison (the UI's `DiffSide`, `diffInput.ts`). */
|
||||
export type DiffSide_Deserialize =
|
||||
/** File content at a Git revision (`HEAD`, `:0` = index, a commit id). */
|
||||
({ type: "rev"; rev: string; path?: string | null; label?: string | null }) & { id?: never; labelDetail?: never; text?: never } |
|
||||
({ type: "rev"; rev: string; path?: string | null; label?: string | null }) & { id?: never; text?: never } |
|
||||
/** The working file (unsaved editor buffer included). */
|
||||
({ type: "worktree"; label?: string | null; labelDetail?: string | null }) & { id?: never; path?: never; rev?: never; text?: never } |
|
||||
({ type: "worktree"; label?: string | null }) & { id?: never; path?: never; rev?: never; text?: never } |
|
||||
/** Another file (Compare With…, Compare Files). */
|
||||
({ type: "file"; path: string; label?: string | null }) & { id?: never; labelDetail?: never; rev?: never; text?: never } |
|
||||
/** Literal text, such as clipboard contents or an editor selection. */
|
||||
({ type: "text"; text: string; label: string; labelDetail?: string | null }) & { id?: never; path?: never; rev?: never } |
|
||||
({ type: "file"; path: string; label?: string | null }) & { id?: never; rev?: never; text?: never } |
|
||||
/** Literal text: a side that does not exist. */
|
||||
({ type: "text"; text: string; label: string }) & { id?: never; path?: never; rev?: never } |
|
||||
/** A Local History revision. */
|
||||
({ type: "history"; id: string; label: string }) & { labelDetail?: never; path?: never; rev?: never; text?: never };
|
||||
({ type: "history"; id: string; label: string }) & { path?: never; rev?: never; text?: never };
|
||||
|
||||
/** One side of a diff window's comparison (the UI's `DiffSide`, `diffInput.ts`). */
|
||||
export type DiffSide_Serialize =
|
||||
/** File content at a Git revision (`HEAD`, `:0` = index, a commit id). */
|
||||
({ type: "rev"; rev: string; path?: string | null; label?: string | null }) & { id?: never; labelDetail?: never; text?: never } |
|
||||
({ type: "rev"; rev: string; path?: string | null; label?: string | null }) & { id?: never; text?: never } |
|
||||
/** The working file (unsaved editor buffer included). */
|
||||
({ type: "worktree"; label?: string | null; labelDetail?: string | null }) & { id?: never; path?: never; rev?: never; text?: never } |
|
||||
({ type: "worktree"; label?: string | null }) & { id?: never; path?: never; rev?: never; text?: never } |
|
||||
/** Another file (Compare With…, Compare Files). */
|
||||
({ type: "file"; path: string; label?: string | null }) & { id?: never; labelDetail?: never; rev?: never; text?: never } |
|
||||
/** Literal text, such as clipboard contents or an editor selection. */
|
||||
({ type: "text"; text: string; label: string; labelDetail?: string | null }) & { id?: never; path?: never; rev?: never } |
|
||||
({ type: "file"; path: string; label?: string | null }) & { id?: never; rev?: never; text?: never } |
|
||||
/** Literal text: a side that does not exist. */
|
||||
({ type: "text"; text: string; label: string }) & { id?: never; path?: never; rev?: never } |
|
||||
/** A Local History revision. */
|
||||
({ type: "history"; id: string; label: string }) & { labelDetail?: never; path?: never; rev?: never; text?: never };
|
||||
({ type: "history"; id: string; label: string }) & { path?: never; rev?: never; text?: never };
|
||||
|
||||
export type DirectoryCompareEntry = {
|
||||
path: string,
|
||||
@@ -7233,8 +7126,6 @@ version: number } |
|
||||
{ type: "docDiskConflict"; doc: DocId; path: string } |
|
||||
/** A complete workspace edit can be undone as one operation. */
|
||||
{ type: "workspaceEditApplied"; id: number; paths: IpcPath[];
|
||||
/** Files the edit renamed, as the edit named them: editors open on them follow. */
|
||||
moves: FileMove[];
|
||||
/**
|
||||
* Made by an agent through the MCP server's tools: undoable like a refactoring, but
|
||||
* not announced as one.
|
||||
@@ -8270,10 +8161,7 @@ export type LineMarkerInfo = {
|
||||
export type LineMatch = {
|
||||
/** 0-based line. */
|
||||
line: number,
|
||||
/**
|
||||
* Line text, truncated around the matches for very long lines: such a line comes as one
|
||||
* `LineMatch` per window, so the same `line` can repeat.
|
||||
*/
|
||||
/** Line text, truncated around the match for very long lines. */
|
||||
text: string,
|
||||
/** UTF-16 column ranges within `text`. */
|
||||
ranges: ([number, number])[],
|
||||
@@ -8968,41 +8856,16 @@ export type MenuConfig = {
|
||||
* A menu entry for a menu bar drawn by the frontend (Windows title bar).
|
||||
* Labels are the English defaults; the frontend localises them like the native menu.
|
||||
*/
|
||||
export type MenuNode = MenuNode_Serialize | MenuNode_Deserialize;
|
||||
|
||||
/**
|
||||
* A menu entry for a menu bar drawn by the frontend (Windows title bar).
|
||||
* Labels are the English defaults; the frontend localises them like the native menu.
|
||||
*/
|
||||
export type MenuNode_Deserialize = ({ kind: "submenu"; id: string; label: string;
|
||||
/** Saved layout selection, unset for ordinary submenus. */
|
||||
current: boolean | null; children: MenuNode_Deserialize[] }) & { arg?: never; checked?: never; hint?: never } |
|
||||
export type MenuNode = { kind: "submenu"; id: string; label: string; children: MenuNode[] } |
|
||||
/**
|
||||
* Runs `id` with `arg`. Items with an `arg` (Open Recent) carry their final label.
|
||||
* `checked` is the state of a frontend-listed toggle (Status Bar Widgets). Spec toggles
|
||||
* leave it unset: the frontend menu reads their state from the action (`toggled`), the
|
||||
* source [`MenuConfig::checked`] is built from for the native menu.
|
||||
*/
|
||||
({ kind: "action"; id: string; label: string; hint: string | null; arg: string | null; checked: boolean | null }) & { children?: never; current?: never } |
|
||||
{ kind: "action"; id: string; label: string; hint: string | null; arg: string | null; checked: boolean | null } |
|
||||
/** A disabled placeholder such as "No Recent Projects". */
|
||||
({ kind: "placeholder"; id: string; label: string }) & { arg?: never; checked?: never; children?: never; current?: never; hint?: never } | ({ kind: "separator" }) & { arg?: never; checked?: never; children?: never; current?: never; hint?: never; id?: never; label?: never };
|
||||
|
||||
/**
|
||||
* A menu entry for a menu bar drawn by the frontend (Windows title bar).
|
||||
* Labels are the English defaults; the frontend localises them like the native menu.
|
||||
*/
|
||||
export type MenuNode_Serialize = ({ kind: "submenu"; id: string; label: string;
|
||||
/** Saved layout selection, unset for ordinary submenus. */
|
||||
current?: boolean | null; children: MenuNode_Serialize[] }) & { arg?: never; checked?: never; hint?: never } |
|
||||
/**
|
||||
* Runs `id` with `arg`. Items with an `arg` (Open Recent) carry their final label.
|
||||
* `checked` is the state of a frontend-listed toggle (Status Bar Widgets). Spec toggles
|
||||
* leave it unset: the frontend menu reads their state from the action (`toggled`), the
|
||||
* source [`MenuConfig::checked`] is built from for the native menu.
|
||||
*/
|
||||
({ kind: "action"; id: string; label: string; hint: string | null; arg: string | null; checked: boolean | null }) & { children?: never; current?: never } |
|
||||
/** A disabled placeholder such as "No Recent Projects". */
|
||||
({ kind: "placeholder"; id: string; label: string }) & { arg?: never; checked?: never; children?: never; current?: never; hint?: never } | ({ kind: "separator" }) & { arg?: never; checked?: never; children?: never; current?: never; hint?: never; id?: never; label?: never };
|
||||
{ kind: "placeholder"; id: string; label: string } | { kind: "separator" };
|
||||
|
||||
/** Merge dialog › Modify options (shared by the Pull dialog). */
|
||||
export type MergeOptions = {
|
||||
@@ -9151,8 +9014,6 @@ export type NewAgentTask = {
|
||||
base: string | null,
|
||||
/** Per-session MCP server enable/disable overrides (`server_name` -> `enabled`). */
|
||||
mcpOverrides?: { [key in string]: boolean },
|
||||
/** Per-session skill modes (`skill name` -> mode). */
|
||||
skillOverrides?: { [key in string]: AgentSkillMode },
|
||||
/**
|
||||
* Creates the task without sending `prompt` (it only names the task): the composer's
|
||||
* `!` command runs in it first.
|
||||
|
||||
@@ -1,118 +0,0 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { EditorSelection, EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { closeBrackets } from "@codemirror/autocomplete";
|
||||
import { insertNewlineAndIndent } from "@codemirror/commands";
|
||||
import { javascript } from "@codemirror/lang-javascript";
|
||||
import { validateEditorExtras } from "@/platform/editorSettings";
|
||||
import { prefsExtension } from "./prefs";
|
||||
import { findLanguageDescription, loadSupport } from "./languages";
|
||||
|
||||
const views: EditorView[] = [];
|
||||
afterEach(() => views.splice(0).forEach((v) => v.destroy()));
|
||||
|
||||
/** A TSX editor wired as the real one: language support (with `autoCloseTags`), closeBrackets and prefs. */
|
||||
function make(text: string) {
|
||||
const at = text.indexOf("|");
|
||||
const view = new EditorView({
|
||||
state: EditorState.create({
|
||||
doc: text.replace("|", ""),
|
||||
selection: EditorSelection.cursor(at),
|
||||
extensions: [
|
||||
javascript({ jsx: true, typescript: true }),
|
||||
closeBrackets(),
|
||||
prefsExtension({
|
||||
prefs: validateEditorExtras({}),
|
||||
path: "",
|
||||
softWrap: false,
|
||||
showWhitespace: false,
|
||||
hardWrapAt: 120,
|
||||
readOnly: false,
|
||||
language: "typescriptreact",
|
||||
}),
|
||||
],
|
||||
}),
|
||||
parent: document.body,
|
||||
});
|
||||
views.push(view);
|
||||
return view;
|
||||
}
|
||||
|
||||
function show(view: EditorView): string {
|
||||
const doc = view.state.doc.toString();
|
||||
const head = view.state.selection.main.head;
|
||||
return doc.slice(0, head) + "|" + doc.slice(head);
|
||||
}
|
||||
|
||||
/** Types `text` one character at a time through the real input handlers. */
|
||||
function type(v: EditorView, text: string) {
|
||||
for (const ch of text) {
|
||||
const r = v.state.selection.main;
|
||||
const insert = () => v.state.update(v.state.replaceSelection(ch), { userEvent: "input.type" });
|
||||
if (!v.state.facet(EditorView.inputHandler).some((h) => h(v, r.from, r.to, ch, insert))) v.dispatch(insert());
|
||||
}
|
||||
}
|
||||
|
||||
describe("JSX tag auto-close", () => {
|
||||
it("closes an opening tag on `>`", () => {
|
||||
const v = make("const a = |;");
|
||||
type(v, "<div>");
|
||||
expect(show(v)).toBe("const a = <div>|</div>;");
|
||||
});
|
||||
|
||||
it("closes components, member names and fragments", () => {
|
||||
const v = make("const a = |;");
|
||||
type(v, "<Foo.Bar>");
|
||||
expect(show(v)).toBe("const a = <Foo.Bar>|</Foo.Bar>;");
|
||||
const f = make("const a = |;");
|
||||
type(f, "<>");
|
||||
expect(show(f)).toBe("const a = <>|</>;");
|
||||
});
|
||||
|
||||
it("closes after attributes, but not self-closing tags", () => {
|
||||
const v = make("const a = |;");
|
||||
type(v, '<div id="x">');
|
||||
expect(show(v)).toBe('const a = <div id="x">|</div>;');
|
||||
const s = make("const a = |;");
|
||||
type(s, "<Foo />");
|
||||
expect(show(s)).toBe("const a = <Foo />|;");
|
||||
});
|
||||
|
||||
it("completes the closing tag on `</`", () => {
|
||||
const v = make("const a = <div>x|;");
|
||||
type(v, "</");
|
||||
expect(show(v)).toBe("const a = <div>x</div>|;");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Enter between JSX tags", () => {
|
||||
/** Presses Enter at `|` with the editor's TSX / JSX mode (its grammar patches included). */
|
||||
async function enter(mode: "TSX" | "JSX", text: string) {
|
||||
const support = await loadSupport(findLanguageDescription(mode, `/p/a.${mode.toLowerCase()}`)!);
|
||||
const at = text.indexOf("|");
|
||||
const view = new EditorView({
|
||||
state: EditorState.create({
|
||||
doc: text.replace("|", ""),
|
||||
selection: EditorSelection.cursor(at),
|
||||
extensions: support!,
|
||||
}),
|
||||
parent: document.body,
|
||||
});
|
||||
views.push(view);
|
||||
insertNewlineAndIndent(view);
|
||||
return show(view);
|
||||
}
|
||||
|
||||
it("puts the caret on an indented line with the closing tag below, at the opening tag's indent", async () => {
|
||||
expect(await enter("TSX", "function A() {\n return (\n <div>|</div>\n );\n}")).toBe(
|
||||
"function A() {\n return (\n <div>\n |\n </div>\n );\n}",
|
||||
);
|
||||
expect(await enter("JSX", 'const a = <Foo.Bar id="x">|</Foo.Bar>;')).toBe(
|
||||
'const a = <Foo.Bar id="x">\n |\n</Foo.Bar>;',
|
||||
);
|
||||
});
|
||||
|
||||
it("only splits a tag pair", async () => {
|
||||
expect(await enter("TSX", "const a = <div>x|</div>;")).toBe("const a = <div>x\n|</div>;");
|
||||
});
|
||||
});
|
||||
@@ -17,7 +17,6 @@ import {
|
||||
language as languageFacet,
|
||||
type StreamParser,
|
||||
} from "@codemirror/language";
|
||||
import { NodeProp } from "@lezer/common";
|
||||
import { styleTags, tags as t } from "@lezer/highlight";
|
||||
import { languages as languageData } from "@codemirror/language-data";
|
||||
import type { DocBackend, LanguageInfo } from "../backend";
|
||||
@@ -451,19 +450,8 @@ const EXTRA_TAGS: Record<string, Parameters<typeof styleTags>[0]> = {
|
||||
|
||||
const bracedIndent = delimitedIndent({ closing: "}" });
|
||||
|
||||
/**
|
||||
* JSX tags pair up as HTML's do: Enter between `<div>` and `</div>` puts the caret on an
|
||||
* indented line of its own with the closing tag below, and the tags match each other.
|
||||
*/
|
||||
const JSX_TAG_PAIRS = [
|
||||
NodeProp.closedBy.add({ JSXOpenTag: ["JSXCloseTag"] }),
|
||||
NodeProp.openedBy.add({ JSXCloseTag: ["JSXOpenTag"] }),
|
||||
];
|
||||
|
||||
/** Grammar props the stock languages lack: indentation that follows the language's usual style, JSX tag pairs. */
|
||||
/** Grammar props the stock languages lack: indentation that follows the language's usual style. */
|
||||
const EXTRA_PROPS: Record<string, NonNullable<Parameters<LRLanguage["configure"]>[0]["props"]>> = {
|
||||
JSX: JSX_TAG_PAIRS,
|
||||
TSX: JSX_TAG_PAIRS,
|
||||
// clang-format's built-in styles (NamespaceIndentation: None, no extern block indent) keep the
|
||||
// contents of `namespace x { … }` and `extern "C" { … }` at the level of the braces' line.
|
||||
"C++": [
|
||||
|
||||
@@ -3,7 +3,6 @@ import { EditorSelection, EditorState, type Extension } from "@codemirror/state"
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { history, redo, undo } from "@codemirror/commands";
|
||||
import { html } from "@codemirror/lang-html";
|
||||
import { javascript } from "@codemirror/lang-javascript";
|
||||
import { linkedTags } from "./linkedTags";
|
||||
import { prefsExtension } from "./prefs";
|
||||
import { angular } from "./angular";
|
||||
@@ -222,53 +221,6 @@ describe("linked html tags", () => {
|
||||
}
|
||||
});
|
||||
|
||||
describe("in JSX / TSX", () => {
|
||||
const tsx = (text: string) => makeWith([javascript({ jsx: true, typescript: true }), linkedTags, history()], text);
|
||||
|
||||
it("renames the closing tag while the opening one is typed, and back", () => {
|
||||
const v = tsx('const a = <div| className="x">hi</div>;');
|
||||
type(v, "s");
|
||||
expect(show(v)).toBe('const a = <divs| className="x">hi</divs>;');
|
||||
const w = tsx("const a = <Foo>hi</Fo|o>;");
|
||||
type(w, "x");
|
||||
expect(show(w)).toBe("const a = <Foxo>hi</Fox|o>;");
|
||||
});
|
||||
|
||||
it("renames member and namespaced names as a whole", () => {
|
||||
const v = tsx("const a = <Foo.Bar|>x</Foo.Bar>;");
|
||||
type(v, "z");
|
||||
expect(v.state.doc.toString()).toBe("const a = <Foo.Barz>x</Foo.Barz>;");
|
||||
const w = tsx("const a = <|Foo.Bar>x</Foo.Bar>;");
|
||||
type(w, "My");
|
||||
expect(w.state.doc.toString()).toBe("const a = <MyFoo.Bar>x</MyFoo.Bar>;");
|
||||
});
|
||||
|
||||
it("follows the element's own closing tag through nested same-name elements", () => {
|
||||
const v = tsx("const a = <div|><div></div></div>;");
|
||||
type(v, "x");
|
||||
expect(v.state.doc.toString()).toBe("const a = <divx><div></div></divx>;");
|
||||
});
|
||||
|
||||
it("leaves fragments, self-closing tags and attributes alone", () => {
|
||||
const v = tsx("const a = <Foo| />;");
|
||||
type(v, "x");
|
||||
expect(v.state.doc.toString()).toBe("const a = <Foox />;");
|
||||
const w = tsx("const a = <div |>x</div>;");
|
||||
type(w, "a");
|
||||
expect(w.state.doc.toString()).toBe("const a = <div a>x</div>;");
|
||||
const f = tsx("const a = <|>x</>;");
|
||||
type(f, "p");
|
||||
expect(f.state.doc.toString()).toBe("const a = <p>x</>;");
|
||||
});
|
||||
|
||||
it("undoes both tags in one step", () => {
|
||||
const v = tsx("const a = <div|></div>;");
|
||||
type(v, "x");
|
||||
expect(undo(v)).toBe(true);
|
||||
expect(v.state.doc.toString()).toBe("const a = <div></div>;");
|
||||
});
|
||||
});
|
||||
|
||||
describe("the smart key gates the filter", () => {
|
||||
/** The real wiring: prefsExtension attaches the filter for the document's language. */
|
||||
const prefs = (language: string | undefined, smartKeys: Record<string, unknown> = {}) =>
|
||||
@@ -304,28 +256,6 @@ describe("linked html tags", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("links tags for JSX / TSX", () => {
|
||||
for (const language of ["typescriptreact", "javascriptreact"]) {
|
||||
const v = makeWith(
|
||||
[
|
||||
javascript({ jsx: true, typescript: language === "typescriptreact" }),
|
||||
prefsExtension({
|
||||
prefs: validateEditorExtras({ smartKeys: {} }),
|
||||
path: "",
|
||||
softWrap: false,
|
||||
showWhitespace: false,
|
||||
hardWrapAt: 120,
|
||||
readOnly: false,
|
||||
language,
|
||||
}),
|
||||
],
|
||||
"const a = <div|></div>;",
|
||||
);
|
||||
type(v, "s");
|
||||
expect(v.state.doc.toString()).toBe("const a = <divs></divs>;");
|
||||
}
|
||||
});
|
||||
|
||||
it("stays off when the option is off", () => {
|
||||
const v = prefs("html", { simultaneousTagEditing: false });
|
||||
type(v, "s");
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
/**
|
||||
* Linked editing for matching HTML and JSX tags, as in IDEA's Simultaneous
|
||||
* Linked editing for matching HTML tags, as in IDEA's Simultaneous
|
||||
* `<tag></tag>` editing (on by default) and VS Code's Linked Editing: editing
|
||||
* the name in an opening (or closing) tag renames the matching tag of the same
|
||||
* element as you type. Done from the syntax tree — `@lezer/html`'s
|
||||
* `OpenTag`/`CloseTag` elements, shared by every HTML-based mode, and
|
||||
* `@lezer/javascript`'s `JSXOpenTag`/`JSXCloseTag` — so it works without a
|
||||
* language server.
|
||||
* `OpenTag`/`CloseTag` elements, shared by every HTML-based mode — so it works
|
||||
* without a language server.
|
||||
*
|
||||
* A transaction whose change lies inside one tag's name is extended with
|
||||
* A transaction whose change lies inside one tag's `TagName` is extended with
|
||||
* the same edit at the same offset in the counterpart's name — one
|
||||
* transaction, so undo takes both back together. Without a matching tag (void
|
||||
* and self-closing tags, unclosed elements, a stray close tag) or with the two
|
||||
@@ -19,37 +18,18 @@ import { syntaxTree } from "@codemirror/language";
|
||||
import type { SyntaxNode, Tree } from "@lezer/common";
|
||||
import { isExternalChange } from "@/editor/api";
|
||||
|
||||
/** A JSX tag's whole name — `div`, `Foo`, `Foo.Bar`, `svg:rect` — as a direct child of its tag. */
|
||||
const JSX_NAMES = new Set(["JSXIdentifier", "JSXBuiltin", "JSXMemberExpression", "JSXNamespacedName"]);
|
||||
const JSX_TAGS = new Set(["JSXOpenTag", "JSXCloseTag"]);
|
||||
|
||||
/** The JSX tag name `n` lies in, or null outside one. */
|
||||
function jsxNameOf(n: SyntaxNode | null): SyntaxNode | null {
|
||||
while (n?.parent && !JSX_TAGS.has(n.parent.name)) n = n.parent;
|
||||
return n?.parent && JSX_NAMES.has(n.name) ? n : null;
|
||||
}
|
||||
|
||||
/** The tag name a changed range edits — an insertion at either edge extends the name. */
|
||||
/** The `TagName` a changed range edits — an insertion at either edge extends the name. */
|
||||
function tagNameAround(tree: Tree, from: number, to: number): SyntaxNode | null {
|
||||
for (const side of [-1, 1] as const) {
|
||||
const inner = tree.resolveInner(from, side);
|
||||
const n = inner.name === "TagName" ? inner : jsxNameOf(inner);
|
||||
if (n && n.from <= from && to <= n.to) return n;
|
||||
}
|
||||
return null;
|
||||
let n = tree.resolveInner(from, -1);
|
||||
if (n.name !== "TagName") n = tree.resolveInner(from, 1);
|
||||
return n.name === "TagName" && n.from <= from && to <= n.to ? n : null;
|
||||
}
|
||||
|
||||
/** The matching tag's name of the same element, or null without one. */
|
||||
function counterpartName(name: SyntaxNode): SyntaxNode | null {
|
||||
const tag = name.parent;
|
||||
const element = tag?.parent;
|
||||
if (!tag || !element) return null;
|
||||
if (element.name === "JSXElement") {
|
||||
const other = element.getChild(tag.name === "JSXOpenTag" ? "JSXCloseTag" : "JSXOpenTag");
|
||||
for (let c = other?.firstChild; c; c = c.nextSibling) if (JSX_NAMES.has(c.name)) return c;
|
||||
return null;
|
||||
}
|
||||
if (element.name !== "Element") return null;
|
||||
if (!tag || element?.name !== "Element") return null;
|
||||
const other = element.getChild(
|
||||
/^Open/.test(tag.name) ? tag.name.replace("Open", "Close") : tag.name.replace("Close", "Open"),
|
||||
);
|
||||
@@ -57,10 +37,10 @@ function counterpartName(name: SyntaxNode): SyntaxNode | null {
|
||||
}
|
||||
|
||||
/** Insertions at a name's edge must extend the name; structural characters end it. */
|
||||
const NOT_NAME_CHARS = /[\s/>"'<={}]/;
|
||||
const NOT_NAME_CHARS = /[\s/>"'<=]/;
|
||||
|
||||
/**
|
||||
* Editing the name of an opening (or closing) HTML or JSX tag renames its matching
|
||||
* Editing the name of an opening (or closing) HTML tag renames its matching
|
||||
* tag, from the syntax tree — no language server. Installed while Smart Keys ›
|
||||
* Simultaneous `<tag></tag>` editing is on (the default).
|
||||
*/
|
||||
|
||||
@@ -518,20 +518,12 @@ export const GUTTER_ICON_GROUPS = [
|
||||
] as const;
|
||||
|
||||
/**
|
||||
* Languages whose outer parser is `@lezer/html`, plus JSX / TSX, where
|
||||
* simultaneous `<tag></tag>` editing works from the syntax tree. Angular
|
||||
* templates carry the `html` backend id (the Angular mode is picked per
|
||||
* project), `erb` is a token-based mode without a syntax tree and stays out.
|
||||
* Languages whose outer parser is `@lezer/html`, where simultaneous
|
||||
* `<tag></tag>` editing works from the syntax tree. Angular templates carry
|
||||
* the `html` backend id (the Angular mode is picked per project), `erb` is a
|
||||
* token-based mode without a syntax tree and stays out.
|
||||
*/
|
||||
const LINKED_TAG_LANGUAGES = new Set([
|
||||
"html",
|
||||
"vue",
|
||||
"jsp",
|
||||
"django-html",
|
||||
"astro",
|
||||
"typescriptreact",
|
||||
"javascriptreact",
|
||||
]);
|
||||
const LINKED_TAG_LANGUAGES = new Set(["html", "vue", "jsp", "django-html", "astro"]);
|
||||
|
||||
export interface PrefsOptions {
|
||||
prefs: EditorExtras;
|
||||
@@ -660,8 +652,8 @@ export function prefsExtension(o: PrefsOptions): Extension {
|
||||
if (k.tabOutOfPair) out.push(tabOut);
|
||||
// Simultaneous `<tag></tag>` editing, from the syntax tree: every mode whose outer
|
||||
// parser is `@lezer/html` — plain HTML plus the HTML-based modes (Vue SFCs, Angular
|
||||
// templates, JSP, Django and Astro; Angular templates carry the `html` backend id),
|
||||
// and JSX / TSX. ERB is token-based (no syntax tree), so it stays out.
|
||||
// templates, JSP, Django and Astro; Angular templates carry the `html` backend id).
|
||||
// ERB is token-based (no syntax tree), so it stays out.
|
||||
if (!o.readOnly && k.simultaneousTagEditing && LINKED_TAG_LANGUAGES.has(o.language ?? "")) out.push(linkedTags);
|
||||
if (o.commentStyle) out.push(lineCommentStyle.of(o.commentStyle));
|
||||
|
||||
|
||||
@@ -571,10 +571,7 @@ describe("DocumentManager + slots", () => {
|
||||
if (id === a.doc) throw new Error("disk full");
|
||||
await save(id);
|
||||
});
|
||||
const logged = vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
await expect(manager.saveAll("explicit")).rejects.toThrow("disk full");
|
||||
expect(logged).toHaveBeenCalledWith("saving /p/a.txt failed", expect.objectContaining({ message: "disk full" }));
|
||||
logged.mockRestore();
|
||||
expect(backend.files.get("/p/a.txt")).toBe("a\n");
|
||||
expect(backend.files.get("/p/b.txt")).toBe("changed b\n");
|
||||
expect(a.getMeta().dirty).toBe(true);
|
||||
|
||||
@@ -927,7 +927,7 @@ export class DocumentManager {
|
||||
try {
|
||||
await model.save("auto");
|
||||
} catch (e) {
|
||||
logError(`autosave of ${model.path} failed`, e);
|
||||
console.warn(`autosave of ${model.path} failed`, e);
|
||||
}
|
||||
}
|
||||
// As in IDEA, a file whose changes are not saved (autosave off, or a failed save) stays
|
||||
@@ -985,8 +985,6 @@ export class DocumentManager {
|
||||
.filter((m) => !(skipUntitled && isUntitledUri(m.path)))
|
||||
.map((m) =>
|
||||
m.save(reason).catch((e) => {
|
||||
// The notification shows the message only; the log keeps the stack for reports.
|
||||
logError(`saving ${m.path} failed`, e);
|
||||
errors.push(e);
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -1,14 +1,9 @@
|
||||
import { afterEach, beforeEach, expect, it, vi } from "vitest";
|
||||
import { redo, redoDepth, undo, undoDepth, history } from "@codemirror/commands";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { _provideOpenEditorPaths, workspaceEditHistory } from "@/editor/api";
|
||||
import { workspaceEditHistory } from "@/editor/api";
|
||||
import { installWorkspaceEditUndo } from "@/features/code-insight/workspaceUndo";
|
||||
import {
|
||||
provideEditorService,
|
||||
provideNotificationService,
|
||||
type EditorService,
|
||||
type NotificationService,
|
||||
} from "@/workbench/contributions";
|
||||
import { provideNotificationService, type NotificationService } from "@/workbench/contributions";
|
||||
import { emitLocalIdeEvent } from "@/platform/ipc";
|
||||
import { createMemoryBackend, type MemoryBackend } from "../backend";
|
||||
import { _resetLanguages } from "../cm/languages";
|
||||
@@ -66,7 +61,6 @@ async function rename() {
|
||||
type: "workspaceEditApplied",
|
||||
id: 9,
|
||||
paths: ["/p/A.java", "/p/B.java", "/p/closed.java"],
|
||||
moves: [],
|
||||
byAgent: false,
|
||||
});
|
||||
}
|
||||
@@ -194,13 +188,7 @@ it("rebuilds multiple redo markers in order when a closed file opens", async ()
|
||||
const a = await open("/p/A.java");
|
||||
await rename();
|
||||
await replace("alt");
|
||||
emitLocalIdeEvent({
|
||||
type: "workspaceEditApplied",
|
||||
id: 10,
|
||||
paths: ["/p/A.java", "/p/B.java"],
|
||||
moves: [],
|
||||
byAgent: true,
|
||||
});
|
||||
emitLocalIdeEvent({ type: "workspaceEditApplied", id: 10, paths: ["/p/A.java", "/p/B.java"], byAgent: true });
|
||||
commands.undoWorkspaceEdit.mockImplementation(async (id: number) => {
|
||||
await replace(id === 10 ? "new" : "old");
|
||||
return { status: "ok", data: null };
|
||||
@@ -269,56 +257,3 @@ it("keeps refactoring markers current while a secondary view is unmounted", asyn
|
||||
expect(commands.undoWorkspaceEdit).toHaveBeenCalledOnce();
|
||||
att.release();
|
||||
});
|
||||
|
||||
it("editors on a file the edit renamed reopen at its new path, through Undo and Redo", async () => {
|
||||
const live = () => slots.filter((s) => !closed.has(s));
|
||||
const closed = new Set<EditorSlot>();
|
||||
const openFile = vi.fn(async (path: string) => {
|
||||
if (!live().some((s) => s.model.path === path)) await open(path);
|
||||
});
|
||||
const closePath = vi.fn(async (path: string) => {
|
||||
for (const s of live())
|
||||
if (s.model.path === path) {
|
||||
closed.add(s);
|
||||
s.dispose();
|
||||
}
|
||||
return true;
|
||||
});
|
||||
provideEditorService({
|
||||
openFile,
|
||||
closePath,
|
||||
activePath: () => live().at(-1)?.model.path ?? null,
|
||||
saveAll: vi.fn(),
|
||||
} as unknown as EditorService);
|
||||
_provideOpenEditorPaths(() => live().map((s) => s.model.path));
|
||||
backend.files.set("/p/Renamed.java", "old");
|
||||
const moved = async (from: string, to: string, run: () => Promise<unknown>) => {
|
||||
openFile.mockClear();
|
||||
await run();
|
||||
await vi.waitFor(() => expect(openFile).toHaveBeenCalledExactlyOnceWith(to, { focus: false }));
|
||||
expect(closePath).toHaveBeenCalledWith(from);
|
||||
expect(live().map((s) => s.model.path)).toEqual(["/p/B.java", to]);
|
||||
};
|
||||
try {
|
||||
await open("/p/B.java");
|
||||
await open("/p/A.java");
|
||||
await moved("/p/A.java", "/p/Renamed.java", async () => {
|
||||
await replace("new");
|
||||
emitLocalIdeEvent({
|
||||
type: "workspaceEditApplied",
|
||||
id: 11,
|
||||
paths: ["/p/A.java", "/p/Renamed.java", "/p/B.java"],
|
||||
moves: [{ from: "/p/A.java", to: "/p/Renamed.java" }],
|
||||
byAgent: false,
|
||||
});
|
||||
});
|
||||
// Reopened editors take part in the refactoring's history like the ones they replace.
|
||||
await moved("/p/Renamed.java", "/p/A.java", () => workspaceEditHistory(11));
|
||||
await moved("/p/A.java", "/p/Renamed.java", () => workspaceEditHistory(11, true));
|
||||
await moved("/p/Renamed.java", "/p/A.java", () => workspaceEditHistory(11));
|
||||
expect(notify).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
provideEditorService(undefined as unknown as EditorService);
|
||||
_provideOpenEditorPaths(() => []);
|
||||
}
|
||||
});
|
||||
@@ -3,8 +3,7 @@ import { invertedEffects, isolateHistory, redo, undo } from "@codemirror/command
|
||||
import { EditorState, Prec, StateEffect, type Transaction, type Extension } from "@codemirror/state";
|
||||
import { EditorView, keymap } from "@codemirror/view";
|
||||
import { _emitWorkspaceEditHistory, _provideWorkspaceHistory, isExternalChange } from "@/editor/api";
|
||||
import { editorsFollowAppliedMoves, reversedMoves, withEditorsFollowing } from "@/editor/fileMoves";
|
||||
import { call, commands, onIdeEvent, type FileMove } from "@/platform/ipc";
|
||||
import { call, commands, onIdeEvent } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
|
||||
interface Marker {
|
||||
@@ -21,7 +20,7 @@ export interface WorkspaceHistoryTarget {
|
||||
|
||||
export class WorkspaceHistory {
|
||||
private targets = new Set<WorkspaceHistoryTarget>();
|
||||
private records = new Map<number, { paths: string[]; moves: FileMove[]; undone: boolean }>();
|
||||
private records = new Map<number, { paths: string[]; undone: boolean }>();
|
||||
private project = useProject.getState().project;
|
||||
private busy = false;
|
||||
private moving = false;
|
||||
@@ -32,7 +31,7 @@ export class WorkspaceHistory {
|
||||
) {}
|
||||
|
||||
start(): () => void {
|
||||
const stop = onIdeEvent("workspaceEditApplied", ({ id, paths, moves }) => {
|
||||
const stop = onIdeEvent("workspaceEditApplied", ({ id, paths }) => {
|
||||
if (this.project !== useProject.getState().project) {
|
||||
this.records.clear();
|
||||
this.project = useProject.getState().project;
|
||||
@@ -44,11 +43,9 @@ export class WorkspaceHistory {
|
||||
record.paths.some((path) => this.affects(paths, path) || paths.some((root) => root.startsWith(`${path}/`)))
|
||||
)
|
||||
this.records.delete(key);
|
||||
this.records.set(id, { paths, moves, undone: false });
|
||||
this.records.set(id, { paths, undone: false });
|
||||
while (this.records.size > 20) this.records.delete(this.records.keys().next().value!);
|
||||
for (const target of this.targets) if (this.affects(paths, target.path)) this.mark(target, id);
|
||||
// Now, before the file watcher reports the old paths gone and their tabs close.
|
||||
void editorsFollowAppliedMoves(moves);
|
||||
});
|
||||
const unprovide = _provideWorkspaceHistory((id, redo) => this.run(id, redo));
|
||||
return () => {
|
||||
@@ -157,21 +154,14 @@ export class WorkspaceHistory {
|
||||
for (const target of targets)
|
||||
if (!this.step(target, id, forward))
|
||||
throw new Error("Undo newer editor changes before undoing this refactoring");
|
||||
await withEditorsFollowing(
|
||||
async () => {
|
||||
await call(forward ? commands.redoWorkspaceEdit(id) : commands.undoWorkspaceEdit(id));
|
||||
await this.synced();
|
||||
for (const target of targets) {
|
||||
if (!this.targets.has(target)) continue;
|
||||
const tr = this.step(target, id, forward);
|
||||
if (tr) target.dispatch(tr);
|
||||
}
|
||||
// Editors reopened at moved paths build their history from the record: settle it first.
|
||||
record.undone = !forward;
|
||||
},
|
||||
() => (forward ? record.moves : reversedMoves(record.moves)),
|
||||
{ save: false },
|
||||
);
|
||||
await call(forward ? commands.redoWorkspaceEdit(id) : commands.undoWorkspaceEdit(id));
|
||||
await this.synced();
|
||||
for (const target of targets) {
|
||||
if (!this.targets.has(target)) continue;
|
||||
const tr = this.step(target, id, forward);
|
||||
if (tr) target.dispatch(tr);
|
||||
}
|
||||
record.undone = !forward;
|
||||
_emitWorkspaceEditHistory({ id, undone: record.undone });
|
||||
} catch (error) {
|
||||
// A refused backend restore must leave the initiating editor's history intact.
|
||||
|
||||
@@ -1,59 +0,0 @@
|
||||
import { afterEach, expect, it } from "vitest";
|
||||
import { onIdeEvent } from "@/platform/ipc";
|
||||
import { provideEditorService, type EditorService } from "@/workbench/contributions";
|
||||
import { createMemoryBackend } from "./core/backend";
|
||||
import { EditorController, useTabs } from "./core/controller";
|
||||
import { initialTabsState } from "./core/model/tabs";
|
||||
import { editorsFollowAppliedMoves } from "./fileMoves";
|
||||
|
||||
let ctrl: EditorController | null = null;
|
||||
|
||||
afterEach(() => {
|
||||
ctrl?.stop();
|
||||
ctrl = null;
|
||||
useTabs.setState(initialTabsState(), true);
|
||||
});
|
||||
|
||||
function setup(files: Record<string, string>) {
|
||||
const backend = createMemoryBackend(files);
|
||||
backend.onFsChanged = (h) => onIdeEvent("fsChanged", h);
|
||||
const controller = new EditorController(backend);
|
||||
controller.start();
|
||||
ctrl = controller;
|
||||
provideEditorService({
|
||||
openFile: (path, o) => controller.openFile(path, o),
|
||||
activePath: () => controller.activePath(),
|
||||
closePath: (path) => controller.closePath(path),
|
||||
saveAll: async () => {},
|
||||
} as Partial<EditorService> as EditorService);
|
||||
return { controller, backend };
|
||||
}
|
||||
|
||||
const tabPaths = () =>
|
||||
Object.values(useTabs.getState().panes).flatMap((pane) => pane.tabs.map((tab) => tab.input.path));
|
||||
|
||||
it("a renamed active file stays the active editor", async () => {
|
||||
const { controller, backend } = setup({ "/p/A.java": "class A {}", "/p/B.java": "class B {}" });
|
||||
await controller.openFile("/p/B.java", { focus: false });
|
||||
await controller.openFile("/p/A.java", { focus: false });
|
||||
backend.files.set("/p/Renamed.java", backend.files.get("/p/A.java")!);
|
||||
backend.files.delete("/p/A.java");
|
||||
|
||||
await editorsFollowAppliedMoves([{ from: "/p/A.java", to: "/p/Renamed.java" }]);
|
||||
|
||||
expect(tabPaths()).toEqual(["/p/B.java", "/p/Renamed.java"]);
|
||||
expect(controller.activePath()).toBe("/p/Renamed.java");
|
||||
});
|
||||
|
||||
it("a renamed background file leaves the active editor in place", async () => {
|
||||
const { controller, backend } = setup({ "/p/A.java": "class A {}", "/p/B.java": "class B {}" });
|
||||
await controller.openFile("/p/A.java", { focus: false });
|
||||
await controller.openFile("/p/B.java", { focus: false });
|
||||
backend.files.set("/p/Renamed.java", backend.files.get("/p/A.java")!);
|
||||
backend.files.delete("/p/A.java");
|
||||
|
||||
await editorsFollowAppliedMoves([{ from: "/p/A.java", to: "/p/Renamed.java" }]);
|
||||
|
||||
expect(tabPaths().sort()).toEqual(["/p/B.java", "/p/Renamed.java"]);
|
||||
expect(controller.activePath()).toBe("/p/B.java");
|
||||
});
|
||||
@@ -1,81 +0,0 @@
|
||||
/** IDEA keeps editors on files that a refactoring moves or renames: they reopen at the new paths. */
|
||||
import type { FileMove } from "@/bindings";
|
||||
import { openEditorPaths } from "@/editor/api";
|
||||
import { notifyFilesMoved, trackFileMove } from "@/platform/fileOps";
|
||||
import { emitLocalIdeEvent } from "@/platform/ipc";
|
||||
import { isSameOrInside } from "@/platform/paths";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { maybeEditorService } from "@/workbench/contributions";
|
||||
|
||||
export async function saveAllQuietly(editor: { saveAll(): Promise<void> }) {
|
||||
try {
|
||||
await editor.saveAll();
|
||||
} catch {
|
||||
/* unsaved files are reported by the editor */
|
||||
}
|
||||
}
|
||||
|
||||
/** `path` after `moves`. */
|
||||
export function movedPath(path: string, moves: readonly FileMove[]): string {
|
||||
let p = path;
|
||||
for (const m of moves) if (isSameOrInside(p, m.from)) p = m.to + p.slice(m.from.length);
|
||||
return p;
|
||||
}
|
||||
|
||||
/** Moves in the opposite direction, last first: what Undo of `moves` does. */
|
||||
export function reversedMoves(moves: readonly FileMove[]): FileMove[] {
|
||||
return [...moves].reverse().map((m) => ({ from: m.to, to: m.from }));
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs `run`, which moves the files `done` names, with the editors following: unsaved changes
|
||||
* are saved first (unless `save` is false), tabs reopen at the new paths.
|
||||
*/
|
||||
export async function withEditorsFollowing<T>(
|
||||
run: () => Promise<T>,
|
||||
done: (r: T) => readonly FileMove[],
|
||||
{ save = true }: { save?: boolean } = {},
|
||||
): Promise<T> {
|
||||
const projectRoot = () => useProject.getState().project?.root ?? null;
|
||||
const root = projectRoot();
|
||||
const editor = maybeEditorService();
|
||||
const openBefore = editor ? openEditorPaths() : [];
|
||||
if (editor && save) await saveAllQuietly(editor);
|
||||
const active = editor?.activePath() ?? null;
|
||||
const { result, applied } = await trackFileMove(root, async () => {
|
||||
const result = await run();
|
||||
const applied = done(result);
|
||||
if (root === projectRoot()) await notifyFilesMoved(applied);
|
||||
return { result, applied };
|
||||
});
|
||||
if (root !== projectRoot()) return result;
|
||||
const open = openBefore.filter((p) => applied.some((m) => isSameOrInside(p, m.from)));
|
||||
if (applied.length)
|
||||
emitLocalIdeEvent({
|
||||
type: "fsChanged",
|
||||
created: applied.map((m) => m.to),
|
||||
modified: [],
|
||||
removed: applied.map((m) => m.from),
|
||||
});
|
||||
if (!editor || !open.length) return result;
|
||||
// The editor closes tabs of removed files in a queue; an open that starts before an
|
||||
// active tab's close counts as superseded and stays in the background.
|
||||
for (const p of open) await editor.closePath?.(p).catch(() => false);
|
||||
const ordered = active && open.includes(active) ? [...open.filter((p) => p !== active), active] : open;
|
||||
for (const p of ordered) await editor.openFile(movedPath(p, applied), { focus: false }).catch(() => {});
|
||||
if (active && !open.includes(active)) await editor.openFile(active, { focus: false }).catch(() => {});
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Editors follow `moves` that a workspace edit already made (a server's rename, Move, a quick
|
||||
* fix): called when the backend reports the edit, before the file watcher closes their tabs.
|
||||
*/
|
||||
export function editorsFollowAppliedMoves(moves: readonly FileMove[]): Promise<void> {
|
||||
if (!moves.length) return Promise.resolve();
|
||||
return withEditorsFollowing(
|
||||
() => Promise.resolve(),
|
||||
() => moves,
|
||||
{ save: false },
|
||||
);
|
||||
}
|
||||
@@ -6,14 +6,6 @@
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
.compactListPopup {
|
||||
min-width: 0;
|
||||
}
|
||||
.listDivider {
|
||||
width: 100%;
|
||||
height: 1px;
|
||||
background: var(--border-popup);
|
||||
}
|
||||
.listHeader {
|
||||
height: 28px;
|
||||
flex: none;
|
||||
@@ -124,7 +116,7 @@
|
||||
.listBody {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: var(--h-list-row);
|
||||
min-height: 24px;
|
||||
padding: 0 0 4px;
|
||||
box-sizing: content-box;
|
||||
}
|
||||
@@ -382,79 +374,52 @@
|
||||
text-decoration: underline;
|
||||
}
|
||||
.defPopup {
|
||||
width: 600px;
|
||||
height: 400px;
|
||||
width: min(640px, 90vw);
|
||||
max-height: 460px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
.defHeader {
|
||||
min-height: var(--h-field);
|
||||
height: 28px;
|
||||
flex: none;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
padding: var(--space-1) var(--space-2);
|
||||
gap: var(--space-1-5);
|
||||
padding: 0 6px 0 12px;
|
||||
background: var(--bg-popup-inline, var(--bg-elev));
|
||||
border-bottom: 1px solid var(--border-popup);
|
||||
font-size: var(--fs-ui);
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
.defTarget {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
min-width: 0;
|
||||
.defFile {
|
||||
color: var(--fg-emphasis);
|
||||
}
|
||||
.defTarget > svg {
|
||||
flex: none;
|
||||
}
|
||||
.defName,
|
||||
.defPath {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.defPath {
|
||||
max-width: 45%;
|
||||
min-width: 0;
|
||||
color: var(--fg-subtle);
|
||||
}
|
||||
.defFrame {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
outline: none;
|
||||
}
|
||||
.defActions {
|
||||
margin-inline-start: auto;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex: none;
|
||||
gap: var(--space-0-5);
|
||||
}
|
||||
.defCount {
|
||||
flex: none;
|
||||
font-size: var(--fs-small);
|
||||
font-variant-numeric: tabular-nums;
|
||||
color: var(--fg-subtle);
|
||||
}
|
||||
.defBody {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow: auto;
|
||||
padding: var(--space-3) var(--space-2);
|
||||
color: var(--fg-emphasis);
|
||||
padding: 4px 12px;
|
||||
}
|
||||
.defCode {
|
||||
margin: 0;
|
||||
font: inherit;
|
||||
.defBody pre {
|
||||
white-space: pre;
|
||||
}
|
||||
.defCode code {
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
.previewDialog [data-dialog-body] {
|
||||
display: flex;
|
||||
|
||||
@@ -340,7 +340,6 @@ describe("quick definition popup", () => {
|
||||
],
|
||||
index: 0,
|
||||
themeClasses: "",
|
||||
codeStyle: { fontSize: "16px", lineHeight: "24px" },
|
||||
});
|
||||
render(<LspPopups />);
|
||||
const frame = () => screen.getByRole("dialog", { name: "Definition" }).firstElementChild as HTMLElement;
|
||||
|
||||
+36
-114
@@ -16,7 +16,6 @@ import {
|
||||
Spinner,
|
||||
SymbolBadge,
|
||||
fileIconName,
|
||||
firstSelectable,
|
||||
fuzzyMatch,
|
||||
selectableText,
|
||||
T,
|
||||
@@ -27,7 +26,6 @@ import {
|
||||
closePopup,
|
||||
updatePopup,
|
||||
useLspPopup,
|
||||
type DefinitionTarget,
|
||||
type ListPopupItem,
|
||||
type ListPreview,
|
||||
type LspPopup,
|
||||
@@ -41,7 +39,6 @@ import styles from "./Popups.module.css";
|
||||
import fieldsetStyles from "@/ui/DialogFieldset.module.css";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { useRowHeight } from "@/ui/density";
|
||||
|
||||
export function BulbIcon({ fix }: { fix?: boolean }) {
|
||||
return <Icon name={fix ? "bulb-fix" : "bulb"} size={16} className={styles.bulb} />;
|
||||
@@ -84,44 +81,19 @@ function ListPreviewPanel({
|
||||
const LIST_PREVIEW_WIDTH = 420;
|
||||
const MIN_SIDE_BY_SIDE_WIDTH = 660;
|
||||
|
||||
type ListPopupRow =
|
||||
| { kind: "action"; item: ListPopupItem; match: number[] | null }
|
||||
| { kind: "section"; key: string; label?: string };
|
||||
|
||||
const isListSection = (row: ListPopupRow) => row.kind === "section";
|
||||
const dividerHeight = (row: ListPopupRow) => (row.kind === "section" && !row.label ? 9 : undefined);
|
||||
|
||||
function listPopupRows(items: ListPopupItem[], query: string): ListPopupRow[] {
|
||||
const rows: ListPopupRow[] = [];
|
||||
let previous: string | undefined;
|
||||
for (const item of items) {
|
||||
const match = query ? fuzzyMatch(item.label, query) : null;
|
||||
if (query && match === null) continue;
|
||||
const { section } = item;
|
||||
if (section?.id !== previous && (section?.label || rows.length)) {
|
||||
rows.push({ kind: "section", key: `section:${rows.length}`, label: section?.label });
|
||||
}
|
||||
rows.push({ kind: "action", item, match });
|
||||
previous = section?.id;
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
function ListPopup({ popup }: { popup: Extract<LspPopup, { kind: "list" }> }) {
|
||||
const [query, setQuery] = useState("");
|
||||
const rows = useMemo(() => listPopupRows(popup.items, query), [popup.items, query]);
|
||||
const firstEnabled = rows.findIndex((row) => row.kind === "action" && !row.item.disabled);
|
||||
const filtered = useMemo(() => {
|
||||
if (!query) return popup.items.map((item) => ({ item, match: null as number[] | null }));
|
||||
return popup.items.map((item) => ({ item, match: fuzzyMatch(item.label, query) })).filter((r) => r.match !== null);
|
||||
}, [popup.items, query]);
|
||||
const firstEnabled = Math.max(
|
||||
0,
|
||||
filtered.findIndex((r) => !r.item.disabled),
|
||||
);
|
||||
const [active, setActive] = useState(firstEnabled);
|
||||
const clamped = Math.min(active, rows.length - 1);
|
||||
const activeIndex =
|
||||
rows[clamped]?.kind === "action"
|
||||
? clamped
|
||||
: firstEnabled >= 0
|
||||
? firstEnabled
|
||||
: firstSelectable(rows, isListSection);
|
||||
const activeRow = rows[activeIndex];
|
||||
const activeItem = activeRow?.kind === "action" ? activeRow.item : undefined;
|
||||
const showIcons = !popup.compact || popup.items.some((item) => item.icon || item.symbol);
|
||||
const activeIndex = Math.min(active, Math.max(0, filtered.length - 1));
|
||||
const activeItem = filtered[activeIndex]?.item;
|
||||
|
||||
// Choosers highlight what the selected row would act on.
|
||||
useEffect(() => {
|
||||
@@ -183,20 +155,16 @@ function ListPopup({ popup }: { popup: Extract<LspPopup, { kind: "list" }> }) {
|
||||
if (item) activate(item);
|
||||
} else if (e.key === "Backspace" && query) {
|
||||
setQuery(query.slice(0, -1));
|
||||
setActive(-1);
|
||||
setActive(0);
|
||||
e.preventDefault();
|
||||
} else if (e.key.length === 1 && !(e.key === " " && !query)) {
|
||||
setQuery(query + e.key);
|
||||
setActive(-1);
|
||||
setActive(0);
|
||||
e.preventDefault();
|
||||
}
|
||||
};
|
||||
|
||||
const rowHeight = useRowHeight();
|
||||
const height = Math.min(
|
||||
12 * rowHeight,
|
||||
rows.reduce((sum, row) => sum + (dividerHeight(row) ?? rowHeight), 0) || rowHeight,
|
||||
);
|
||||
const height = Math.min(12, Math.max(1, filtered.length)) * 24;
|
||||
// Rows are virtualized (absolutely positioned), so size the popup from the content.
|
||||
const width = useMemo(() => {
|
||||
const chars = Math.max(
|
||||
@@ -205,9 +173,8 @@ function ListPopup({ popup }: { popup: Extract<LspPopup, { kind: "list" }> }) {
|
||||
(i) => i.label.length + (i.preview?.length ?? 0) + (i.detail?.length ?? 0) + (i.shortcut?.length ?? 0),
|
||||
),
|
||||
);
|
||||
const padding = popup.compact ? 44 + (showIcons ? 20 : 0) : 90;
|
||||
return Math.min(720, Math.max(popup.compact ? 272 : 320, chars * 7 + padding + (popup.numbered ? 16 : 0)));
|
||||
}, [popup, showIcons]);
|
||||
return Math.min(720, Math.max(320, chars * 7 + 90 + (popup.numbered ? 16 : 0)));
|
||||
}, [popup]);
|
||||
const shownPreview = popup.preview
|
||||
? preview && preview.id === activeItem?.id
|
||||
? preview.data
|
||||
@@ -248,7 +215,6 @@ function ListPopup({ popup }: { popup: Extract<LspPopup, { kind: "list" }> }) {
|
||||
aria-label={popup.title}
|
||||
className={clsx(
|
||||
styles.listPopup,
|
||||
popup.compact && styles.compactListPopup,
|
||||
hasPreview && styles.withPreview,
|
||||
previewBelow && styles.previewBelow,
|
||||
previewLeft && styles.previewLeft,
|
||||
@@ -275,19 +241,14 @@ function ListPopup({ popup }: { popup: Extract<LspPopup, { kind: "list" }> }) {
|
||||
</div>
|
||||
<div ref={bodyRef} onKeyDown={onKeyDown} className={styles.listBody} style={{ height }}>
|
||||
<List
|
||||
items={rows}
|
||||
getKey={(row) => (row.kind === "section" ? row.key : row.item.id)}
|
||||
isSection={isListSection}
|
||||
sectionHeightOf={dividerHeight}
|
||||
renderSection={(row) =>
|
||||
row.kind === "section" && row.label ? <T>{row.label}</T> : <span className={styles.listDivider} />
|
||||
}
|
||||
items={filtered}
|
||||
getKey={(r) => r.item.id}
|
||||
activeIndex={activeIndex}
|
||||
onActiveChange={setActive}
|
||||
hoverSelects
|
||||
autoFocus
|
||||
aria-label={popup.title}
|
||||
onActivate={(row) => row.kind === "action" && activate(row.item)}
|
||||
onActivate={(r) => activate(r.item)}
|
||||
empty={
|
||||
popup.busy ? (
|
||||
<span className={styles.empty}>
|
||||
@@ -299,9 +260,7 @@ function ListPopup({ popup }: { popup: Extract<LspPopup, { kind: "list" }> }) {
|
||||
</span>
|
||||
)
|
||||
}
|
||||
renderItem={(row) => {
|
||||
if (row.kind !== "action") return null;
|
||||
const { item, match } = row;
|
||||
renderItem={({ item, match }) => {
|
||||
const n = popup.numbered && !query ? indexOf(item) + 1 : 0;
|
||||
return (
|
||||
<div
|
||||
@@ -312,7 +271,7 @@ function ListPopup({ popup }: { popup: Extract<LspPopup, { kind: "list" }> }) {
|
||||
data-line={item.location?.line}
|
||||
>
|
||||
{popup.numbered && <span className={styles.mnemonic}>{n > 0 && n <= 9 ? n : ""}</span>}
|
||||
{showIcons && <ItemIcon item={item} />}
|
||||
<ItemIcon item={item} />
|
||||
<HighlightedText className={styles.label} text={item.label} indices={match} tone="accent" />
|
||||
{item.preview && (
|
||||
<span className={styles.preview} title={item.preview}>
|
||||
@@ -545,8 +504,6 @@ function DefinitionPopup({ popup }: { popup: Extract<LspPopup, { kind: "definiti
|
||||
const target = popup.targets[popup.index]!;
|
||||
const { location } = target;
|
||||
const many = popup.targets.length > 1;
|
||||
const source = (loc: DefinitionTarget["location"]) => `${relativePath(root, loc.path)}:${loc.range.start.line + 1}`;
|
||||
const targetIcon = (path: string) => fileIconName(basename(path), path);
|
||||
const open = () => {
|
||||
closePopup();
|
||||
void editorService().openFile(location.path, {
|
||||
@@ -567,76 +524,41 @@ function DefinitionPopup({ popup }: { popup: Extract<LspPopup, { kind: "definiti
|
||||
}
|
||||
};
|
||||
return (
|
||||
<Popup
|
||||
open
|
||||
anchor={popup.anchor}
|
||||
onClose={closePopup}
|
||||
aria-label={tx("Definition")}
|
||||
className={styles.defPopup}
|
||||
resizable="both"
|
||||
>
|
||||
<Popup open anchor={popup.anchor} onClose={closePopup} aria-label="Definition" className={styles.defPopup}>
|
||||
<div className={styles.defFrame} tabIndex={-1} data-autofocus onKeyDown={onKeyDown}>
|
||||
<div className={styles.defHeader}>
|
||||
<Icon name={fileIconName(basename(location.path), location.path)} size={14} />
|
||||
{many ? (
|
||||
<Select
|
||||
variant="ghost"
|
||||
className={styles.defTarget}
|
||||
aria-label="Definition"
|
||||
value={String(popup.index)}
|
||||
options={popup.targets.map((t, i) => ({
|
||||
value: String(i),
|
||||
label: t.name,
|
||||
verbatim: true,
|
||||
icon: targetIcon(t.location.path),
|
||||
detail: source(t.location),
|
||||
detail: `${basename(t.location.path)}:${t.location.range.start.line + 1}`,
|
||||
}))}
|
||||
onChange={(v) => select(Number(v))}
|
||||
/>
|
||||
) : (
|
||||
<div className={styles.defTarget}>
|
||||
<Icon name={targetIcon(location.path)} size={14} />
|
||||
<span className={styles.defName} title={target.name}>
|
||||
{target.name}
|
||||
</span>
|
||||
</div>
|
||||
<span className={styles.defFile}>{basename(location.path)}</span>
|
||||
)}
|
||||
<span className={styles.defPath} title={source(location)}>
|
||||
{source(location)}
|
||||
<span className={styles.defPath}>
|
||||
{relativePath(root, location.path)}:{location.range.start.line + 1}
|
||||
</span>
|
||||
<div className={styles.defActions}>
|
||||
{many && (
|
||||
<>
|
||||
<IconButton
|
||||
icon="chevron-left"
|
||||
size="small"
|
||||
title="Previous Definition"
|
||||
onClick={() => select(popup.index - 1)}
|
||||
/>
|
||||
<span className={styles.defCount} aria-live="polite">
|
||||
{popup.index + 1}/{popup.targets.length}
|
||||
</span>
|
||||
<IconButton
|
||||
icon="chevron-right"
|
||||
size="small"
|
||||
title="Next Definition"
|
||||
onClick={() => select(popup.index + 1)}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
<IconButton icon="edit" size="small" title="Edit Source" shortcut="F4" onClick={open} />
|
||||
</div>
|
||||
<span className={styles.spacer} />
|
||||
{many && (
|
||||
<span className={styles.defCount}>
|
||||
{popup.index + 1}/{popup.targets.length}
|
||||
</span>
|
||||
)}
|
||||
<IconButton icon="edit" size="small" title="Edit Source" shortcut="F4" onClick={open} />
|
||||
</div>
|
||||
<div
|
||||
className={clsx(popup.themeClasses, styles.defBody)}
|
||||
style={popup.codeStyle}
|
||||
tabIndex={0}
|
||||
role="region"
|
||||
aria-label={tx("Preview")}
|
||||
>
|
||||
<div className={clsx(popup.themeClasses, styles.docScope)}>
|
||||
<DomContent
|
||||
key={popup.index}
|
||||
className={selectableText}
|
||||
build={() => renderCode(target.text, target.language, styles.defCode)}
|
||||
className={clsx(styles.defBody, selectableText)}
|
||||
build={() => renderCode(target.text, target.language, "cm-lsp-code")}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -323,22 +323,6 @@ describe("applying completions", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("puts the caret inside the parentheses of a server-inserted call that takes arguments", async () => {
|
||||
setInvokeRoute(() => Promise.resolve(null));
|
||||
try {
|
||||
const { view, req } = setup("x.rea|\n", "", [completionExtension()]);
|
||||
view.dispatch({ effects: StateEffect.appendConfig.of(lspDoc.of({ doc: 1 } as EditorDocContext)) });
|
||||
const command = { title: "Apply Completion", command: "jetbrains.kotlin.completion.apply", arguments: ["1"] };
|
||||
const kotlin = item({ label: "read", kind: "method", labelDetail: "(name: String)", insertText: "", command });
|
||||
applyLspCompletion(view, makeCompletion(kotlin, req), 5, 5, "insert");
|
||||
view.dispatch({ changes: { from: 5, insert: "d()" }, annotations: remoteChange.of(true) });
|
||||
expect(view.state.doc.toString()).toBe("x.read()\n");
|
||||
expect(view.state.selection.main.head).toBe(7);
|
||||
} finally {
|
||||
setInvokeRoute(null);
|
||||
}
|
||||
});
|
||||
|
||||
it("completes at every caret whose typed prefix matches the main caret's", () => {
|
||||
const { view, req } = setup("a.cr|\nb.cr\nc.xy", "", [EditorState.allowMultipleSelections.of(true)]);
|
||||
// Carets after both `cr`s (the main one first) and after `xy`.
|
||||
|
||||
@@ -462,8 +462,6 @@ async function applyLateEdits(view: EditorView, c: LspCompletion, insertedAt: nu
|
||||
interface ServerInsert {
|
||||
at: number;
|
||||
others: readonly number[];
|
||||
/** The item is a call that takes arguments: the caret goes inside an inserted `()`. */
|
||||
inside?: boolean;
|
||||
}
|
||||
const awaitServerInsert = StateEffect.define<ServerInsert | null>();
|
||||
const serverInsertAt = StateField.define<ServerInsert | null>({
|
||||
@@ -472,11 +470,7 @@ const serverInsertAt = StateField.define<ServerInsert | null>({
|
||||
for (const e of tr.effects) if (e.is(awaitServerInsert)) return e.value;
|
||||
// The edit landed, or the caret moved on before it did.
|
||||
if (value === null || tr.annotation(remoteChange) || tr.selection) return null;
|
||||
return {
|
||||
at: tr.changes.mapPos(value.at, -1),
|
||||
others: value.others.map((p) => tr.changes.mapPos(p, -1)),
|
||||
inside: value.inside,
|
||||
};
|
||||
return { at: tr.changes.mapPos(value.at, -1), others: value.others.map((p) => tr.changes.mapPos(p, -1)) };
|
||||
},
|
||||
});
|
||||
|
||||
@@ -547,9 +541,7 @@ const caretAfterServerInsert = EditorState.transactionFilter.of((tr) => {
|
||||
if (tr.changes.touchesRange(from, to)) continue;
|
||||
others.push({ from: tr.changes.mapPos(from, 1), to: tr.changes.mapPos(to, -1) });
|
||||
}
|
||||
const inside =
|
||||
pending.inside && /\(\)$/.test(landed.insert) && tr.newDoc.sliceString(mainAfter - 2, mainAfter) === "()";
|
||||
const selection = EditorSelection.cursor(inside ? mainAfter - 1 : mainAfter);
|
||||
const selection = EditorSelection.cursor(mainAfter);
|
||||
if (!others.length) return [tr, { selection, sequential: true }];
|
||||
// Not part of this transaction: a remote one is not sent back to the document model.
|
||||
const changes = others
|
||||
@@ -561,12 +553,6 @@ const caretAfterServerInsert = EditorState.transactionFilter.of((tr) => {
|
||||
/** Client-side commands handled by the editor itself (VS Code ids servers commonly send). */
|
||||
const CLIENT_COMMANDS = new Set(["editor.action.triggerParameterHints", "editor.action.triggerSuggest"]);
|
||||
|
||||
/** A function or method whose signature lists parameters (`(name: String)`), as far as the item tells. */
|
||||
function takesArguments(item: Pick<CompletionItem, "kind" | "labelDetail" | "detail">): boolean {
|
||||
if (item.kind && !CALLABLE.has(item.kind)) return false;
|
||||
return /^\s*\(\s*[^)\s]/.test(item.labelDetail ?? item.detail ?? "");
|
||||
}
|
||||
|
||||
/** kotlin-lsp inserts the item itself (`jetbrains.kotlin.completion.apply`): nothing goes in here. */
|
||||
function serverInserts(item: CompletionItem): boolean {
|
||||
const cmd = item.command?.command;
|
||||
@@ -578,10 +564,7 @@ function runCommand(view: EditorView, item: CompletionItem, others: readonly num
|
||||
if (!command?.command) return;
|
||||
const cmd = command.command;
|
||||
const serverInserted = serverInserts(item);
|
||||
if (serverInserted)
|
||||
view.dispatch({
|
||||
effects: awaitServerInsert.of({ at: view.state.selection.main.head, others, inside: takesArguments(item) }),
|
||||
});
|
||||
if (serverInserted) view.dispatch({ effects: awaitServerInsert.of({ at: view.state.selection.main.head, others }) });
|
||||
if (cmd === "editor.action.triggerParameterHints") setTimeout(() => triggerSignatureHelp(view), 0);
|
||||
else if (cmd === "editor.action.triggerSuggest") setTimeout(() => startCompletion(view), 0);
|
||||
else if (!CLIENT_COMMANDS.has(cmd) && !cmd.startsWith("editor.")) {
|
||||
|
||||
@@ -413,14 +413,12 @@ export async function quickDefinition(view: EditorView, kind: "definition" | "ty
|
||||
showHint(view, "Cannot read the definition's file");
|
||||
return;
|
||||
}
|
||||
const { fontFamily, fontSize, fontWeight, lineHeight, tabSize } = getComputedStyle(view.contentDOM);
|
||||
openPopup({
|
||||
kind: "definition",
|
||||
anchor: caretAnchor(view, pos),
|
||||
targets,
|
||||
index: 0,
|
||||
themeClasses: view.themeClasses,
|
||||
codeStyle: { fontFamily, fontSize, fontWeight, lineHeight, tabSize },
|
||||
});
|
||||
} catch (e) {
|
||||
if (!stale()) reportLspError(view, e, true);
|
||||
|
||||
Loaded 100 of 237 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user