mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-22 19:49:35 -10:00
Compare commits
68
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3d26de001f | ||
|
|
a5c8fe17fd | ||
|
|
0684795334 | ||
|
|
30cbb80f22 | ||
|
|
5cfb0d3311 | ||
|
|
bccf1bd7d6 | ||
|
|
3d79454be8 | ||
|
|
46e4af2b32 | ||
|
|
067edb7d60 | ||
|
|
0a4abf1705 | ||
|
|
d31699c86a | ||
|
|
9467c4ea1b | ||
|
|
7c12c58874 | ||
|
|
9f47ef0991 | ||
|
|
3b614dda7a | ||
|
|
5acd778340 | ||
|
|
7c682a580f | ||
|
|
dc07691279 | ||
|
|
2d04a3d9bc | ||
|
|
8f9b9b1016 | ||
|
|
096964c798 | ||
|
|
f1bfd5db52 | ||
|
|
a17af582f3 | ||
|
|
47f018d8b5 | ||
|
|
94aa62430c | ||
|
|
4242c94bfc | ||
|
|
8864ff595d | ||
|
|
0a08d9f4ce | ||
|
|
7dbfe8852e | ||
|
|
ae97d5f1c2 | ||
|
|
4340a96c59 | ||
|
|
0af7bcc7cf | ||
|
|
4f52f5ebfa | ||
|
|
f284633162 | ||
|
|
0ceda2c385 | ||
|
|
8b3f55dfb4 | ||
|
|
c0e888dd2f | ||
|
|
04bed01942 | ||
|
|
dfafe6c767 | ||
|
|
461c71a50b | ||
|
|
82085a227e | ||
|
|
c3f420374c | ||
|
|
6bf7bc8c2b | ||
|
|
34dfc166db | ||
|
|
64632dc4d7 | ||
|
|
f484fd6802 | ||
|
|
8121dc87f1 | ||
|
|
97f78908a1 | ||
|
|
e7aec17d46 | ||
|
|
cb24f252c5 | ||
|
|
8557b8d21e | ||
|
|
99a8f8feaa | ||
|
|
4b76566af4 | ||
|
|
51bab9a25b | ||
|
|
302c4068cf | ||
|
|
ff11932a65 | ||
|
|
745038b4e2 | ||
|
|
3c3b26b419 | ||
|
|
1189a71205 | ||
|
|
f27dea2d8a | ||
|
|
7b5ff4e4b5 | ||
|
|
e94dc1baae | ||
|
|
3228da223e | ||
|
|
332334fb4f | ||
|
|
047ec9d6bc | ||
|
|
912c710096 | ||
|
|
38f1c4810c | ||
|
|
7fe7ec0fea |
No files matched your search
@@ -194,14 +194,14 @@ impl AgentCatalogs {
|
||||
(shared.paths.models_file.clone(), shared.paths.project_root.clone(), provider.to_owned())
|
||||
}
|
||||
|
||||
fn fallback(shared: &Shared, provider: &str) -> CatalogData {
|
||||
/// The catalog saved for this project, for before this run looked anything up.
|
||||
fn saved(shared: &Shared, provider: &str) -> CatalogData {
|
||||
let cache = shared.known.lock();
|
||||
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,
|
||||
})
|
||||
cache
|
||||
.get(provider)
|
||||
.and_then(|known| known.catalogs.get(&shared.root_key()))
|
||||
.map(|saved| saved.catalog.clone())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub(crate) fn cached(&self, shared: &Shared, provider: &str) -> CatalogData {
|
||||
@@ -210,32 +210,14 @@ impl AgentCatalogs {
|
||||
.entries
|
||||
.get(&Self::key(shared, provider))
|
||||
.and_then(|e| e.catalog.clone())
|
||||
.unwrap_or_else(|| Self::fallback(shared, provider))
|
||||
.unwrap_or_else(|| Self::saved(shared, provider))
|
||||
}
|
||||
|
||||
/// 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()
|
||||
/// 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()
|
||||
}
|
||||
|
||||
pub(crate) fn levels(&self, shared: &Shared, provider: &str, model: &str) -> Option<Vec<AgentConfigOption>> {
|
||||
@@ -246,14 +228,7 @@ impl AgentCatalogs {
|
||||
}
|
||||
drop(state);
|
||||
let cache = shared.known.lock();
|
||||
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()
|
||||
cache.get(provider)?.catalogs.get(&shared.root_key())?.catalog.thought_levels.get(model).cloned()
|
||||
}
|
||||
|
||||
pub(super) async fn load_levels(
|
||||
@@ -297,7 +272,7 @@ impl AgentCatalogs {
|
||||
}
|
||||
|
||||
fn snapshot(&self, shared: &Shared, provider: &str, entry: &Entry) -> AgentModelCatalog {
|
||||
let catalog = entry.catalog.clone().unwrap_or_else(|| Self::fallback(shared, provider));
|
||||
let catalog = entry.catalog.clone().unwrap_or_default();
|
||||
let model_failure = entry.requested_model.as_ref().and_then(|model| entry.model_failures.get(model));
|
||||
let unknown_model = entry
|
||||
.requested_model
|
||||
@@ -382,12 +357,11 @@ 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 catalog = entry.catalog.as_ref().or(fallback.as_ref()).expect("cached catalog");
|
||||
let empty = CatalogData::default();
|
||||
let catalog = entry.catalog.as_ref().unwrap_or(&empty);
|
||||
let fresh = entry.successful.is_some_and(|at| now.duration_since(at) < FRESH_FOR);
|
||||
let target = model
|
||||
.filter(|model| {
|
||||
@@ -496,7 +470,7 @@ impl AgentCatalogs {
|
||||
entry.flight_model = None;
|
||||
let success = match result {
|
||||
Ok(found) => {
|
||||
let previous = entry.catalog.take().unwrap_or_else(|| Self::fallback(shared, &key.2));
|
||||
let previous = entry.catalog.take().unwrap_or_default();
|
||||
let mut cache = shared.known.lock();
|
||||
let known = cache.entry(key.2.clone()).or_default();
|
||||
let mut catalog = CatalogData {
|
||||
@@ -510,13 +484,9 @@ 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,11 +230,9 @@ 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_eq!(model_values(&cached), ["old", "retained"]);
|
||||
assert!(cached.refreshed_at_ms.is_none(), "session reports are not fresh discovery");
|
||||
assert!(model_values(&cached).is_empty(), "nothing is offered before the first discovery");
|
||||
let pending = harness.next().await;
|
||||
assert_eq!(pending.params["mcpServers"], json!([]));
|
||||
pending.reply.send(Ok(response(&["retained", "new"], &["medium"]))).unwrap();
|
||||
@@ -258,7 +256,10 @@ 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.known.lock()[PROVIDER].refreshed_at_ms, fresh.refreshed_at_ms);
|
||||
assert_eq!(
|
||||
restored.shared.paths.catalogs.cached(&restored.shared, PROVIDER).refreshed_at_ms,
|
||||
fresh.refreshed_at_ms
|
||||
);
|
||||
assert!(!tmp.path().join("store").exists(), "refresh never creates tasks");
|
||||
}
|
||||
|
||||
@@ -308,6 +309,11 @@ 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;
|
||||
@@ -356,6 +362,7 @@ async fn discovered_model_lookup_does_not_overwrite_a_newer_selection() {
|
||||
#[derive(Clone, Copy)]
|
||||
enum ChatSwitch {
|
||||
Live,
|
||||
Aged,
|
||||
Resume,
|
||||
ResumeFails,
|
||||
Unavailable,
|
||||
@@ -376,7 +383,8 @@ async fn switch_chat_model(scenario: ChatSwitch) {
|
||||
let mut harness = Harness::with_initialize(json!({
|
||||
"protocolVersion": 1, "agentCapabilities": { "loadSession": true }
|
||||
}));
|
||||
let mut manager = make_manager(tmp.path(), Arc::default(), &harness);
|
||||
let catalogs = Arc::new(AgentCatalogs::default());
|
||||
let mut manager = make_manager(tmp.path(), catalogs.clone(), &harness);
|
||||
let task = manager
|
||||
.create(NewAgentTask {
|
||||
prompt: AgentPrompt { text: "first".into(), ..Default::default() },
|
||||
@@ -443,7 +451,11 @@ 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);
|
||||
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 resumed_launch = if missing_settings { 3 } else { 2 };
|
||||
let load_fails = matches!(scenario, ChatSwitch::ResumeFails);
|
||||
let unavailable = matches!(scenario, ChatSwitch::Unavailable);
|
||||
@@ -684,7 +696,7 @@ async fn next_chat_request(
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn legacy_cache_loads_without_claiming_authoritative_freshness() {
|
||||
async fn a_cache_from_before_project_catalogs_offers_nothing_until_discovery_succeeds() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
configure(tmp.path(), "one");
|
||||
let options = config::options_of(&response(&["legacy"], &["low"]));
|
||||
@@ -700,12 +712,11 @@ async fn legacy_cache_loads_without_claiming_authoritative_freshness() {
|
||||
let manager = make_manager(tmp.path(), Arc::default(), &harness);
|
||||
let mut events = events(&manager);
|
||||
let cached = manager.refresh_models(PROVIDER, false, None).unwrap();
|
||||
assert_eq!(model_values(&cached), ["legacy"]);
|
||||
assert!(model_values(&cached).is_empty());
|
||||
assert!(cached.refreshing && cached.refreshed_at_ms.is_none());
|
||||
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"));
|
||||
harness.next().await.reply.send(Ok(response(&["current"], &["low"]))).unwrap();
|
||||
let found = completed(&mut events).await;
|
||||
assert_eq!(model_values(&found), ["current"]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
+193
-60
@@ -23,7 +23,7 @@ mod provider;
|
||||
pub mod registry;
|
||||
pub mod security;
|
||||
mod shell;
|
||||
mod skills;
|
||||
pub mod skills;
|
||||
mod timeline;
|
||||
mod worktree;
|
||||
|
||||
@@ -131,6 +131,19 @@ 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,
|
||||
@@ -156,27 +169,18 @@ 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 in its last session, for the New Task page.
|
||||
/// What an agent offered, 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>>,
|
||||
/// 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.
|
||||
/// Model catalogs by project root, valid for the launch context they were read with.
|
||||
#[serde(default, rename = "projectCatalogs")]
|
||||
catalogs: HashMap<String, catalogs::SavedCatalog>,
|
||||
}
|
||||
@@ -294,7 +298,8 @@ impl Shared {
|
||||
self.paths.project_root.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
/// Cache levels only when `model` confirms which model the session reported them for.
|
||||
/// Keeps the commands a session offered and the effort levels it reported for `model`, the
|
||||
/// only model whose levels it describes.
|
||||
fn remember(
|
||||
&self,
|
||||
provider: &str,
|
||||
@@ -303,43 +308,22 @@ 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;
|
||||
// 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();
|
||||
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);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
// Discovery reads one model's options; a session on another model reports that model's.
|
||||
let learned = model.filter(|_| acp && known.authoritative).zip(config).map(|(model, config)| {
|
||||
if acp && let Some((model, config)) = model.zip(config) {
|
||||
let levels: Vec<_> = config.iter().filter(|o| config::is_per_model_option(o)).cloned().collect();
|
||||
(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 !levels.is_empty() {
|
||||
self.paths.catalogs.learn_levels(self, provider, model, levels);
|
||||
}
|
||||
}
|
||||
if changed {
|
||||
self.emit(AgentEvent::Providers);
|
||||
@@ -528,6 +512,8 @@ 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)>>,
|
||||
@@ -575,6 +561,7 @@ 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);
|
||||
@@ -724,10 +711,15 @@ 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,
|
||||
/// and, for Claude Code, skills and custom commands on disk it has not listed (for Hermes,
|
||||
/// its profile's skills).
|
||||
/// 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.
|
||||
pub async fn commands(&self, provider: &str, task: Option<&str>) -> IdeResult<Vec<AgentCommand>> {
|
||||
let (provider, offered, cwd) = match task {
|
||||
Some(id) => {
|
||||
@@ -770,11 +762,44 @@ impl AgentManager {
|
||||
.await?;
|
||||
return Ok(skills::merge(offered, found));
|
||||
}
|
||||
if provider != "claude" && provider != "claude-acp" {
|
||||
return Ok(offered);
|
||||
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);
|
||||
}
|
||||
let found = blocking(move || Ok(skills::discover(&cwd, home.as_deref()))).await?;
|
||||
Ok(skills::merge(offered, found))
|
||||
// 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)
|
||||
}
|
||||
|
||||
fn task(&self, id: &str) -> IdeResult<Arc<Task>> {
|
||||
@@ -858,6 +883,7 @@ impl AgentManager {
|
||||
retry: None,
|
||||
background: Box::default(),
|
||||
mcp_overrides: BTreeMap::new(),
|
||||
skill_overrides: BTreeMap::new(),
|
||||
stats: Box::default(),
|
||||
};
|
||||
let file = TaskFile {
|
||||
@@ -976,6 +1002,7 @@ impl AgentManager {
|
||||
retry: None,
|
||||
background: Box::default(),
|
||||
mcp_overrides: req.mcp_overrides,
|
||||
skill_overrides: req.skill_overrides,
|
||||
stats: Box::default(),
|
||||
};
|
||||
let file = TaskFile {
|
||||
@@ -1319,13 +1346,14 @@ 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);
|
||||
let mut params = session_params(&cwd_s, &mcp_servers, skills_delivery.as_ref());
|
||||
params["sessionId"] = json!(live.session);
|
||||
params
|
||||
},
|
||||
@@ -1726,6 +1754,7 @@ 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))
|
||||
@@ -1987,6 +2016,38 @@ 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) {
|
||||
@@ -2019,6 +2080,55 @@ 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);
|
||||
@@ -2075,6 +2185,7 @@ 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()),
|
||||
@@ -2366,7 +2477,8 @@ impl Task {
|
||||
if stop != "cancelled" {
|
||||
self.emit_attention(AgentAttentionReason::Finished);
|
||||
}
|
||||
if self.mcp_reload_pending.swap(false, Ordering::AcqRel)
|
||||
if (self.mcp_reload_pending.swap(false, Ordering::AcqRel)
|
||||
|| self.skills_reload_pending.swap(false, Ordering::AcqRel))
|
||||
&& self.state.lock().background_tasks.is_empty()
|
||||
{
|
||||
self.recycle_resumable_session();
|
||||
@@ -2395,8 +2507,7 @@ impl Task {
|
||||
|
||||
async fn switch_discovered_model(&self, target: AgentConfigOption, value: String) -> IdeResult<()> {
|
||||
let provider = self.state.lock().task.provider.clone();
|
||||
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(|| {
|
||||
let candidate = self.shared.paths.catalogs.listed_model(&self.shared, &provider, &value).ok_or_else(|| {
|
||||
IdeError::invalid(format!("{} has no value {value} in the current model catalog", target.name))
|
||||
})?;
|
||||
let selection = {
|
||||
@@ -2884,6 +2995,7 @@ 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();
|
||||
|
||||
@@ -2898,7 +3010,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);
|
||||
let mut params = session_params(&cwd_s, &mcp_servers, skills_delivery.as_ref());
|
||||
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;
|
||||
@@ -2938,7 +3050,7 @@ impl Task {
|
||||
let (session_id, result) = match session {
|
||||
Some(s) => s,
|
||||
None => {
|
||||
let params = session_params(&cwd_s, &mcp_servers);
|
||||
let params = session_params(&cwd_s, &mcp_servers, skills_delivery.as_ref());
|
||||
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 },
|
||||
@@ -3914,13 +4026,34 @@ 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.
|
||||
fn session_params(cwd: &str, mcp: &McpForSession) -> Value {
|
||||
/// 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 {
|
||||
let mut params = json!({ "cwd": cwd, "mcpServers": mcp.servers });
|
||||
let mut meta = json!({});
|
||||
if !mcp.off.is_empty() {
|
||||
params["_meta"] = json!({ "openidea": { "mcpServersOff": mcp.off } });
|
||||
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
|
||||
}
|
||||
|
||||
@@ -110,6 +110,9 @@ 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)]
|
||||
@@ -687,6 +690,9 @@ 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)]
|
||||
@@ -705,6 +711,8 @@ 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.
|
||||
@@ -879,6 +887,84 @@ 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,6 +172,10 @@ 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.
|
||||
@@ -356,10 +360,13 @@ 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,
|
||||
@@ -673,6 +680,14 @@ 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,6 +334,31 @@ 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")
|
||||
@@ -414,6 +439,31 @@ 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);
|
||||
@@ -434,14 +484,13 @@ impl CodexShim {
|
||||
let models = self.models().await?;
|
||||
self.prepare_project_trust(params).await;
|
||||
let mut request = json!({ "cwd": params.get("cwd") });
|
||||
if let Some(config) = translate::mcp_config(params) {
|
||||
request["config"] = config;
|
||||
}
|
||||
apply_thread_config(params, &mut request);
|
||||
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 }))
|
||||
}
|
||||
@@ -452,9 +501,7 @@ impl CodexShim {
|
||||
let models = self.models().await?;
|
||||
self.prepare_project_trust(params).await;
|
||||
let mut request = json!({ "threadId": id, "cwd": params.get("cwd") });
|
||||
if let Some(config) = translate::mcp_config(params) {
|
||||
request["config"] = config;
|
||||
}
|
||||
apply_thread_config(params, &mut request);
|
||||
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());
|
||||
@@ -462,6 +509,7 @@ 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 }))
|
||||
}
|
||||
@@ -472,9 +520,7 @@ 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") });
|
||||
if let Some(config) = translate::mcp_config(params) {
|
||||
request["config"] = config;
|
||||
}
|
||||
apply_thread_config(params, &mut request);
|
||||
if let Some(s) = &settings {
|
||||
request["model"] = json!(s.model_slug(&models));
|
||||
request["approvalPolicy"] = json!(s.mode.approval_policy());
|
||||
@@ -482,6 +528,7 @@ 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,6 +372,24 @@ 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)
|
||||
}
|
||||
@@ -496,6 +514,7 @@ 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
|
||||
@@ -546,6 +565,7 @@ 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,11 +1,17 @@
|
||||
//! 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`).
|
||||
//! 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.
|
||||
|
||||
use crate::{AgentCommand, AgentCommandSource};
|
||||
use std::collections::HashSet;
|
||||
use std::path::Path;
|
||||
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};
|
||||
|
||||
const MAX_DESCRIPTION: usize = 200;
|
||||
/// Command directories nest this deep at most (`a/b/c.md` → `a:b:c`).
|
||||
@@ -200,6 +206,370 @@ 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::*;
|
||||
@@ -333,4 +703,231 @@ 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);
|
||||
}
|
||||
}
|
||||
+125
-239
@@ -1010,7 +1010,6 @@ 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()));
|
||||
@@ -1197,7 +1196,6 @@ 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.
|
||||
@@ -1206,7 +1204,6 @@ 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;
|
||||
@@ -2167,52 +2164,6 @@ 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> {
|
||||
@@ -2220,51 +2171,6 @@ 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.
|
||||
@@ -2303,12 +2209,9 @@ 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 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}");
|
||||
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:?}");
|
||||
restored.shutdown();
|
||||
}
|
||||
}
|
||||
@@ -2541,100 +2444,6 @@ 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 =
|
||||
@@ -3192,49 +3001,6 @@ 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 {
|
||||
@@ -3868,6 +3634,123 @@ 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};
|
||||
@@ -4532,6 +4415,7 @@ 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();
|
||||
@@ -4660,6 +4544,7 @@ 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();
|
||||
@@ -4685,6 +4570,7 @@ 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();
|
||||
@@ -4763,10 +4649,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);
|
||||
let params = session_params("/p", &mcp, None);
|
||||
assert_eq!(params["cwd"], "/p");
|
||||
assert_eq!(params["mcpServers"][0]["name"], "docs");
|
||||
assert_eq!(params["_meta"]["openidea"]["mcpServersOff"], json!(["github"]));
|
||||
let none = McpForSession { servers: Vec::new(), off: Vec::new() };
|
||||
assert!(session_params("/p", &none).get("_meta").is_none());
|
||||
assert!(session_params("/p", &none, None).get("_meta").is_none());
|
||||
}
|
||||
@@ -25,6 +25,98 @@ 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())))
|
||||
}
|
||||
@@ -38,6 +130,9 @@ 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),
|
||||
@@ -127,6 +222,7 @@ pub(crate) fn changes(cwd: &Path, base: &str) -> IdeResult<Vec<AgentChange>> {
|
||||
added,
|
||||
removed,
|
||||
old_path: f.old_path,
|
||||
repo: None,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
@@ -143,6 +239,9 @@ 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
|
||||
@@ -157,6 +256,7 @@ 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))
|
||||
})
|
||||
@@ -165,7 +265,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 }
|
||||
AgentChange { path, rel_path, kind: ChangeKind::Added, added, removed: 0, old_path: None, repo: None }
|
||||
}
|
||||
|
||||
/// The commits from `base` (exclusive) to `head` (inclusive) in `cwd`, newest first, each
|
||||
@@ -201,6 +301,7 @@ pub(crate) fn commits(cwd: &Path, base: &str, head: &str) -> IdeResult<Vec<Agent
|
||||
added,
|
||||
removed,
|
||||
old_path: f.old_path,
|
||||
repo: None,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
@@ -266,6 +367,9 @@ 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()) };
|
||||
@@ -324,6 +428,9 @@ 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 {
|
||||
@@ -353,6 +460,8 @@ 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) };
|
||||
@@ -545,6 +654,18 @@ 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())
|
||||
}
|
||||
@@ -587,10 +708,16 @@ 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 Some(repo) = Repo::discover(cwd)? else { return Ok(false) };
|
||||
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 mut saved = false;
|
||||
for (rel, stamp) in before {
|
||||
let path = repo.root().join(rel);
|
||||
let path = root.join(rel);
|
||||
if stamp.is_none() || !std::fs::metadata(&path).is_ok_and(|m| m.is_file() && m.len() <= SAVED_MAX) {
|
||||
continue;
|
||||
}
|
||||
@@ -625,7 +752,8 @@ pub(crate) fn restore(
|
||||
}
|
||||
None => match rev {
|
||||
Some(rev) => {
|
||||
let repo = Repo::discover(cwd)?.ok_or_else(|| IdeError::invalid("not in a git repository"))?;
|
||||
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"))?;
|
||||
repo.file_bytes_at(&change.path.0, Some(rev))?
|
||||
}
|
||||
None => None,
|
||||
@@ -665,6 +793,9 @@ 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>,
|
||||
@@ -680,8 +811,16 @@ 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(repo) = discover(cwd)? else { return Ok(TurnStart::default()) };
|
||||
let head = repo.head()?.1;
|
||||
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
|
||||
};
|
||||
// As the turn's end is read, so the two compare.
|
||||
let before = snapshot(cwd)?;
|
||||
let mut saved = BTreeSet::new();
|
||||
@@ -702,7 +841,7 @@ pub(crate) fn start_turn(cwd: &Path, dir: &Path, previous: Option<&TurnStart>) -
|
||||
}
|
||||
}
|
||||
for (rel, stamp) in &before {
|
||||
let path = repo.root().join(rel);
|
||||
let path = at.base.join(rel);
|
||||
if stamp.is_none()
|
||||
|| saved.contains(rel)
|
||||
|| !std::fs::metadata(&path).is_ok_and(|m| m.is_file() && m.len() <= SAVED_MAX)
|
||||
@@ -715,7 +854,7 @@ pub(crate) fn start_turn(cwd: &Path, dir: &Path, previous: Option<&TurnStart>) -
|
||||
saved.insert(rel.clone());
|
||||
}
|
||||
}
|
||||
Ok(TurnStart { head, before, saved, changed: None })
|
||||
Ok(TurnStart { head, heads, before, saved, changed: None })
|
||||
}
|
||||
|
||||
/// The files that changed in `cwd` since the turn `start` began: in the working tree (as
|
||||
@@ -724,20 +863,25 @@ 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();
|
||||
if let Some(repo) = discover(cwd)?
|
||||
&& let (Some(from), Some(to)) = (&start.head, repo.head()?.1)
|
||||
&& *from != to
|
||||
{
|
||||
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}") };
|
||||
for f in repo.diff_revisions(from, &to)? {
|
||||
all.extend(f.old_path);
|
||||
all.insert(f.path);
|
||||
all.extend(f.old_path.map(named));
|
||||
all.insert(named(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(repo: &Repo, rel: &str, start: &TurnStart, dir: &Path) -> IdeResult<Option<Vec<u8>>> {
|
||||
fn at_turn_start(at: &TurnRepos, 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() {
|
||||
@@ -746,10 +890,13 @@ fn at_turn_start(repo: &Repo, rel: &str, start: &TurnStart, dir: &Path) -> IdeRe
|
||||
"{rel} had changes when the turn started that weren't saved; roll it back in Git instead"
|
||||
))),
|
||||
},
|
||||
None => match &start.head {
|
||||
Some(head) => repo.file_bytes_at(&repo.root().join(rel), Some(head)),
|
||||
None => Ok(None),
|
||||
},
|
||||
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),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -771,13 +918,13 @@ pub(crate) fn turn_changes(
|
||||
dir: &Path,
|
||||
changed: &BTreeSet<String>,
|
||||
) -> IdeResult<Vec<AgentChange>> {
|
||||
let Some(repo) = discover(cwd)? else { return Ok(Vec::new()) };
|
||||
let Some(at) = TurnRepos::of(cwd)? else { return Ok(Vec::new()) };
|
||||
let mut out = Vec::new();
|
||||
for rel in changed {
|
||||
let path = repo.root().join(rel);
|
||||
let path = at.base.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(&repo, rel, start, dir) {
|
||||
let (kind, (added, removed)) = match at_turn_start(&at, rel, start, dir) {
|
||||
Ok(then) if then == now => continue,
|
||||
Ok(then) => {
|
||||
let kind = match (&then, &now) {
|
||||
@@ -790,19 +937,29 @@ pub(crate) fn turn_changes(
|
||||
// Its start wasn't saved: listed, without counts.
|
||||
Err(_) => (ChangeKind::Modified, (0, 0)),
|
||||
};
|
||||
out.push(AgentChange { path: IpcPath(path), rel_path: rel.clone(), kind, added, removed, old_path: None });
|
||||
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),
|
||||
});
|
||||
}
|
||||
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(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) {
|
||||
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))
|
||||
{
|
||||
return file_at(cwd, path, head);
|
||||
}
|
||||
let Some(bytes) = at_turn_start(&repo, &rel, start, dir)? else { return Ok(None) };
|
||||
let Some(bytes) = at_turn_start(&at, &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),
|
||||
@@ -828,12 +985,15 @@ 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 repo = repo_at(cwd)?;
|
||||
put(&change.path.0, at_turn_start(&repo, &change.rel_path, start, dir)?)
|
||||
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)?)
|
||||
}
|
||||
|
||||
pub(crate) fn file_at(cwd: &Path, path: &Path, rev: &str) -> IdeResult<Option<String>> {
|
||||
let Some(repo) = discover(cwd)? else { return Ok(None) };
|
||||
// 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 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),
|
||||
@@ -962,6 +1122,54 @@ 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,6 +102,8 @@ 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,6 +130,11 @@ 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 {
|
||||
@@ -150,6 +155,7 @@ impl Default for AgentSettings {
|
||||
new_task_approvals: NewTaskApprovals::Bypass,
|
||||
defaults: BTreeMap::new(),
|
||||
mcp_servers: BTreeMap::new(),
|
||||
skills: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -205,6 +211,34 @@ 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,6 +110,17 @@ 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) {
|
||||
@@ -184,6 +195,14 @@ 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,6 +151,7 @@ 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,
|
||||
@@ -190,6 +191,7 @@ 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: trust::TrustStore,
|
||||
pub trust: std::sync::Arc<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: trust::TrustStore::load(&config_dir, &data_dir),
|
||||
trust: std::sync::Arc::new(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 keeps a window of very long lines and drops the matches outside it:
|
||||
// such lines are matched again in the file's whole text.
|
||||
// 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.
|
||||
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,11 +679,15 @@ 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)
|
||||
{
|
||||
hits.extend(line_hits(path, text, ranges, m.line));
|
||||
if expanded.insert(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,8 +7,9 @@ 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, AgentTask, CustomAgentInput, ExternalSession, McpExternalSource,
|
||||
McpImportSelection, McpProbeResult, McpScope, McpServer, McpServerInput, McpTransport, NewAgentTask,
|
||||
AgentPrompt, AgentProvider, AgentQueued, AgentSkillMode, AgentSkillPolicy, AgentSkillState, AgentTask,
|
||||
CustomAgentInput, ExternalSession, McpExternalSource, McpImportSelection, McpProbeResult, McpScope, McpServer,
|
||||
McpServerInput, McpTransport, NewAgentTask, SkillsPolicy,
|
||||
};
|
||||
use ide_command::command;
|
||||
use ide_core::error::ErrorKind;
|
||||
@@ -1028,6 +1029,148 @@ 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());
|
||||
@@ -1183,6 +1326,9 @@ 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), tree-sitter otherwise.
|
||||
/// visibility and type-alias kinds), 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,10 +113,13 @@ 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; borrow it from the syntax tree.
|
||||
// Server symbols carry no visibility, nor a kind for type aliases; borrow them from
|
||||
// the syntax tree.
|
||||
Some(mut items) => {
|
||||
if !snap.large {
|
||||
ide_language::merge_visibility(&mut items, &syntax());
|
||||
let syntax = syntax();
|
||||
ide_language::merge_visibility(&mut items, &syntax);
|
||||
ide_language::merge_kinds(&mut items, &syntax);
|
||||
}
|
||||
items
|
||||
}
|
||||
|
||||
@@ -335,6 +335,12 @@ 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,6 +22,17 @@ 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)]
|
||||
@@ -98,10 +109,7 @@ pub(crate) fn search_project(
|
||||
Some(ProjectFileSet::Test) => roots.is_test(rel),
|
||||
_ => true,
|
||||
};
|
||||
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 literals = |path: &Path, text: &str| literals_of(project, syntax, path, text);
|
||||
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,9 +75,19 @@ 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);
|
||||
ide_search::replace_files(&host, &query, &replacement, preserve_case, &targets, &cancel, &|e| {
|
||||
let _ = events.send(e);
|
||||
})
|
||||
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);
|
||||
},
|
||||
)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| ide_core::IdeError::internal(e.to_string()));
|
||||
|
||||
@@ -3059,6 +3059,10 @@ impl HostApi for PluginApi {
|
||||
dunce::canonicalize(files).map_err(failed)
|
||||
}
|
||||
|
||||
fn install_dir(&self) -> Result<PathBuf, HostError> {
|
||||
dunce::canonicalize(&self.pkg.dir).map_err(failed)
|
||||
}
|
||||
|
||||
fn read_text_file(&self, real: &Path, max: usize) -> Result<String, HostError> {
|
||||
// Unsaved editor contents win, as they do for project files.
|
||||
if let Some(text) = self.shared.workspace().and_then(|w| w.buffer_text(real)) {
|
||||
@@ -3749,6 +3753,19 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn install_dir_is_the_canonical_package_directory() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let pkg = tmp.path().join("acme.lint");
|
||||
std::fs::create_dir_all(&pkg).unwrap();
|
||||
std::fs::write(pkg.join("readme.pdf"), b"%PDF").unwrap();
|
||||
let api = api(&pkg, Arc::default());
|
||||
let install = api.install_dir().unwrap();
|
||||
assert_eq!(install, dunce::canonicalize(&pkg).unwrap());
|
||||
assert!(install.join("readme.pdf").is_file());
|
||||
assert_ne!(install, api.plugin_dir().unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn storage_moves_an_older_storage_json_to_one_file_per_key() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -738,6 +738,19 @@ 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,6 +187,19 @@ 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,3 +195,56 @@ 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_visibility,
|
||||
VueComponentImport, VueRefAccess, VueRefElement, WebReference, WebReferenceKind, merge_kinds, 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_visibility;
|
||||
pub use outline::{merge_kinds, merge_visibility};
|
||||
pub use php_align::PhpAlignment;
|
||||
pub use python_facts::{MethodBody, PythonClassFacts, PythonFacts, PythonMethodFacts};
|
||||
use std::cell::RefCell;
|
||||
|
||||
@@ -495,6 +495,36 @@ 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,6 +1476,88 @@ 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";
|
||||
|
||||
@@ -652,6 +652,10 @@ pub trait HostApi: Send + Sync {
|
||||
fn plugin_dir(&self) -> Result<PathBuf, HostError> {
|
||||
Err(HostError::Failed("private plugin storage is unavailable".into()))
|
||||
}
|
||||
/// The plugin's install / package directory (read-only for the guest).
|
||||
fn install_dir(&self) -> Result<PathBuf, HostError> {
|
||||
Err(HostError::Failed("plugin install directory is unavailable".into()))
|
||||
}
|
||||
/// Replaces the text of a file whose real path the caller already checked:
|
||||
/// in one step, keeping its encoding and BOM (a new file is UTF-8). Refused
|
||||
/// while an editor holds unsaved changes for it.
|
||||
|
||||
@@ -313,11 +313,11 @@ impl StoreData {
|
||||
|
||||
/// `path` as the real path an `fs.read:…` grant covers, or what the plugin
|
||||
/// should be told instead (`denied` naming the capability to declare).
|
||||
/// The private plugin-dir and the install directory are readable without a
|
||||
/// grant; writing still needs `fs.write` or the private dir.
|
||||
fn granted_file(&self, path: &str) -> Result<PathBuf, wit::Error> {
|
||||
let mut granted = self.granted.clone();
|
||||
if let Ok(dir) = self.host.plugin_dir() {
|
||||
granted.push(Capability::FsRead(to_ipc(&dir)));
|
||||
}
|
||||
granted.extend(self.builtin_read_roots());
|
||||
sandbox::resolve_granted(&granted, path).map_err(Into::into)
|
||||
}
|
||||
|
||||
@@ -331,6 +331,19 @@ impl StoreData {
|
||||
sandbox::resolve_writable(&granted, path).map_err(Into::into)
|
||||
}
|
||||
|
||||
/// Private plugin-dir and install directory: readable without an `fs.read`
|
||||
/// grant; `editor.open` / `open-location` may use them without project.read.
|
||||
fn builtin_read_roots(&self) -> Vec<Capability> {
|
||||
let mut roots = Vec::new();
|
||||
if let Ok(dir) = self.host.plugin_dir() {
|
||||
roots.push(Capability::FsRead(to_ipc(&dir)));
|
||||
}
|
||||
if let Ok(dir) = self.host.install_dir() {
|
||||
roots.push(Capability::FsRead(to_ipc(&dir)));
|
||||
}
|
||||
roots
|
||||
}
|
||||
|
||||
fn client(&self) -> Option<&str> {
|
||||
self.invocation.client.as_deref()
|
||||
}
|
||||
@@ -1144,9 +1157,7 @@ impl StoreData {
|
||||
sandbox::resolve_in_root(root, path).map_err(wit::Error::Invalid)
|
||||
}
|
||||
fn openable_path(&self, path: &str) -> Result<PathBuf, wit::Error> {
|
||||
if let Ok(dir) = self.host.plugin_dir()
|
||||
&& let Ok(real) = sandbox::resolve_granted(&[Capability::FsRead(to_ipc(&dir))], path)
|
||||
{
|
||||
if let Ok(real) = sandbox::resolve_granted(&self.builtin_read_roots(), path) {
|
||||
return Ok(real);
|
||||
}
|
||||
self.require(Capability::ProjectRead)?;
|
||||
@@ -2078,9 +2089,7 @@ impl views::Host for StoreData {
|
||||
}
|
||||
|
||||
fn open_location(&mut self, path: String, line: u32, column: u32) -> Fallible<()> {
|
||||
if let Ok(dir) = self.host.plugin_dir()
|
||||
&& let Ok(real) = sandbox::resolve_granted(&[Capability::FsRead(to_ipc(&dir))], &path)
|
||||
{
|
||||
if let Ok(real) = sandbox::resolve_granted(&self.builtin_read_roots(), &path) {
|
||||
if let Err(e) = self.require_interactive() {
|
||||
return Ok(Err(e));
|
||||
}
|
||||
|
||||
@@ -1 +1 @@
|
||||
b59392bcc1999048f0ab922ec659bc21d9e825c696fa41d9f0a40c85627a5b2c
|
||||
d442e600d82cab0f79ad6decf95ca9d06c89dcd3119c500a11f48cdc54a5d5f4
|
||||
@@ -1 +1 @@
|
||||
034b99891313c03eb2a6b8c3cb2e4784129e1936965be803512f1d869b1768c2
|
||||
af048639f57e86262543c3dcd18bca27d384b6ad99a625af869f0812bf8ac93c
|
||||
@@ -1 +1 @@
|
||||
29ec0a96e2a0f6965915c7c25e35036743fc27a49037df588c217e8abfff93e3
|
||||
95b7263ca584c6b1b035be4dde64c7ae57b407c6a86b5ab6fe2736134e1d7754
|
||||
@@ -1 +1 @@
|
||||
87b367cfdd65c360920eff7be4d6a8d6b939721f6398aa6a01e39a289590699e
|
||||
1e5b10e8e77bdc7ed6bf002a415458caef7eee9a98123229dddf0d148af58f73
|
||||
@@ -1 +1 @@
|
||||
7d034ee1a4b99615642d5bf033802f8e4662216d45b209c4c7a24eb8f1338f48
|
||||
5b3d4ad737cde32fc808bcd8c93d9cdd7d53961985db0428ab567b4e97ed4ffb
|
||||
@@ -1 +1 @@
|
||||
3fdf985273ec14ae623fa84602a9220cfbfb2e0e587ab192fc2bcb8d990ce9e3
|
||||
04b1cbc2148cff8c0fa2d6a4f127a6a3c8ade5a7dc1541c1a16a656def299f33
|
||||
@@ -1 +1 @@
|
||||
8434e9271e27a6778bb3d5922e8925f3fd9f1d35377e5dddf5b5eb5416bd09bb
|
||||
918c44ee3a58a073dd65e2f7e32501cf9e84a59f24452c166e75457f7c232c89
|
||||
@@ -1 +1 @@
|
||||
9fa7468ce385ff33c1f3b99c84711e0d11a84b10e8e4f95b358fcd2ccc96e255
|
||||
c980260c235249186f754e16597de9d49663771d711ce6873bf83ebaf2a0fc34
|
||||
@@ -1 +1 @@
|
||||
5220a5bfb6ec0467a72e63e21d690e70b7d46b4f2eaff4116a8a79220a5eca8f
|
||||
df5729d63b83fbc511e0ba8509f9d370c5124b5af4c70f286c8965d2b0d890ef
|
||||
@@ -1 +1 @@
|
||||
a962127d1c6e37e85b81973a272a5d6b383cc2884b41bb2d82e8640ef5f8f943
|
||||
305965c6cbf2fd2b331bf9e2c473cfa9a543ab39ff0d47317ee9e28be9ea5b0f
|
||||
@@ -1 +1 @@
|
||||
92ad3e43e7f343004dcf26a51e282e97ed694cc9bd7325ff75aa5b18f1a2eeb6
|
||||
a1bb95a8a23ddd2d55bf64c724f73debfb503f252f57d8ae46afda8a0717fc20
|
||||
@@ -1 +1 @@
|
||||
2200ed0d44dbafb70ad864cb9569b0b2c37cf9eec1582b05efa903a9e8ec89ee
|
||||
b8be3120a468190aebb473c8f5d2e13889210241c9ab43c89cbf703c00366c8e
|
||||
@@ -1 +1 @@
|
||||
644612ee4228010f141042ea0eab5431b8386370f863a70b63cd3315f69d963a
|
||||
9b345dec001bcb7c0d8e6e214099d597b02976f20c2449af9847e8b69d0a5ab7
|
||||
@@ -1 +1 @@
|
||||
2af5d46516bfc1d38ad1f24d6cf3c57e2d6db6b0d3225748f55c4f13110430fb
|
||||
23e0c2ab39ba83aa332b57046b0b8c1bf236e3e61a14874ed82d20ce388873b6
|
||||
@@ -1 +1 @@
|
||||
0ee0773cefd61b8144d0550718e1988a1e60438bee826c3867350e28886a56f7
|
||||
e2d2afeb53f0af478963cde0c97fb016b1a424bf97952c7474a18e38e9e9ed55
|
||||
@@ -1 +1 @@
|
||||
941cb9008aaab11464b193c37b91e2476d771ec526247713f291c6642caf5995
|
||||
6bff7a7521a4a969aa8d9bd1363ef5efd544e079e77e55e51b19fff13b586b3a
|
||||
@@ -1 +1 @@
|
||||
06d70aae3152c88d1299a9b33f151b0baa4a77c3ca7145215c6f6e0aa40727b2
|
||||
27bb4c06b18703c43155e1a45c9edfb249a19443a68e87441babeeb71cb127d9
|
||||
@@ -1 +1 @@
|
||||
86eb87758e4f7c0242a18f12a113c31d418da64d7198041120f19401a5707bfb
|
||||
deb7995931cf8e344a486fbab275fd3ec7ddff73b05a841593e5521c4a514084
|
||||
@@ -1 +1 @@
|
||||
4442bb686fa18e8e8a52fd1cd8683b8767ec7908ffc1454dff476d9cb1711be9
|
||||
dc6670ff6373d148430f5c9c13d1ec5407b2d94c74c2209562737076468ca79d
|
||||
+1
-1
@@ -1 +1 @@
|
||||
dd51f1b8634ff6305ba1a69c8457bd586996200a2b18e4a08d0cfa2fb60abaf6
|
||||
9e111c4c541312dc231bac5a4fd1120b59191ecadce2dca73c77f4bff2a9d0e8
|
||||
@@ -1 +1 @@
|
||||
4319f2655ee1e240b33f4b96c23fff59c61aa62d6ccc628715e5ff9fe38c2717
|
||||
caa4053cd7f0135ab14a8c5c56abe198394e370549fea6d9df4d4c11c38fcabf
|
||||
@@ -1 +1 @@
|
||||
50c4fd7e08a4187afae0e00c775a61578b82bbad056807ad063ee47e79e2cef1
|
||||
8beb151f14b062438c4024b13bbdedbf5d65099415ad9d055fe63a4b1d64d010
|
||||
@@ -1 +1 @@
|
||||
220666302d814e6d8bde346954205c94c82320d5584d46f01672fd7d32400bf3
|
||||
fa6a660890e0beee7599726e9c30142601fbcd6f82a519b1b5952ef30f450bfb
|
||||
@@ -1 +1 @@
|
||||
4ee484afaa1a1f71a9e544582d90db3260307fc89b8f514aaaff883df2761ba6
|
||||
a7c1ec4814e4268fe185ae493413532528970264e84f717087b57a303ebe3591
|
||||
@@ -1 +1 @@
|
||||
3fba59ce802d88a2a1c026480a2cb8ce4d9539eb7b88f5a18bf6232f7adef147
|
||||
450d1e698882257d6c75b16984a6086259acce2c66a92b96c76ed3d6e15a0b4d
|
||||
@@ -1 +1 @@
|
||||
73433da25d5304d0a3cb83d750d02feb5e270ee7e9f680c4ee9d923afa9aa066
|
||||
738791aa00d63961fa7e8ed6ac7601f46848ecc0d25a498b6019eb151bf9169e
|
||||
@@ -1 +1 @@
|
||||
12df43f99eac93f4e1a070635780ad653932cf69a14595175d8ba6d4f0a4445c
|
||||
957d02e3d72673ca4a9ca80eb7c3e63087a6d8377411fc820d3808f024326b2e
|
||||
@@ -1 +1 @@
|
||||
427b63c11188689262101cde971af0a92e54bd6c88a4e3cc8fdfa1a7c8c95fce
|
||||
f0a57acc6ca29b0dc2803596a0a39ceb1e2185b59a44f5533e8f9b19bf214afd
|
||||
@@ -1 +1 @@
|
||||
07ae58fe39746b779b1e466d7bbbb666ba550f427c7bf8de97d7ede647c00bc0
|
||||
7890cfd9a08b67b47ae098ce24e02551935337b8501636e29164ff4ca6244e7e
|
||||
@@ -1 +1 @@
|
||||
f9912644c28512e37299834123cd4c94f6ed11f29bd38ddbc1c92df168447494
|
||||
769f873adfa7ed3752a059dac89e60f2203b8ce91b36fe0a7cb9c724e0cf895b
|
||||
@@ -1 +1 @@
|
||||
ea0eec8c07d6469d3ab63c3bb08c85b01208be1757edffe5eabcb7be79ccf537
|
||||
ea31cbeefee7f219f86fc7e65315aea7efebe3b91c9cec6e12d4f551b9655d95
|
||||
@@ -1 +1 @@
|
||||
1ce55fabaa5ea1ddf770c8a1ad7f7b60a843c82c453d42289088c4b2fec61d84
|
||||
bb30795e7d62b19b237759beeab9da6f6028fea7862d8fa83c6b3238a26f540d
|
||||
@@ -1 +1 @@
|
||||
3356b4ec918c668c4c249f84afb9bafcd06c073ba86235b6ceea7ef6220cdaf5
|
||||
65725512c8a8d3ad6cb02a4f947541dd1688a3208e37fa4ed0474ca8197f2340
|
||||
@@ -1337,6 +1337,10 @@ 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,7 +1725,15 @@ 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"));
|
||||
assert!(cfg.initialization_options.is_none());
|
||||
// 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}");
|
||||
}
|
||||
// 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,13 +1,12 @@
|
||||
//! Parallel walk + per-file search.
|
||||
|
||||
use crate::iter::for_each_match;
|
||||
use crate::line::line_match;
|
||||
use crate::line::line_matches;
|
||||
use crate::mask::FileMask;
|
||||
use crate::pattern::ScopePattern;
|
||||
use crate::query::{Compiled, line_terminator};
|
||||
use crate::{
|
||||
FileMatches, LineMatch, LiteralKind, LiteralRange, Literals, PathFilter, SearchContext, SearchScope, SearchSummary,
|
||||
TextSource,
|
||||
FileMatches, LineMatch, LiteralRange, Literals, PathFilter, SearchContext, SearchScope, SearchSummary, TextSource,
|
||||
};
|
||||
use grep_regex::RegexMatcher;
|
||||
use grep_searcher::{BinaryDetection, Searcher, SearcherBuilder, Sink, SinkMatch};
|
||||
@@ -52,6 +51,7 @@ struct Control<'a> {
|
||||
matches: AtomicU32,
|
||||
files: AtomicU32,
|
||||
max: u32,
|
||||
whole_word: bool,
|
||||
}
|
||||
|
||||
impl Control<'_> {
|
||||
@@ -131,6 +131,7 @@ 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();
|
||||
@@ -462,12 +463,6 @@ 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;
|
||||
|
||||
@@ -488,12 +483,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, &buffer[..range.end], range.start, |mm| {
|
||||
for_each_match(self.matcher, self.ctl.whole_word, &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.accepts(literal_at(literals, block_start.saturating_add(a))));
|
||||
found.retain(|&(a, _)| context.keeps(literals, block_start.saturating_add(a)));
|
||||
}
|
||||
|
||||
let mut next = found.iter().copied().peekable();
|
||||
@@ -521,7 +516,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);
|
||||
self.lines.push(line_match(line_no, &block[line_start..content_end], &ranges));
|
||||
line_matches(line_no, &block[line_start..content_end], &ranges, &mut self.lines);
|
||||
}
|
||||
line_start = line_end_incl;
|
||||
line_no += 1;
|
||||
@@ -706,6 +701,7 @@ mod budget_tests {
|
||||
matches: AtomicU32::new(0),
|
||||
files: AtomicU32::new(0),
|
||||
max,
|
||||
whole_word: false,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,16 +1,27 @@
|
||||
//! Match iteration that never splits a UTF-8 sequence after an empty match
|
||||
//! (`grep-matcher`'s iterators advance by a single byte).
|
||||
//! (`grep-matcher`'s iterators advance by a single byte), and that applies
|
||||
//! IDEA's whole-word rule.
|
||||
|
||||
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.
|
||||
pub(crate) fn for_each_match(matcher: &RegexMatcher, haystack: &[u8], at: usize, mut f: impl FnMut(Match)) {
|
||||
/// 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),
|
||||
) {
|
||||
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;
|
||||
@@ -23,6 +34,7 @@ pub(crate) fn for_each_match(matcher: &RegexMatcher, haystack: &[u8], at: usize,
|
||||
/// 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),
|
||||
@@ -34,6 +46,10 @@ 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;
|
||||
@@ -45,12 +61,59 @@ 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() {
|
||||
return m.end();
|
||||
}
|
||||
let mut next = m.end() + 1;
|
||||
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;
|
||||
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, replacement_edits,
|
||||
replace_files, replace_files_in_context, replacement_edits,
|
||||
};
|
||||
pub use words::{WordFiles, WordQuery, files_with_word};
|
||||
|
||||
@@ -99,8 +99,15 @@ 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.
|
||||
fn needs_literals(self) -> bool {
|
||||
pub(crate) fn needs_literals(self) -> bool {
|
||||
matches!(self, Self::InComments | Self::InStringLiterals)
|
||||
}
|
||||
}
|
||||
@@ -160,7 +167,8 @@ pub type PathFilter<'a> = &'a (dyn Fn(&str) -> bool + Sync);
|
||||
pub struct LineMatch {
|
||||
/// 0-based line.
|
||||
pub line: u32,
|
||||
/// Line text, truncated around the match for very long lines.
|
||||
/// 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.
|
||||
pub text: String,
|
||||
/// UTF-16 column ranges within `text`.
|
||||
pub ranges: Vec<(u32, u32)>,
|
||||
@@ -285,7 +293,9 @@ 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, text.as_bytes(), 0, |m| out.push((m.start(), m.end())));
|
||||
iter::for_each_match(&compiled.matcher, compiled.whole_word, text.as_bytes(), 0, |m| {
|
||||
out.push((m.start(), m.end()))
|
||||
});
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
@@ -308,7 +318,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, haystack, &mut caps, |caps| {
|
||||
iter::for_each_captures(matcher, compiled.whole_word, haystack, &mut caps, |caps| {
|
||||
let Some(m) = caps.get(0) else { return };
|
||||
out.extend_from_slice(&haystack[last..m.start()]);
|
||||
last = m.end();
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! 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.
|
||||
//! 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.
|
||||
|
||||
use crate::LineMatch;
|
||||
|
||||
@@ -8,33 +9,57 @@ pub(crate) const MAX_LINE_LEN: usize = 500;
|
||||
/// How much text before the first match a truncated line keeps.
|
||||
const CONTEXT_BEFORE: usize = 100;
|
||||
|
||||
/// `line` excludes the line terminator; `ranges` are sorted, non-overlapping
|
||||
/// 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
|
||||
/// byte ranges within `line`.
|
||||
pub(crate) fn line_match(line_no: u32, line: &[u8], ranges: &[(usize, usize)]) -> LineMatch {
|
||||
pub(crate) fn line_matches(line_no: u32, line: &[u8], ranges: &[(usize, usize)], out: &mut Vec<LineMatch>) {
|
||||
match std::str::from_utf8(line) {
|
||||
Ok(s) => from_str(line_no, s, ranges),
|
||||
Ok(s) => from_str(line_no, s, ranges, out),
|
||||
Err(_) => {
|
||||
let (s, mapped) = lossy(line, ranges);
|
||||
from_str(line_no, &s, &mapped)
|
||||
from_str(line_no, &s, &mapped, out)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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()))))
|
||||
};
|
||||
#[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) {
|
||||
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) {
|
||||
if a > end || (a == end && b > a) || (used > 0 && b > end) {
|
||||
break;
|
||||
}
|
||||
used += 1;
|
||||
let (a, b) = (floor_boundary(s, a.max(start)), ceil_boundary(s, b.min(end)));
|
||||
if a < pos {
|
||||
continue;
|
||||
@@ -45,7 +70,7 @@ fn from_str(line_no: u32, s: &str, ranges: &[(usize, usize)]) -> LineMatch {
|
||||
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 }
|
||||
(LineMatch { line: line_no, text: text.to_owned(), ranges: out, text_offset: text_offset as u32 }, used)
|
||||
}
|
||||
|
||||
/// Byte window `[start, end)` of at most `MAX_LINE_LEN` UTF-16 units that
|
||||
@@ -186,4 +211,30 @@ 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,6 +9,8 @@ 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
|
||||
@@ -19,12 +21,13 @@ 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 }),
|
||||
Ok(matcher) => Ok(Compiled { matcher, multi_line, whole_word }),
|
||||
// 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 }),
|
||||
Ok(matcher) => Ok(Compiled { matcher, multi_line: true, whole_word }),
|
||||
Err(_) => Err(invalid_pattern(query, &err)),
|
||||
},
|
||||
Err(err) => Err(invalid_pattern(query, &err)),
|
||||
@@ -35,7 +38,8 @@ 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)
|
||||
.word(query.whole_word)
|
||||
// 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.
|
||||
.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::{SearchQuery, iter, query};
|
||||
use crate::{LiteralRange, Literals, SearchContext, SearchQuery, iter, query};
|
||||
use grep_matcher::{Captures, Matcher};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult, Pos, Range, TextEdit};
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -128,10 +128,11 @@ pub fn replacement_edits(
|
||||
preserve: bool,
|
||||
only: Option<&[Pos]>,
|
||||
) -> IdeResult<Vec<TextEdit>> {
|
||||
edits_except(text, query, replacement, preserve, only, None)
|
||||
edits_except(text, query, replacement, preserve, only, None, None)
|
||||
}
|
||||
|
||||
/// [`replacement_edits`] leaving out the matches that start at `skip`.
|
||||
/// [`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`].
|
||||
fn edits_except(
|
||||
text: &str,
|
||||
query: &SearchQuery,
|
||||
@@ -139,6 +140,7 @@ 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());
|
||||
@@ -153,10 +155,13 @@ 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, haystack, &mut caps, |caps| {
|
||||
iter::for_each_captures(matcher, compiled.whole_word, 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) {
|
||||
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()))
|
||||
{
|
||||
return;
|
||||
}
|
||||
let mut new_text = if query.is_regex {
|
||||
@@ -227,6 +232,23 @@ 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)?;
|
||||
@@ -244,8 +266,14 @@ pub fn replace_files(
|
||||
if only.is_some_and(|o| o.is_empty()) {
|
||||
continue;
|
||||
}
|
||||
let result =
|
||||
host.edit_file(&target.path, &mut |text| edits_except(text, query, replacement, preserve, only, skip));
|
||||
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())
|
||||
});
|
||||
match result {
|
||||
Ok(n) => {
|
||||
if n > 0 {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult, Pos, TextEdit};
|
||||
use ide_search::{
|
||||
ReplaceEvent, ReplaceHost, ReplaceTarget, SearchQuery, SearchScope, preserve_case, preview, replace_files,
|
||||
replacement_edits,
|
||||
LiteralKind, LiteralRange, ReplaceEvent, ReplaceHost, ReplaceTarget, SearchQuery, SearchScope, preserve_case,
|
||||
preview, replace_files, replace_files_in_context, replacement_edits,
|
||||
};
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
@@ -169,3 +169,46 @@ 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,6 +132,36 @@ 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")]);
|
||||
@@ -431,6 +461,41 @@ 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,6 +315,41 @@ 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,6 +235,12 @@ 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).
|
||||
@@ -245,7 +251,7 @@ fn cli_status(r: &Repo, ignored: &IgnoredNames) -> IdeResult<Entries> {
|
||||
if !crate::execution_allowed() {
|
||||
args.push("--ignore-submodules=dirty");
|
||||
}
|
||||
let out = crate::cli::run(r.root(), &args, None)?;
|
||||
let out = crate::cli::run_env(r.root(), &args, None, &read_only())?;
|
||||
Ok(parse_porcelain_v2(&String::from_utf8_lossy(&out.stdout), ignored))
|
||||
}
|
||||
|
||||
@@ -260,7 +266,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(r.root(), &args, None)?;
|
||||
let out = crate::cli::run_env(r.root(), &args, None, &read_only())?;
|
||||
Ok(parse_porcelain_v2(&String::from_utf8_lossy(&out.stdout), ignored))
|
||||
}
|
||||
|
||||
@@ -397,6 +403,29 @@ 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() {
|
||||
|
||||
@@ -247,8 +247,8 @@ fn event_handler(state: Weak<DirState>, polled: bool) -> impl FnMut(notify::Resu
|
||||
}
|
||||
}
|
||||
|
||||
/// A directory's own mtime moving as entries come and go: polling sees it, the
|
||||
/// OS watchers report only the entries (also seen, through that directory's watch).
|
||||
/// A directory's own mtime moving as entries come and go. Polling also reports
|
||||
/// each changed entry through that directory's watch.
|
||||
fn is_dir_touch(event: ¬ify::Event) -> bool {
|
||||
matches!(event.kind, EventKind::Modify(_)) && event.paths.iter().all(|p| p.is_dir())
|
||||
}
|
||||
@@ -728,6 +728,9 @@ impl EventFilter {
|
||||
Err(_) => None,
|
||||
};
|
||||
let change = match rel.and_then(Self::git_internal) {
|
||||
// Windows also reports a directory modification when Git creates or removes a lock.
|
||||
// The entries carry the actual changes, including edits to a linked worktree's gitfile.
|
||||
Some(true) if change == Change::Modified && path.is_dir() => return,
|
||||
Some(true) => Change::Vcs,
|
||||
Some(false) => return,
|
||||
None if crate::encoding::is_atomic_temp(path) => return,
|
||||
@@ -1330,6 +1333,43 @@ mod tests {
|
||||
assert_eq!(g(".git/objects"), Some(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn git_metadata_directory_touches_do_not_refresh_vcs() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let filter = EventFilter::new(root.clone(), &[]);
|
||||
let modify = EventKind::Modify(ModifyKind::Any);
|
||||
for (dir, lock) in
|
||||
[(".git", "index.lock"), (".git/refs/heads", "main.lock"), (".git/worktrees/wt", "index.lock")]
|
||||
{
|
||||
let dir = root.join(dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let lock = dir.join(lock);
|
||||
let batch = filter.batch(&[
|
||||
ev(EventKind::Create(CreateKind::File), vec![lock.clone()]),
|
||||
ev(EventKind::Remove(RemoveKind::File), vec![lock]),
|
||||
ev(modify, vec![dir.clone()]),
|
||||
]);
|
||||
assert!(batch.is_empty(), "{}: {batch:?}", dir.display());
|
||||
for kind in [EventKind::Create(CreateKind::Folder), EventKind::Remove(RemoveKind::Folder)] {
|
||||
let batch = filter.batch(&[ev(kind, vec![dir.clone()])]);
|
||||
assert_eq!(batch.vcs, vec![dir.clone()]);
|
||||
}
|
||||
}
|
||||
|
||||
let gitfile = root.join("wt/.git");
|
||||
std::fs::create_dir_all(root.join("wt")).unwrap();
|
||||
std::fs::write(&gitfile, "gitdir: ../.git/worktrees/wt\n").unwrap();
|
||||
let index = root.join(".git/index");
|
||||
let head = root.join(".git/refs/heads/main");
|
||||
std::fs::write(&index, b"index data").unwrap();
|
||||
std::fs::write(&head, b"commit id").unwrap();
|
||||
for path in [gitfile, index, head] {
|
||||
let batch = filter.batch(&[ev(modify, vec![path.clone()])]);
|
||||
assert_eq!(batch.vcs, vec![path]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_gitignore_and_rule_changes_in_one_batch() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -422,6 +422,8 @@ 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)?;
|
||||
@@ -501,7 +503,7 @@ impl Documents {
|
||||
});
|
||||
}
|
||||
history.prune(SystemTime::now(), MAX_HISTORY_BYTES, MAX_HISTORY_AGE);
|
||||
self.sink.emit(IdeEvent::WorkspaceEditApplied { id, paths: affected, by_agent });
|
||||
self.sink.emit(IdeEvent::WorkspaceEditApplied { id, paths: affected, moves, by_agent });
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -4,20 +4,13 @@
|
||||
|
||||
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,6 +898,16 @@ 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, LanguageId, NullSink, Pos, Range, TextChange, TextEdit, WorkspaceEdit};
|
||||
use ide_core::{ChangeSet, FileEdit, FileMove, LanguageId, NullSink, Pos, Range, TextChange, TextEdit, WorkspaceEdit};
|
||||
use ide_core::{IdeEvent, error::ErrorKind};
|
||||
use ide_workspace::Documents;
|
||||
use parking_lot::Mutex;
|
||||
@@ -162,6 +162,45 @@ 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,6 +83,8 @@ 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**.
|
||||
@@ -139,6 +141,14 @@ 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 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.
|
||||
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.
|
||||
|
||||
## 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. There is no React-specific tooling beyond that.
|
||||
- **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>`.
|
||||
- **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,4 +109,3 @@ 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,6 +83,8 @@ Codex 有自己的项目信任设置。如果它禁用了当前项目的 `.codex
|
||||
|
||||
在已有对话中,打开**模型 › 刷新模型**即可查找新上线的模型,不会发送消息或更改当前选择。如果 agent 无法直接切换,所选模型会保持待应用状态。提供商返回新模型支持的思考强度后,你就可以选择强度。发送下一条消息时,OpenIDEA 会先恢复原会话并应用所选模型和思考强度,再发送消息。如果无法恢复会话,或原会话不接受其中任何一项,OpenIDEA 会还原之前的选择并提示错误,不会发送该消息。
|
||||
|
||||
已有对话的模型选择器会列出该 agent 当前的模型列表(与新任务使用的相同),外加该对话正在使用的模型。它不依赖该对话会话启动时报告的列表,因此在任一对话或新任务中通过刷新找到的模型,可在该 agent 的所有对话中选用。
|
||||
|
||||
所有内置按键映射中,**聚焦 Agent 输入框** 的默认快捷键都是 macOS 上的 `⌘L`、Windows / Linux 上的 `Ctrl+L`。焦点位于你自己的可输入任务对话中时,无论对话显示在编辑器标签页还是工具窗口中,它都会将焦点移回消息输入框,保留草稿、光标位置和选区;重复按下也不会改变这些内容。它不会发送消息,也不会跳转消息历史。
|
||||
|
||||
焦点位于其他位置时,同一快捷键会跳转到编辑器标签页或工具窗口中显示的任务的消息输入框(显示多个时,选择你最近使用的那个),除非该位置有面板占用此快捷键:在代码编辑器中,`⌘L` / `Ctrl+L` 保留编辑器含义(例如“转到行”);在 Windows / Linux 的终端中,`Ctrl+L` 仍会发送给 shell。此快捷键不适用于已归档任务、子 agent 对话或“新建任务”页面,也不会从打开的弹出窗口或对话框中抢走焦点。要修改或移除绑定,请打开 **设置 › 按键映射 › 智能体 › 聚焦 Agent 输入框**。
|
||||
@@ -139,6 +141,14 @@ 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 文件以及 CSS、SCSS、Less、Sass 中,`⇥` / `Tab` 会展开 Emmet 缩写,例如 `ul>li*3` 或 `m10`。在标记语言文件中,编辑器右键菜单还提供 **使用 Emmet 更新标签**,用一个缩写改写光标所在的标签。
|
||||
在 HTML、Vue、Svelte、JSX、TSX 文件以及 CSS、SCSS、Less、Sass 中,`⇥` / `Tab` 会展开 Emmet 缩写,例如 `ul>li*3` 或 `m10`。在标记语言文件中,编辑器右键菜单还提供 **使用 Emmet 更新标签**,用一个缩写改写光标所在的标签。
|
||||
|
||||
## 编写自己的模板
|
||||
|
||||
|
||||
@@ -96,7 +96,7 @@ Jest 和 Vitest 的输出会解析成测试树,支持 **重新运行失败的
|
||||
|
||||
## 框架支持
|
||||
|
||||
- **React**:JSX 和 TSX 有各自的高亮模式,并获得完整的 TypeScript 服务器支持;除此之外没有 React 专属功能。
|
||||
- **React**:JSX 和 TSX 有各自的高亮模式,并获得完整的 TypeScript 服务器支持。输入 `>` 会自动闭合标签,修改开始或结束标签名会同步修改另一端,补全属性名或在属性名后输入 `=` 会按属性类型插入 `""`(字符串)或 `{}`(其他类型)。在元素的子内容中或 `return` / `=>` 之后,`⇥` / `Tab` 会展开 Emmet 缩写:`.card` 会变成 `<div className="card"></div>`。
|
||||
- **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,4 +109,3 @@ Jest 和 Vitest 的输出会解析成测试树,支持 **重新运行失败的
|
||||
- Bun 可以运行但无法调试:它的 inspector 使用 WebKit 协议,vscode-js-debug 无法附加。
|
||||
- Deno 支持运行和调试,但没有 Deno 语言服务器,Deno 文件使用 TypeScript 服务器。
|
||||
- 不支持 Deno task 的覆盖率。
|
||||
- Emmet 只在 HTML、Vue 和 Svelte 中展开,JSX 中不可用。
|
||||
@@ -0,0 +1,74 @@
|
||||
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();
|
||||
});
|
||||
@@ -0,0 +1,95 @@
|
||||
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,7 +1,18 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import type { BuildModel, BuildTool } from "../src/platform/ipc";
|
||||
import type { BuildModel, BuildTool, MavenDependency } 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: [
|
||||
@@ -17,7 +28,14 @@ const model: BuildModel = {
|
||||
modules: [],
|
||||
aggregated: false,
|
||||
plugins: [],
|
||||
dependencies: [],
|
||||
dependencies: [
|
||||
jsonCore,
|
||||
{
|
||||
...jsonCore,
|
||||
artifactId: "json-mapper",
|
||||
children: [{ ...jsonCore, version: "2.0.0", omitted: "conflict", conflictWith: "2.1.0" }],
|
||||
},
|
||||
],
|
||||
profiles: [],
|
||||
javaVersion: 21,
|
||||
command: "mvn",
|
||||
@@ -97,3 +115,45 @@ 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 });
|
||||
});
|
||||
@@ -0,0 +1,113 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import type { ChangelistState } from "../src/bindings";
|
||||
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
|
||||
|
||||
async function action(page: Page, id: string, arg?: string[]) {
|
||||
await page.evaluate(
|
||||
async ({ id, arg }) => {
|
||||
const actions = "/src/platform/actions.ts";
|
||||
const { executeAction } = await import(/* @vite-ignore */ actions);
|
||||
await executeAction(id, arg);
|
||||
},
|
||||
{ id, arg },
|
||||
);
|
||||
}
|
||||
|
||||
async function savedLists(page: Page) {
|
||||
const last = (await ipcCalls(page, "vcs_changelists_save")).at(-1);
|
||||
return last?.changelists as ChangelistState | undefined;
|
||||
}
|
||||
|
||||
test("changelist forms align the fields and preserve multiline comments through create, edit and move", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 1100, height: 700 });
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async () => {
|
||||
const root = "/dev/acme-api";
|
||||
const vcsModule = "/src/features/vcs/store.ts";
|
||||
const { useVcs } = await import(/* @vite-ignore */ vcsModule);
|
||||
useVcs.setState({
|
||||
available: true,
|
||||
root,
|
||||
repo: root,
|
||||
roots: [root],
|
||||
status: [{ path: root + "/build.gradle.kts", relPath: "build.gradle.kts", staged: null, unstaged: "modified" }],
|
||||
});
|
||||
const listModule = "/src/features/vcs/changelists.ts";
|
||||
const { initialChangelists, useChangelists } = await import(/* @vite-ignore */ listModule);
|
||||
useChangelists.setState({
|
||||
state: { ...initialChangelists(), files: { "build.gradle.kts": "default" } },
|
||||
loaded: true,
|
||||
});
|
||||
window.__ipc.handlers.vcs_changelists_save = () => null;
|
||||
const context = "/src/platform/context.ts";
|
||||
const { setContext } = await import(/* @vite-ignore */ context);
|
||||
setContext("vcsAvailable", true);
|
||||
});
|
||||
|
||||
await action(page, "vcs.changelist.new");
|
||||
const create = page.getByRole("dialog", { name: "New Changelist", exact: true });
|
||||
const name = create.getByRole("textbox", { name: "Name:", exact: true });
|
||||
const comment = create.getByRole("textbox", { name: "Comment:", exact: true });
|
||||
const ok = create.getByRole("button", { name: "OK", exact: true });
|
||||
await expect(name).toBeFocused();
|
||||
await expect(ok).toBeDisabled();
|
||||
const nameLabel = (await create.getByText("Name:", { exact: true }).boundingBox())!;
|
||||
const nameField = (await name.boundingBox())!;
|
||||
expect(nameLabel.x + nameLabel.width).toBeLessThan(nameField.x);
|
||||
const commentLabel = (await create.getByText("Comment:", { exact: true }).boundingBox())!;
|
||||
const commentField = (await comment.boundingBox())!;
|
||||
expect(Math.abs(nameField.x - commentField.x)).toBeLessThan(1);
|
||||
expect(commentLabel.x + commentLabel.width).toBeLessThan(commentField.x);
|
||||
expect(commentField.height).toBeGreaterThan(76);
|
||||
await expect(create.getByText("Name:", { exact: true })).toHaveCSS(
|
||||
"font-size",
|
||||
await name.evaluate((el) => getComputedStyle(el).fontSize),
|
||||
);
|
||||
await name.fill("Changes");
|
||||
await expect(name).toHaveAccessibleDescription(/already exists/);
|
||||
await expect(ok).toBeDisabled();
|
||||
|
||||
await name.fill("Release review");
|
||||
await comment.fill("Review the totals.\nAsk for a second check.");
|
||||
await create.getByRole("checkbox", { name: "Set active" }).check();
|
||||
await ok.click();
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const state = await savedLists(page);
|
||||
return state?.lists.find((list) => list.id === state.active)?.comment;
|
||||
})
|
||||
.toBe("Review the totals.\nAsk for a second check.");
|
||||
|
||||
await action(page, "vcs.changelist.edit");
|
||||
const edit = page.getByRole("dialog", { name: "Edit Changelist", exact: true });
|
||||
await expect(edit.getByRole("textbox", { name: "Name:", exact: true })).toHaveValue("Release review");
|
||||
const editComment = edit.getByRole("textbox", { name: "Comment:", exact: true });
|
||||
await expect(editComment).toHaveValue("Review the totals.\nAsk for a second check.");
|
||||
await expect(edit.getByRole("checkbox", { name: "Set active" })).toBeDisabled();
|
||||
await editComment.fill("Review complete.\nReady for the release checklist.");
|
||||
await edit.getByRole("button", { name: "OK", exact: true }).click();
|
||||
await expect
|
||||
.poll(async () => (await savedLists(page))?.lists.find((list) => list.name === "Release review")?.comment)
|
||||
.toBe("Review complete.\nReady for the release checklist.");
|
||||
|
||||
await action(page, "vcs.changelist.move", ["/dev/acme-api/build.gradle.kts"]);
|
||||
const move = page.getByRole("dialog", { name: "Move Changes to Another Changelist" });
|
||||
await move.getByRole("radio", { name: "New changelist:" }).check();
|
||||
await page.setViewportSize({ width: 400, height: 540 });
|
||||
const newName = move.getByRole("textbox", { name: "Name:", exact: true });
|
||||
const stackedName = (await newName.boundingBox())!;
|
||||
const stackedLabel = (await move.getByText("Name:", { exact: true }).boundingBox())!;
|
||||
expect(stackedLabel.y + stackedLabel.height).toBeLessThanOrEqual(stackedName.y);
|
||||
expect(Math.abs(stackedLabel.x - stackedName.x)).toBeLessThan(1);
|
||||
await newName.fill("Ready to ship");
|
||||
await move.getByRole("textbox", { name: "Comment:", exact: true }).fill("Move the reviewed change here.");
|
||||
await move.getByRole("button", { name: "OK", exact: true }).click();
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const state = await savedLists(page);
|
||||
return state?.lists.find((list) => list.id === state.files?.["build.gradle.kts"])?.name;
|
||||
})
|
||||
.toBe("Ready to ship");
|
||||
});
|
||||
@@ -76,6 +76,34 @@ 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", "table tbody td:first-child"],
|
||||
["notifications", "[role='listbox'] [role='option'] > [class*='notificationGroupLabel']"],
|
||||
["keymap", "[class*='presetLabel']"],
|
||||
["editor.inspections", "[class*='profileControls'] > span:first-child"],
|
||||
["vcs.issueNavigation", "[class*='pageBody'] button:not([aria-label])"],
|
||||
|
||||
@@ -39,3 +39,55 @@ 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();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
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");
|
||||
});
|
||||
@@ -0,0 +1,61 @@
|
||||
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");
|
||||
});
|
||||
@@ -0,0 +1,56 @@
|
||||
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([]);
|
||||
});
|
||||
@@ -0,0 +1,104 @@
|
||||
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();
|
||||
});
|
||||
@@ -0,0 +1,104 @@
|
||||
import { expect, ipcCalls, openFromTree, stubDesktop, test } from "./fixtures";
|
||||
|
||||
test("the file revision chooser previews commit messages and compares the selected revision", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await openFromTree(page, "build.gradle.kts");
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async () => {
|
||||
const root = "/dev/acme-api";
|
||||
const path = `${root}/build.gradle.kts`;
|
||||
const latest = "123abcd000000000000000000000000000000000";
|
||||
const previous = "456efab000000000000000000000000000000000";
|
||||
window.__ipc.handlers.vcs_revision_files = () => ["build.gradle.kts"];
|
||||
window.__ipc.handlers.vcs_log = () => [
|
||||
{
|
||||
id: latest,
|
||||
shortId: "123abcd",
|
||||
author: "Lena Park",
|
||||
timeMs: Date.now(),
|
||||
summary: "Update reviewed totals",
|
||||
message: "Update reviewed totals",
|
||||
messageTruncated: true,
|
||||
},
|
||||
{
|
||||
id: previous,
|
||||
shortId: "456efab",
|
||||
author: "Morgan Chen",
|
||||
timeMs: Date.UTC(2025, 9, 18),
|
||||
summary: "Include October adjustments",
|
||||
message: "Include October adjustments\n\nUse the corrected quantities from the October review.",
|
||||
},
|
||||
];
|
||||
window.__ipc.handlers.vcs_log_details_batch = () => [
|
||||
{ message: "Update reviewed totals\n\nUse the totals reviewed by the release team." },
|
||||
];
|
||||
window.__ipc.handlers.vcs_file_at = () => "val reviewedTotal = 28\n";
|
||||
window.__ipc.handlers.vcs_file_mode = () => "100644";
|
||||
|
||||
const storeModule = "/src/features/vcs/store.ts";
|
||||
const historyModule = "/src/features/vcs/fileRevisions.ts";
|
||||
const contextModule = "/src/platform/context.ts";
|
||||
const actionsModule = "/src/platform/actions.ts";
|
||||
const { useVcs } = await import(/* @vite-ignore */ storeModule);
|
||||
const { hasFileHistory, trackFileHistory } = await import(/* @vite-ignore */ historyModule);
|
||||
const { setContext } = await import(/* @vite-ignore */ contextModule);
|
||||
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
|
||||
useVcs.setState({ roots: [root], heads: { [root]: { headCommit: latest } }, statusLoaded: true });
|
||||
trackFileHistory();
|
||||
await expectFileHistory();
|
||||
setContext("vcsAvailable", true);
|
||||
await executeAction("vcs.compareWithRevision", path);
|
||||
|
||||
async function expectFileHistory() {
|
||||
for (let i = 0; i < 20 && !hasFileHistory(path); i++) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
}
|
||||
if (!hasFileHistory(path)) throw new Error("The sample file has no tracked history");
|
||||
}
|
||||
});
|
||||
|
||||
const chooser = page.getByRole("dialog", { name: "Compare with Revision…" });
|
||||
const search = chooser.getByRole("textbox", { name: "Search file revisions" });
|
||||
const revisions = chooser.getByRole("listbox", { name: "File revisions" });
|
||||
const message = chooser.getByRole("region", { name: "Commit message" });
|
||||
await expect(revisions.getByRole("option")).toHaveCount(2);
|
||||
await expect(message).toContainText("Use the totals reviewed by the release team.");
|
||||
await expect
|
||||
.poll(() => ipcCalls(page, "vcs_log_details_batch"))
|
||||
.toEqual([
|
||||
expect.objectContaining({
|
||||
repo: "/dev/acme-api",
|
||||
revisions: ["123abcd000000000000000000000000000000000"],
|
||||
}),
|
||||
]);
|
||||
|
||||
const firstAuthor = await revisions.getByText("Lena Park", { exact: true }).boundingBox();
|
||||
const secondAuthor = await revisions.getByText("Morgan Chen", { exact: true }).boundingBox();
|
||||
expect(Math.abs(firstAuthor!.x - secondAuthor!.x)).toBeLessThan(1);
|
||||
await search.press("Tab");
|
||||
await expect(message).toBeFocused();
|
||||
await search.press("ArrowDown");
|
||||
await expect(revisions.getByRole("option", { name: /Morgan Chen/ })).toHaveAttribute("aria-selected", "true");
|
||||
await expect(message).toContainText("Use the corrected quantities from the October review.");
|
||||
|
||||
await page.setViewportSize({ width: 480, height: 350 });
|
||||
const listBox = (await revisions.boundingBox())!;
|
||||
const messageBox = (await message.boundingBox())!;
|
||||
expect(messageBox.y).toBeGreaterThanOrEqual(listBox.y + listBox.height - 1);
|
||||
expect(messageBox.y + messageBox.height).toBeLessThanOrEqual(350);
|
||||
await search.fill("unmatched");
|
||||
await expect(revisions).toContainText("No commits");
|
||||
await expect(message).not.toContainText("Use the corrected quantities from the October review.");
|
||||
await search.fill("October adjustments");
|
||||
await expect(revisions.getByRole("option")).toHaveCount(1);
|
||||
await expect(message).toContainText("Use the corrected quantities from the October review.");
|
||||
await search.press("Enter");
|
||||
await expect(chooser).toBeHidden();
|
||||
await expect
|
||||
.poll(() => ipcCalls(page, "vcs_file_at"))
|
||||
.toContainEqual({
|
||||
path: "/dev/acme-api/build.gradle.kts",
|
||||
rev: "456efab000000000000000000000000000000000",
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,69 @@
|
||||
import { expect, openFromTree, stubDesktop, test } from "./fixtures";
|
||||
|
||||
test("Git annotations align dates and full author names at UI text size", async ({ workbench: page }) => {
|
||||
const editor = await openFromTree(page, "build.gradle.kts");
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async () => {
|
||||
const root = "/dev/acme-api";
|
||||
const file = `${root}/build.gradle.kts`;
|
||||
const handlers = window.__ipc.handlers;
|
||||
handlers.vcs_blame = () => [
|
||||
{
|
||||
commit: "a1234567".padEnd(40, "a"),
|
||||
author: "Lena Park",
|
||||
timeMs: Date.UTC(2026, 4, 3, 12),
|
||||
summary: "Update totals",
|
||||
},
|
||||
{
|
||||
commit: "b1234567".padEnd(40, "b"),
|
||||
author: "Lena Ortiz",
|
||||
timeMs: Date.UTC(2026, 8, 23, 12),
|
||||
summary: "Review totals",
|
||||
},
|
||||
];
|
||||
const projectModule = "/src/platform/project.ts";
|
||||
const { useProject } = await import(/* @vite-ignore */ projectModule);
|
||||
const { settings } = useProject.getState();
|
||||
useProject.setState({
|
||||
settings: {
|
||||
...settings,
|
||||
general: { ...settings?.general, dateFormat: { overrideSystem: true, pattern: "d MMMM yyyy" } },
|
||||
},
|
||||
});
|
||||
const storeModule = "/src/features/vcs/store.ts";
|
||||
const { useVcs } = await import(/* @vite-ignore */ storeModule);
|
||||
useVcs.setState({ available: true, root, repo: root, roots: [root] });
|
||||
const contextModule = "/src/platform/context.ts";
|
||||
const { setContext } = await import(/* @vite-ignore */ contextModule);
|
||||
setContext("vcsAvailable", true);
|
||||
const actionsModule = "/src/platform/actions.ts";
|
||||
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
|
||||
await executeAction("vcs.annotate", file);
|
||||
});
|
||||
|
||||
const gutter = editor.locator(".cm-vcs-blame");
|
||||
const first = gutter.locator("[data-commit]").filter({ hasText: "3 May 2026" });
|
||||
const second = gutter.locator("[data-commit]").filter({ hasText: "23 September 2026" });
|
||||
const firstAuthor = first.locator(".cm-vcs-blame-author");
|
||||
const secondAuthor = second.locator(".cm-vcs-blame-author");
|
||||
await expect(firstAuthor).toHaveText("Lena Park");
|
||||
await expect(secondAuthor).toHaveText("Lena Ortiz");
|
||||
await expect
|
||||
.poll(async () => Math.abs((await firstAuthor.boundingBox())!.x - (await secondAuthor.boundingBox())!.x))
|
||||
.toBeLessThan(1);
|
||||
const uiSize = await editor.evaluate((el) => getComputedStyle(el).getPropertyValue("--fs-ui").trim());
|
||||
await expect(firstAuthor).toHaveCSS("font-size", uiSize);
|
||||
|
||||
const firstRevision = first.locator(".cm-vcs-blame-revision");
|
||||
await expect(firstRevision).toBeHidden();
|
||||
await second.click({ button: "right" });
|
||||
await page.getByRole("menuitem", { name: "Options", exact: true }).hover();
|
||||
await page.getByRole("menuitemcheckbox", { name: "Revision", exact: true }).click();
|
||||
await expect(firstRevision).toBeVisible();
|
||||
expect((await firstRevision.boundingBox())!.x).toBeLessThan(
|
||||
(await first.locator(".cm-vcs-blame-date").boundingBox())!.x,
|
||||
);
|
||||
await expect
|
||||
.poll(async () => Math.abs((await firstAuthor.boundingBox())!.x - (await secondAuthor.boundingBox())!.x))
|
||||
.toBeLessThan(1);
|
||||
});
|
||||
Loaded 100 of 331 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user