Порівняти коміти

..
Автор SHA1 Повідомлення Дата
l0ng-ai 7410977c52 fix(vcs): align the directory comparison layout 2026-11-21 01:13:47 +08:00
134 змінених файлів з 708 додано та 14982 видалено

No files matched your search

+14 -178
Переглянути файл
@@ -23,7 +23,7 @@ mod provider;
pub mod registry;
pub mod security;
mod shell;
pub mod skills;
mod skills;
mod timeline;
mod worktree;
@@ -131,19 +131,6 @@ pub type McpServersFn = dyn Fn() -> Vec<McpServer> + Send + Sync;
/// Returns the executable of the running built-in MCP server, if any.
pub type McpExecutableFn = dyn Fn() -> Option<PathBuf> + Send + Sync;
/// The `[agents.skills.<name>]` policies a session resolves against: the user's (global
/// `settings.toml`), the workspace's (`.openidea/settings.toml`), and whether the workspace
/// is trusted (an untrusted one can only turn skills off).
#[derive(Clone, Debug, Default)]
pub struct SkillsPolicy {
pub user: BTreeMap<String, AgentSkillPolicy>,
pub workspace: BTreeMap<String, AgentSkillPolicy>,
pub workspace_trusted: bool,
}
/// Returns the skill policies for this project.
pub type SkillsPolicyFn = dyn Fn() -> SkillsPolicy + Send + Sync;
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
struct CopilotBinaryKey {
command: String,
@@ -169,7 +156,6 @@ 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,
}
@@ -542,8 +528,6 @@ struct Task {
idle_epoch: AtomicU64,
/// Turned on when per-session MCP overrides changed while a turn was busy; dropped once idle.
mcp_reload_pending: AtomicBool,
/// Turned on when per-session skill overrides changed while a turn was busy; dropped once idle.
skills_reload_pending: AtomicBool,
/// Settings already sent this session (`(option, value)`), so a refusal is not retried.
config_sent: Mutex<HashSet<(String, String)>>,
dirty: Mutex<BTreeSet<(Session, usize)>>,
@@ -591,7 +575,6 @@ impl AgentManager {
idle_release_ms: AtomicU64::new(IDLE_RELEASE.as_millis() as u64),
mcp_servers_hook: RwLock::new(None),
mcp_executable_hook: RwLock::new(None),
skills_policy_hook: RwLock::new(None),
attention_seq: AtomicU64::new(0),
});
shared.paths.catalogs.subscribe(&shared);
@@ -741,15 +724,10 @@ impl AgentManager {
*self.shared.mcp_executable_hook.write() = Some(Arc::from(hook));
}
/// Provides the user and workspace skill policies and the workspace's trust.
pub fn set_skills_policy_hook(&self, hook: Box<SkillsPolicyFn>) {
*self.shared.skills_policy_hook.write() = Some(Arc::from(hook));
}
/// The slash commands to complete for `provider`, in `task`'s directory or (without one)
/// in the project: what the agent offered last time there, unadvertised builtins,
/// for Claude Code the skills and custom commands on disk it has not listed (for
/// Hermes, its profile's skills), and the skills hub's active skills for every agent.
/// and, for Claude Code, skills and custom commands on disk it has not listed (for Hermes,
/// its profile's skills).
pub async fn commands(&self, provider: &str, task: Option<&str>) -> IdeResult<Vec<AgentCommand>> {
let (provider, offered, cwd) = match task {
Some(id) => {
@@ -792,44 +770,11 @@ impl AgentManager {
.await?;
return Ok(skills::merge(offered, found));
}
if provider == "claude" || provider == "claude-acp" {
let claude_cwd = cwd.clone();
let found = blocking(move || Ok(skills::discover(&claude_cwd, home.as_deref()))).await?;
offered = skills::merge(offered, found);
if provider != "claude" && provider != "claude-acp" {
return Ok(offered);
}
// The hub's active skills complete on every agent; its `off` ones drop out here,
// which is all the enforcement an ACP agent gets.
let holder = self.task_for_commands(&provider, task);
let states = match holder {
Some(holder) => holder.skill_states().await,
None => {
let (policy, root) = {
let shared = &self.shared;
let policy = shared.skills_policy_hook.read().as_ref().map(|hook| hook()).unwrap_or_default();
(policy, shared.paths.project_root.clone())
};
let home = self.shared.paths.home_dir.clone();
blocking(move || {
Ok(skills::resolve(
skills::discover_skills(&root, home.as_deref()),
None,
&policy.workspace,
&policy.user,
policy.workspace_trusted,
))
})
.await
.unwrap_or_default()
}
};
Ok(skills::menu_commands(offered, &states))
}
/// The task to resolve skills for, when the commands are for one and its provider matches.
fn task_for_commands(&self, provider: &str, task: Option<&str>) -> Option<Arc<Task>> {
let task = self.task(task?).ok()?;
let matches = task.state.lock().task.provider == provider;
matches.then_some(task)
let found = blocking(move || Ok(skills::discover(&cwd, home.as_deref()))).await?;
Ok(skills::merge(offered, found))
}
fn task(&self, id: &str) -> IdeResult<Arc<Task>> {
@@ -913,7 +858,6 @@ impl AgentManager {
retry: None,
background: Box::default(),
mcp_overrides: BTreeMap::new(),
skill_overrides: BTreeMap::new(),
stats: Box::default(),
};
let file = TaskFile {
@@ -1032,7 +976,6 @@ impl AgentManager {
retry: None,
background: Box::default(),
mcp_overrides: req.mcp_overrides,
skill_overrides: req.skill_overrides,
stats: Box::default(),
};
let file = TaskFile {
@@ -1376,14 +1319,13 @@ impl AgentManager {
(s.task.cwd.0.clone(), s.task.provider.clone(), s.task.mcp_overrides.clone())
};
let mcp_servers = source.shared.mcp_servers_for_session(&provider_id, &live.init, &mcp_overrides);
let skills_delivery = source.stage_skills(stage_key(live.driver), &cwd).await;
let cwd_s = dunce::canonicalize(&cwd).unwrap_or(cwd).to_string_lossy().into_owned();
let reply: Value = live
.peer
.request(
"session/fork",
{
let mut params = session_params(&cwd_s, &mcp_servers, skills_delivery.as_ref());
let mut params = session_params(&cwd_s, &mcp_servers);
params["sessionId"] = json!(live.session);
params
},
@@ -1784,7 +1726,6 @@ impl AgentManager {
*task.deleted.lock() = true;
let _ = std::fs::remove_file(self.shared.paths.store_dir.join(format!("{id}.json")));
let _ = std::fs::remove_dir_all(task.turn_dir());
skills::remove_farm(&self.shared.paths.store_dir, id);
let saved = task.state.lock().saved.clone();
if let Some(saved) = saved
&& !self.tasks.read().values().any(|t| t.state.lock().saved.as_ref() == Some(&saved))
@@ -2046,38 +1987,6 @@ impl AgentManager {
Ok(out)
}
/// Sets the session's skill modes; like MCP overrides, a change reaches the agent when
/// its idle session is recycled and the next turn starts fresh.
pub fn set_skill_overrides(&self, id: &str, overrides: BTreeMap<String, AgentSkillMode>) -> IdeResult<AgentTask> {
let task = self.task(id)?;
let cleaned: BTreeMap<String, AgentSkillMode> = overrides
.into_iter()
.filter_map(|(k, v)| (!k.trim().is_empty()).then(|| (k.trim().to_owned(), v)))
.collect();
let (changed, busy, has_bg, out) = {
let mut s = task.state.lock();
if s.task.status == AgentStatus::Archived {
return Err(IdeError::invalid("the task is archived"));
}
let changed = s.task.skill_overrides != cleaned;
if changed {
s.task.skill_overrides = cleaned;
s.task.updated_ms = now_ms();
}
(changed, s.busy, !s.background_tasks.is_empty(), s.task.clone())
};
if changed {
task.persist();
task.emit_task();
if busy || has_bg || !task.permissions.lock().is_empty() {
task.skills_reload_pending.store(true, Ordering::Release);
} else {
task.recycle_resumable_session();
}
}
Ok(out)
}
/// Recycles idle resumable live sessions (or schedules reload after the running turn) when
/// global, workspace, or built-in IDE MCP server settings change.
pub fn notify_mcp_servers_changed(&self) {
@@ -2110,55 +2019,6 @@ impl AgentManager {
}
impl Task {
/// The skills offered in this project: every discovery resolved against the policies
/// and the task's overrides.
async fn skill_states(&self) -> Vec<AgentSkillState> {
let (policy, overrides, home, root) = {
let shared = &self.shared;
let policy = shared.skills_policy_hook.read().as_ref().map(|hook| hook()).unwrap_or_default();
let overrides = self.state.lock().task.skill_overrides.clone();
(policy, overrides, shared.paths.home_dir.clone(), shared.paths.project_root.clone())
};
blocking(move || {
Ok(skills::resolve(
skills::discover_skills(&root, home.as_deref()),
Some(&overrides),
&policy.workspace,
&policy.user,
policy.workspace_trusted,
))
})
.await
.unwrap_or_default()
}
/// Stages the session's skills into the task's farm and reports what its CLI takes.
/// Nothing staged for an ACP agent (its `/` menu is filtered instead), and a failed
/// stage (locked files, full disk) runs the session without the farm.
async fn stage_skills(&self, provider: &str, cwd: &Path) -> Option<skills::Delivery> {
let states = self.skill_states().await;
let (farm, home, out_cwd) = {
(
skills::farm_dir(&self.shared.paths.store_dir, &self.id),
self.shared.paths.home_dir.clone(),
cwd.to_path_buf(),
)
};
let provider = provider.to_owned();
match blocking(move || {
skills::stage(&farm, &provider, &states, &out_cwd, home.as_deref())
.map_err(|e| IdeError::internal(e.to_string()))
})
.await
{
Ok(delivery) => Some(delivery),
Err(e) => {
tracing::warn!("agent task {}: staging its skills failed: {e}", self.id);
None
}
}
}
fn restore(file: TaskFile, shared: Arc<Shared>) -> Arc<Self> {
let mut task = file.task;
config::add_client_options(&task.provider, &mut task.config);
@@ -2215,7 +2075,6 @@ impl Task {
turns: AtomicU64::new(0),
idle_epoch: AtomicU64::new(0),
mcp_reload_pending: AtomicBool::new(false),
skills_reload_pending: AtomicBool::new(false),
config_sent: Mutex::new(HashSet::new()),
dirty: Mutex::new(BTreeSet::new()),
streamed: Mutex::new(HashMap::new()),
@@ -2507,8 +2366,7 @@ impl Task {
if stop != "cancelled" {
self.emit_attention(AgentAttentionReason::Finished);
}
if (self.mcp_reload_pending.swap(false, Ordering::AcqRel)
|| self.skills_reload_pending.swap(false, Ordering::AcqRel))
if self.mcp_reload_pending.swap(false, Ordering::AcqRel)
&& self.state.lock().background_tasks.is_empty()
{
self.recycle_resumable_session();
@@ -3026,7 +2884,6 @@ impl Task {
let (capabilities, embedded) = capabilities_of(&init);
let mcp_overrides = self.state.lock().task.mcp_overrides.clone();
let mcp_servers = self.shared.mcp_servers_for_session(provider_id, &init, &mcp_overrides);
let skills_delivery = self.stage_skills(stage_key(spec.driver), cwd).await;
// Agents that compare canonical paths fail in a symlinked directory (macOS `/tmp`).
let cwd_s = dunce::canonicalize(cwd).unwrap_or_else(|_| cwd.to_path_buf()).to_string_lossy().into_owned();
@@ -3041,7 +2898,7 @@ impl Task {
}
if let (Some(id), true, false) = (saved, can_load, start_fresh) {
self.replaying.store(true, Ordering::Release);
let mut params = session_params(&cwd_s, &mcp_servers, skills_delivery.as_ref());
let mut params = session_params(&cwd_s, &mcp_servers);
params["sessionId"] = json!(&id);
let loaded = self.request_with_auth(&peer, &init, &mut tried_auth, "session/load", params).await;
tokio::time::sleep(REPLAY_GRACE).await;
@@ -3081,7 +2938,7 @@ impl Task {
let (session_id, result) = match session {
Some(s) => s,
None => {
let params = session_params(&cwd_s, &mcp_servers, skills_delivery.as_ref());
let params = session_params(&cwd_s, &mcp_servers);
let v = self.request_with_auth(&peer, &init, &mut tried_auth, "session/new", params).await.map_err(
|e| match self.sign_in_error(&e, Some(&sign_in_message)) {
Some(msg) => SessionOpenError { message: msg, allow_acp_fallback: false },
@@ -4057,34 +3914,13 @@ struct McpForSession {
off: Vec<String>,
}
/// The driver a session's staged skills are staged for (`skills::stage` matches on it):
/// the native CLIs take the farm, everything else (an ACP agent) gets the `/` menu filter.
fn stage_key(driver: provider::Driver) -> &'static str {
match driver {
provider::Driver::Claude => "claude",
provider::Driver::Codex => "codex",
provider::Driver::Copilot => "copilot",
provider::Driver::Acp => "acp",
}
}
/// The session parameters `session/new`, `session/load` and `session/fork` share: the MCP
/// servers, and the ones off for this session, so an agent that also loads its own
/// configuration (Claude Code) can keep a same-named server of it off too — plus the
/// session's staged skills for the drivers that take them.
fn session_params(cwd: &str, mcp: &McpForSession, skills: Option<&skills::Delivery>) -> Value {
/// configuration (Claude Code) can keep a same-named server of it off too.
fn session_params(cwd: &str, mcp: &McpForSession) -> Value {
let mut params = json!({ "cwd": cwd, "mcpServers": mcp.servers });
let mut meta = json!({});
if !mcp.off.is_empty() {
meta["mcpServersOff"] = json!(mcp.off);
}
if let Some(skills) = skills
&& let Ok(v) = serde_json::to_value(skills)
{
meta["skills"] = v;
}
if !meta.is_null() && meta.as_object().is_some_and(|m| !m.is_empty()) {
params["_meta"] = json!({ "openidea": meta });
params["_meta"] = json!({ "openidea": { "mcpServersOff": mcp.off } });
}
params
}
-84
Переглянути файл
@@ -110,9 +110,6 @@ pub struct AgentTask {
/// Per-session MCP server enable/disable overrides (`server_name` -> `enabled`), including `"openidea"`.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub mcp_overrides: BTreeMap<String, bool>,
/// Per-session skill modes (`skill name` -> mode), on top of the settings' policies.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub skill_overrides: BTreeMap<String, AgentSkillMode>,
/// Token counts of the last turn and context compressions, when the agent reports them.
// Boxed so that `AgentEvent::Task` stays within clippy's `large_enum_variant` bound on Windows.
#[serde(default)]
@@ -690,9 +687,6 @@ pub struct NewAgentTask {
/// Per-session MCP server enable/disable overrides (`server_name` -> `enabled`).
#[serde(default)]
pub mcp_overrides: BTreeMap<String, bool>,
/// Per-session skill modes (`skill name` -> mode).
#[serde(default)]
pub skill_overrides: BTreeMap<String, AgentSkillMode>,
/// Creates the task without sending `prompt` (it only names the task): the composer's
/// `!` command runs in it first.
#[serde(default)]
@@ -885,84 +879,6 @@ fn default_true() -> bool {
true
}
pub use ide_core::settings::{AgentSkillMode, AgentSkillPolicy};
/// Which CLI's own folders a skill was discovered in (Settings › Agents › Skills groups by it).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentSkillSource {
/// The project's `.agents/skills` and `.openidea/skills`.
#[default]
Workspace,
/// The user's `~/.agents/skills` (what `npx skills add` fills).
User,
/// The project's `.claude/skills`.
ClaudeWorkspace,
/// `~/.claude/skills`.
ClaudeUser,
/// The project's `.github/skills` (Copilot's repository skills).
GithubWorkspace,
/// `~/.copilot/skills` and `~/.copilot/installed-plugins/*`.
CopilotUser,
/// The project's `.codex/skills`.
CodexWorkspace,
/// `~/.codex/skills`.
CodexUser,
/// The project's `.cursor/skills`.
CursorWorkspace,
/// `~/.cursor/skills`.
CursorUser,
}
impl AgentSkillSource {
/// Whether skills of this source are only read, never delivered by OpenIDEA: the CLI
/// discovers them itself, so "off" holds only where the CLI supports a native disable.
pub fn discovered(&self) -> bool {
!matches!(self, Self::Workspace | Self::User)
}
}
/// One discovered skill: a folder with a `SKILL.md`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentSkill {
/// The frontmatter `name`, else the folder's name.
pub name: String,
pub description: String,
/// Canonical folder holding `SKILL.md` (symlinks resolved, so duplicates collapse).
pub path: IpcPath,
pub source: AgentSkillSource,
/// The `SKILL.md` passes validation (`name` matches its folder, `description` present).
pub valid: bool,
/// What validation found (`name` mismatch, missing or over-long description…).
pub warnings: Vec<String>,
}
/// A skill as Settings › Agents › Skills shows it: discovery plus the effective mode and
/// which layer decided it.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentSkillState {
pub skill: AgentSkill,
pub mode: AgentSkillMode,
/// What set `mode`: a session override, the workspace, the user's settings, workspace
/// trust, or nothing (the default `auto`).
pub origin: AgentSkillOrigin,
}
/// Which layer decided a skill's [`AgentSkillState::mode`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentSkillOrigin {
#[default]
None,
Session,
Workspace,
User,
/// An untrusted workspace's skills and policies may only turn skills off.
Trust,
}
/// An external MCP configuration file discovered on disk (user CLI config or workspace file).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
-15
Переглянути файл
@@ -172,10 +172,6 @@ struct Session {
mcp_config: Option<tempfile::TempPath>,
/// MCP servers switched off for this session (`--disallowedTools`), its own config's too.
mcp_off: Vec<String>,
/// The staged skills folder passed as `--add-dir` (its `.claude/skills` holds the copies).
skills_add_dir: Option<PathBuf>,
/// The staged skills' `--settings` JSON (`skillOverrides` for the native ones too).
skills_settings: Option<String>,
shim: Weak<Shim>,
st: Mutex<State>,
/// Serializes (re)starting the process.
@@ -360,13 +356,10 @@ impl Shim {
None
}
});
let skills = params.pointer("/_meta/openidea/skills");
let session = Arc::new(Session {
id: id.to_owned(),
mcp_config,
mcp_off,
skills_add_dir: skills.and_then(|s| s.get("claudeAddDir")).and_then(Value::as_str).map(PathBuf::from),
skills_settings: skills.and_then(|s| s.get("claudeSettings")).and_then(Value::as_str).map(str::to_owned),
shim: Arc::downgrade(self),
st: Mutex::new(State {
proc: None,
@@ -680,14 +673,6 @@ impl Session {
if !self.mcp_off.is_empty() {
args.extend(["--disallowedTools".to_owned(), self.mcp_off.join(",")]);
}
// The staged skills: `.claude/skills` of the added directory is discovered like the
// project's own, and the settings hold the modes of the skills it sees natively too.
if let Some(dir) = &self.skills_add_dir {
args.extend(["--add-dir".to_owned(), dir.to_string_lossy().into_owned()]);
}
if let Some(settings) = &self.skills_settings {
args.extend(["--settings".to_owned(), settings.clone()]);
}
args.extend(start.args());
let launch =
Launch { program: shim.config.program.clone(), args, cwd: self.cwd.clone(), env: shim.config.env.clone() };
+9 -56
Переглянути файл
@@ -334,31 +334,6 @@ fn str_param<'a>(params: &'a Value, key: &str) -> Result<&'a str, ResponseError>
params.get(key).and_then(Value::as_str).ok_or_else(|| invalid(format!("missing {key}")))
}
/// Fills a `thread/start`/`thread/resume`/`thread/fork` request's `config` with the session's
/// MCP servers and its staged skills: the off ones, by path (`skills.config` entries with
/// `enabled = false`, which the CLI honors for the copies it discovers natively too).
fn apply_thread_config(params: &Value, request: &mut Value) {
let mut config = translate::mcp_config(params).unwrap_or_else(|| json!({}));
let off: Vec<Value> = params
.pointer("/_meta/openidea/skills/codexOff")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(|entry| {
let path = entry.get(1)?.as_str()?;
Some(json!({ "path": path, "enabled": false }))
})
.collect();
if !off.is_empty()
&& let Some(map) = config.as_object_mut()
{
map.insert("skills".into(), json!({ "config": off }));
}
if !config.as_object().is_some_and(|m| m.is_empty()) {
request["config"] = config;
}
}
impl CodexShim {
fn codex(&self) -> &Peer {
self.codex.get().expect("attached before any message")
@@ -439,31 +414,6 @@ impl CodexShim {
}
}
/// Hands the session's staged skills to the app-server: the farm's `codex` tree joins
/// its discovery roots. Best-effort: a CLI version without `skills/extraRoots/set`
/// (the method arrived later than some pinned installs) runs without the farm, as
/// before.
async fn apply_skill_roots(&self, session: &str, params: &Value) {
let roots = params
.pointer("/_meta/openidea/skills/codexExtraRoots")
.and_then(Value::as_array)
.map(|a| a.iter().filter_map(Value::as_str).collect::<Vec<_>>())
.unwrap_or_default();
if roots.is_empty() {
return;
}
let set = tokio::time::timeout(
Duration::from_secs(5),
self.call("skills/extraRoots/set", json!({ "extraRoots": roots })),
)
.await;
match set {
Ok(Ok(_)) => {}
Ok(Err(e)) => tracing::info!("codex session {session}: could not set the extra skill roots: {}", e.message),
Err(e) => tracing::info!("codex session {session}: could not set the extra skill roots: {e}"),
}
}
/// Registers a thread codex opened for a session of its own; returns its `configOptions`.
fn open_thread(&self, result: &Value, models: &[ModelInfo], settings: Option<Settings>) -> (String, Value) {
let thread = result.get("thread").unwrap_or(&Value::Null);
@@ -484,13 +434,14 @@ impl CodexShim {
let models = self.models().await?;
self.prepare_project_trust(params).await;
let mut request = json!({ "cwd": params.get("cwd") });
apply_thread_config(params, &mut request);
if let Some(config) = translate::mcp_config(params) {
request["config"] = config;
}
let result = self.call("thread/start", request).await?;
let (id, options) = self.open_thread(&result, &models, None);
if id.is_empty() {
return Err(error(codes::INTERNAL_ERROR, "codex started no thread"));
}
self.apply_skill_roots(&id, params).await;
self.publish_skills(&id).await;
Ok(json!({ "sessionId": id, "configOptions": options }))
}
@@ -501,7 +452,9 @@ impl CodexShim {
let models = self.models().await?;
self.prepare_project_trust(params).await;
let mut request = json!({ "threadId": id, "cwd": params.get("cwd") });
apply_thread_config(params, &mut request);
if let Some(config) = translate::mcp_config(params) {
request["config"] = config;
}
let result = self.call("thread/resume", request).await?;
let (_, options) = self.open_thread(&result, &models, None);
let cwd = self.state.lock().threads.get(id).and_then(|t| t.cwd.clone());
@@ -509,7 +462,6 @@ impl CodexShim {
for update in translate::history(thread, cwd.as_deref()) {
self.emit(id, update);
}
self.apply_skill_roots(id, params).await;
self.publish_skills(id).await;
Ok(json!({ "configOptions": options }))
}
@@ -520,7 +472,9 @@ impl CodexShim {
self.prepare_project_trust(params).await;
let settings = self.state.lock().threads.get(source).and_then(|t| t.settings.clone());
let mut request = json!({ "threadId": source, "cwd": params.get("cwd") });
apply_thread_config(params, &mut request);
if let Some(config) = translate::mcp_config(params) {
request["config"] = config;
}
if let Some(s) = &settings {
request["model"] = json!(s.model_slug(&models));
request["approvalPolicy"] = json!(s.mode.approval_policy());
@@ -528,7 +482,6 @@ impl CodexShim {
}
let result = self.call("thread/fork", request).await?;
let (id, options) = self.open_thread(&result, &models, settings);
self.apply_skill_roots(&id, params).await;
self.publish_skills(&id).await;
Ok(json!({ "sessionId": id, "configOptions": options }))
}
-20
Переглянути файл
@@ -372,24 +372,6 @@ fn error(code: i64, message: impl Into<String>) -> ResponseError {
ResponseError { code, message: message.into(), data: None }
}
/// Adds the session's staged skills to a `session.create`/`session.resume` request:
/// `skillDirectories` (the farm's `copilot` tree) and `disabledSkills` (the off and
/// slash-only ones; Copilot invokes skills with the model only, so a slash-only skill has
/// no other switch here).
fn apply_skills(params: &Value, req: &mut Value) {
let skills = params.pointer("/_meta/openidea/skills");
if let Some(dirs) = skills.and_then(|s| s.get("copilotSkillDirectories")).and_then(Value::as_array)
&& !dirs.is_empty()
{
req["skillDirectories"] = json!(dirs.iter().filter_map(Value::as_str).collect::<Vec<_>>());
}
if let Some(disabled) = skills.and_then(|s| s.get("copilotDisabledSkills")).and_then(Value::as_array)
&& !disabled.is_empty()
{
req["disabledSkills"] = json!(disabled.iter().filter_map(Value::as_str).collect::<Vec<_>>());
}
}
fn invalid(message: impl Into<String>) -> ResponseError {
error(codes::INVALID_PARAMS, message)
}
@@ -514,7 +496,6 @@ impl CopilotShim {
if let Some(disabled) = translate::wire_disabled_mcp_servers(params) {
req["disabledMcpServers"] = disabled;
}
apply_skills(params, &mut req);
let created = self.call("session.create", req).await?;
let session_id = created
@@ -565,7 +546,6 @@ impl CopilotShim {
if let Some(disabled) = translate::wire_disabled_mcp_servers(params) {
req["disabledMcpServers"] = disabled;
}
apply_skills(params, &mut req);
let resumed = self.call("session.resume", req).await?;
if let Ok(current) = self.call("session.model.getCurrent", json!({ "sessionId": session_id })).await {
+7 -604
Переглянути файл
@@ -1,17 +1,11 @@
//! Slash commands and skills on disk. Claude Code's own discovery (`.claude/skills` and
//! `.claude/commands` of the working directory tree and `~/.claude`, and a Hermes profile's
//! `skills`) for completion before (or without) a session, plus the multi-level skills hub
//! of #3897: every CLI's skill folders discovered once, deduplicated by canonical path,
//! resolved against the `[agents.skills.<name>]` policies of the global and workspace
//! settings, and staged into a per-session folder the CLIs each receive their own way.
//! Claude Code's slash commands on disk, for completion before (or without) a session:
//! skills (`.claude/skills/<dir>/SKILL.md`) and custom commands (`.claude/commands/**/*.md`)
//! of the working directory and every directory above it, then the user's `~/.claude`; and
//! the skills of a Hermes profile (`<profile>/skills`).
use crate::{
AgentCommand, AgentCommandSource, AgentSkill, AgentSkillMode, AgentSkillOrigin, AgentSkillPolicy, AgentSkillSource,
AgentSkillState,
};
use ide_core::output_encoding::strip_ansi;
use std::collections::{BTreeMap, HashSet};
use std::path::{Path, PathBuf};
use crate::{AgentCommand, AgentCommandSource};
use std::collections::HashSet;
use std::path::Path;
const MAX_DESCRIPTION: usize = 200;
/// Command directories nest this deep at most (`a/b/c.md` → `a:b:c`).
@@ -206,370 +200,6 @@ fn truncate(s: &str) -> String {
}
}
// ─── The skills hub (#3897): discovery, policy, delivery ────────────────────────────
/// A skill's `name` must be this and lowercase letters, digits and hyphens only.
fn valid_name(name: &str) -> bool {
(1..=64).contains(&name.len()) && name.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
}
/// A `SKILL.md`'s description is at most this many characters.
const MAX_SKILL_DESCRIPTION: usize = 1024;
/// The workspace folders skills are discovered in, by the source they report.
const WORKSPACE_ROOTS: &[(&str, AgentSkillSource)] = &[
(".agents/skills", AgentSkillSource::Workspace),
(".openidea/skills", AgentSkillSource::Workspace),
(".claude/skills", AgentSkillSource::ClaudeWorkspace),
(".github/skills", AgentSkillSource::GithubWorkspace),
(".codex/skills", AgentSkillSource::CodexWorkspace),
(".cursor/skills", AgentSkillSource::CursorWorkspace),
];
/// The home folders skills are discovered in, by the source they report.
const HOME_ROOTS: &[(&str, AgentSkillSource)] = &[
(".agents/skills", AgentSkillSource::User),
(".claude/skills", AgentSkillSource::ClaudeUser),
(".copilot/skills", AgentSkillSource::CopilotUser),
(".codex/skills", AgentSkillSource::CodexUser),
(".cursor/skills", AgentSkillSource::CursorUser),
];
/// Every skill found under `workspace` (a project, scanned even for a worktree task, whose
/// checkout lacks untracked skills) and `home`, in source precedence order, symlinked
/// duplicates collapsed by canonical path: the first of a path wins, and so does the first
/// of a name (the higher source), so a session never sees one skill twice.
pub fn discover_skills(workspace: &Path, home: Option<&Path>) -> Vec<AgentSkill> {
let mut out: Vec<AgentSkill> = Vec::new();
let mut seen_paths: HashSet<PathBuf> = HashSet::new();
let mut seen_names: HashSet<String> = HashSet::new();
let mut roots: Vec<(PathBuf, AgentSkillSource)> = Vec::new();
roots.extend(WORKSPACE_ROOTS.iter().map(|(rel, source)| (workspace.join(rel), *source)));
let mut plugin_roots = Vec::new();
if let Some(home) = home {
roots.extend(HOME_ROOTS.iter().map(|(rel, source)| (home.join(rel), *source)));
// `copilot install` unpacks plugins under `installed-plugins/<plugin>/`, whose skills
// sit in a `skills` folder (or directly in the plugin folder).
let plugins = home.join(".copilot/installed-plugins");
if let Ok(plugins) = plugins.read_dir() {
for plugin in plugins.flatten() {
if plugin.path().is_dir() {
plugin_roots.push((plugin.path().join("skills"), AgentSkillSource::CopilotUser));
plugin_roots.push((plugin.path(), AgentSkillSource::CopilotUser));
}
}
}
}
roots.extend(plugin_roots);
for (root, source) in roots {
for skill in skills_of(&root, source) {
let path = dunce::canonicalize(&skill.path.0).unwrap_or_else(|_| skill.path.0.clone());
if !seen_paths.insert(path.clone()) || !seen_names.insert(skill.name.clone()) {
continue;
}
out.push(AgentSkill { path: path.into(), ..skill });
}
}
out
}
/// The skills of one root: `<name>/SKILL.md` folders, validated.
fn skills_of(root: &Path, source: AgentSkillSource) -> Vec<AgentSkill> {
let mut out: Vec<AgentSkill> = Vec::new();
let Ok(entries) = std::fs::read_dir(root) else { return out };
for entry in entries.flatten() {
let dir = entry.path();
let Some(folder) = dir.file_name().and_then(|n| n.to_str()).map(str::to_owned) else { continue };
if !dir.is_dir() || folder.starts_with('.') {
continue;
}
let Ok(text) = std::fs::read_to_string(dir.join("SKILL.md")) else { continue };
let meta = Frontmatter::parse(&text);
let name = meta.get("name").filter(|n| !n.is_empty()).map(str::to_owned).unwrap_or_else(|| folder.clone());
let mut warnings = Vec::new();
if !valid_name(&name) {
warnings.push(format!("`name: {name}` is not 1-64 lowercase letters, digits or hyphens"));
}
if name != folder {
warnings.push(format!("`name: {name}` does not match the folder `{folder}`"));
}
let description = meta.get("description").unwrap_or_default();
let description = strip_ansi(description).trim().to_owned();
if description.is_empty() {
warnings.push("no `description`: the model never sees when to use it".into());
} else if description.chars().count() > MAX_SKILL_DESCRIPTION {
warnings.push(format!("`description` is over {MAX_SKILL_DESCRIPTION} characters"));
}
out.push(AgentSkill {
name,
description: truncate(&description),
path: dir.into(),
source,
valid: warnings.is_empty(),
warnings,
});
}
out.sort_by(|a, b| a.name.cmp(&b.name));
out
}
/// A skill's mode, as one policy layer of the settings has it.
type Policies = BTreeMap<String, AgentSkillPolicy>;
/// Resolves every skill's mode: a session override, then the workspace's and the user's
/// `[agents.skills.<name>]` policy, then the default `auto` — with an untrusted workspace
/// able to turn skills off only: its own skills stay off (whatever the session chose), and
/// its policies hold only when they turn a skill off.
pub fn resolve(
skills: Vec<AgentSkill>,
session: Option<&BTreeMap<String, AgentSkillMode>>,
workspace: &Policies,
user: &Policies,
workspace_trusted: bool,
) -> Vec<AgentSkillState> {
let mut out = Vec::new();
for skill in skills {
let workspace_skill = matches!(
skill.source,
AgentSkillSource::Workspace
| AgentSkillSource::ClaudeWorkspace
| AgentSkillSource::GithubWorkspace
| AgentSkillSource::CodexWorkspace
| AgentSkillSource::CursorWorkspace
);
let (mode, origin) = if workspace_skill && !workspace_trusted {
// Workspace trust gates the workspace's own skills, whatever else says.
(AgentSkillMode::Off, AgentSkillOrigin::Trust)
} else if let Some(chosen) = session.and_then(|s| s.get(&skill.name)) {
(*chosen, AgentSkillOrigin::Session)
} else if let Some(policy) =
workspace.get(&skill.name).filter(|p| workspace_trusted || p.mode == AgentSkillMode::Off)
{
(policy.mode, AgentSkillOrigin::Workspace)
} else if let Some(policy) = user.get(&skill.name) {
(policy.mode, AgentSkillOrigin::User)
} else {
(AgentSkillMode::Auto, AgentSkillOrigin::None)
};
out.push(AgentSkillState { skill, mode, origin });
}
out
}
/// What one CLI session receives for its active skills. Sent to the shims in
/// `session/new`'s `_meta.openidea.skills`, so each driver applies its own fields.
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub struct Delivery {
/// Claude Code: the farm passed as `--add-dir` (its `.claude/skills` holds the staged copies).
#[serde(skip_serializing_if = "Option::is_none")]
pub claude_add_dir: Option<PathBuf>,
/// Claude Code: the `--settings` JSON with `skillOverrides` (the native skills too).
#[serde(skip_serializing_if = "Option::is_none")]
pub claude_settings: Option<String>,
/// Copilot: `skillDirectories` (the farm's `copilot` tree).
#[serde(skip_serializing_if = "Vec::is_empty")]
pub copilot_skill_directories: Vec<String>,
/// Copilot: `disabledSkills`, spelled as the skills are.
#[serde(skip_serializing_if = "Vec::is_empty")]
pub copilot_disabled_skills: Vec<String>,
/// Codex: `skills/extraRoots/set` roots (the farm's `codex` tree).
#[serde(skip_serializing_if = "Vec::is_empty")]
pub codex_extra_roots: Vec<String>,
/// Codex: `skills.config` entries turning skills off by path.
#[serde(skip_serializing_if = "Vec::is_empty")]
pub codex_off: Vec<(String, String)>,
}
/// Stages the skills a session of `provider` runs with into `farm` — linking (copying on
/// Windows, where directory symlinks need Developer Mode) every active skill folder into
/// the CLI's tree — and reports what to hand the CLI. Skills the CLI discovers natively
/// (its own folders of the working directory and the home) are not staged again: it already
/// sees them, and seeing both would list one skill twice. Skills `off` are never staged;
/// the CLI's native disable (where it has one) receives their names or paths. An ACP
/// agent gets nothing here: its `/` menu is filtered instead.
pub fn stage(
farm: &Path,
provider: &str,
states: &[AgentSkillState],
cwd: &Path,
home: Option<&Path>,
) -> std::io::Result<Delivery> {
let mut out = Delivery::default();
let cwd = dunce::canonicalize(cwd).unwrap_or_else(|_| cwd.to_path_buf());
// Only the native drivers take the farm, each its own tree; `provider` is their key
// (`claude`, `copilot`, `codex`), anything else (an ACP agent) gets the `/` menu filter.
let (claude_tree, copilot_tree, codex_tree) = match provider {
"claude" => (Some(farm.join(".claude/skills")), None, None),
"copilot" => (None, Some(farm.join("copilot")), None),
"codex" => (None, None, Some(farm.join("codex"))),
_ => return Ok(out),
};
// Restage from scratch: a skill turned off or deleted since the last session must not
// linger in the tree. Removing a tree removes its links, never the skills they point at.
for tree in [&claude_tree, &copilot_tree, &codex_tree].into_iter().flatten() {
match std::fs::remove_dir_all(tree) {
Err(e) if e.kind() != std::io::ErrorKind::NotFound => return Err(e),
_ => {}
}
}
for state in states {
let name = state.skill.name.as_str();
let path = state.skill.path.0.as_path();
match state.mode {
AgentSkillMode::Off => {
out.codex_off.push((name.to_owned(), state.skill.path.to_string_lossy().into_owned()));
}
// Claude Code runs a slash-only skill on `/name`, so it has to see the folder;
// Copilot and Codex have no such mode and get it disabled or left out.
AgentSkillMode::SlashOnly => {
if let Some(tree) = claude_tree.as_ref().filter(|_| !native_claude(&state.skill, &cwd, home)) {
link_skill(&tree.join(name), path)?;
}
}
AgentSkillMode::Auto => {
if let Some(tree) = claude_tree.as_ref().filter(|_| !native_claude(&state.skill, &cwd, home)) {
link_skill(&tree.join(name), path)?;
}
if let Some(tree) = copilot_tree.as_ref().filter(|_| !native_copilot(&state.skill, &cwd, home)) {
link_skill(&tree.join(name), path)?;
}
if let Some(tree) = codex_tree.as_ref().filter(|_| !native_codex(&state.skill, &cwd, home)) {
link_skill(&tree.join(name), path)?;
}
}
}
}
if claude_tree.as_ref().is_some_and(|t| t.exists()) {
out.claude_add_dir = Some(farm.to_path_buf());
}
if let Some(tree) = copilot_tree.as_ref().filter(|t| t.exists()) {
out.copilot_skill_directories.push(tree.to_string_lossy().into_owned());
}
if let Some(tree) = codex_tree.as_ref().filter(|t| t.exists()) {
out.codex_extra_roots.push(tree.to_string_lossy().into_owned());
}
// Claude Code's `skillOverrides` and Copilot's `disabledSkills` take the names of the
// off and slash-only skills — the native copies included.
let off: Vec<&str> =
states.iter().filter(|s| s.mode == AgentSkillMode::Off).map(|s| s.skill.name.as_str()).collect();
let slash: Vec<&str> =
states.iter().filter(|s| s.mode == AgentSkillMode::SlashOnly).map(|s| s.skill.name.as_str()).collect();
if !off.is_empty() || !slash.is_empty() {
let mut overrides = serde_json::Map::new();
for (name, mode) in off.iter().map(|n| (*n, "off")).chain(slash.iter().map(|n| (*n, "user-invocable-only"))) {
overrides.insert(name.to_owned(), serde_json::Value::String(mode.to_owned()));
}
out.claude_settings = Some(
serde_json::to_string(&serde_json::json!({ "skillOverrides": overrides })).expect("settings serialize"),
);
out.copilot_disabled_skills = off.iter().chain(slash.iter()).map(|n| (*n).to_owned()).collect();
out.copilot_disabled_skills.sort();
}
Ok(out)
}
/// Claude Code sees this skill without the farm: its own `.claude/skills` of the working
/// directory (a worktree lacks the untracked originals) or the home.
fn native_claude(skill: &AgentSkill, cwd: &Path, home: Option<&Path>) -> bool {
match skill.source {
AgentSkillSource::ClaudeWorkspace => is_under(skill.path.0.as_path(), cwd),
AgentSkillSource::ClaudeUser => home.is_some_and(|h| is_under(skill.path.0.as_path(), &h.join(".claude"))),
_ => false,
}
}
/// Copilot reads the repository's `.github/skills` and the home's `.copilot` itself.
fn native_copilot(skill: &AgentSkill, cwd: &Path, home: Option<&Path>) -> bool {
match skill.source {
AgentSkillSource::GithubWorkspace => is_under(skill.path.0.as_path(), cwd),
AgentSkillSource::CopilotUser => home.is_some_and(|h| is_under(skill.path.0.as_path(), &h.join(".copilot"))),
_ => false,
}
}
/// Codex reads its own folders itself.
fn native_codex(skill: &AgentSkill, cwd: &Path, home: Option<&Path>) -> bool {
match skill.source {
AgentSkillSource::CodexWorkspace => is_under(skill.path.0.as_path(), cwd),
AgentSkillSource::CodexUser => home.is_some_and(|h| is_under(skill.path.0.as_path(), &h.join(".codex"))),
_ => false,
}
}
fn is_under(path: &Path, root: &Path) -> bool {
path.starts_with(root)
}
/// Puts `name` into the farm tree: a directory symlink where they work, a copy otherwise
/// (Windows needs Developer Mode for directory symlinks).
fn link_skill(link: &Path, target: &Path) -> std::io::Result<()> {
let _ = std::fs::remove_file(link);
if let Some(parent) = link.parent() {
std::fs::create_dir_all(parent)?;
}
#[cfg(unix)]
{
std::os::unix::fs::symlink(target, link)
}
#[cfg(windows)]
{
copy_dir_all(target, link)
}
}
#[cfg(windows)]
fn copy_dir_all(from: &Path, to: &Path) -> std::io::Result<()> {
std::fs::create_dir_all(to)?;
for entry in std::fs::read_dir(from)?.flatten() {
let path = entry.path();
let dest = to.join(entry.file_name());
if path.is_dir() {
copy_dir_all(&path, &dest)?;
} else {
std::fs::copy(&path, &dest)?;
}
}
Ok(())
}
/// Removes a task's farm (task deleted or archived); missing is fine.
pub fn remove_farm(store_dir: &Path, task: &str) {
let farm = farm_dir(store_dir, task);
match std::fs::remove_dir_all(&farm) {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => tracing::warn!("removing the session skills folder {}: {e}", farm.display()),
}
}
/// Where a task's staged skills live.
pub fn farm_dir(store_dir: &Path, task: &str) -> PathBuf {
store_dir.join("session-skills").join(sanitized(task))
}
/// A task id is a uuid, but never trust it with a path segment.
fn sanitized(id: &str) -> String {
id.chars().filter(|c| c.is_ascii_alphanumeric() || *c == '-').collect()
}
/// The `/` menu's skills: the active ones as commands (the agent's own listing wins on a
/// name clash). `Off` ones drop out everywhere; an ACP agent gets no other enforcement, so
/// `slashOnly` ones stay listed — there is nothing to hold them back with.
pub fn menu_commands(offered: Vec<AgentCommand>, states: &[AgentSkillState]) -> Vec<AgentCommand> {
let extra = states
.iter()
.filter(|s| s.mode != AgentSkillMode::Off)
.map(|s| AgentCommand {
name: s.skill.name.clone(),
description: s.skill.description.clone(),
hint: None,
source: AgentCommandSource::Skill,
})
.collect();
merge(offered, extra)
}
#[cfg(test)]
mod tests {
use super::*;
@@ -703,231 +333,4 @@ mod tests {
assert_eq!(f.get("name"), Some("quoted"));
assert_eq!(truncate(&"é".repeat(MAX_DESCRIPTION + 5)).chars().count(), MAX_DESCRIPTION + 1);
}
fn skill(name: &str, source: AgentSkillSource, root: &Path) -> AgentSkill {
AgentSkill {
name: name.into(),
description: format!("{name} does things"),
path: root.join(name).into(),
source,
valid: true,
warnings: Vec::new(),
}
}
fn policy(mode: AgentSkillMode) -> Option<AgentSkillPolicy> {
Some(AgentSkillPolicy { mode })
}
#[test]
fn hub_discovery_scans_every_root_and_collapses_symlinks() {
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path().join("home");
let repo = tmp.path().join("work/app");
std::fs::create_dir_all(&repo).unwrap();
write(&repo.join(".agents/skills/dep/SKILL.md"), "---\nname: dep\ndescription: From the standard root\n---\n");
write(&repo.join(".openidea/skills/local/SKILL.md"), "---\nname: local\ndescription: OpenIDEA's own\n---\n");
write(&repo.join(".claude/skills/claudey/SKILL.md"), "---\nname: claudey\ndescription: Claude's\n---\n");
write(&repo.join(".github/skills/gh/SKILL.md"), "---\nname: gh\ndescription: Copilot's repo one\n---\n");
write(
&home.join(".agents/skills/shared/SKILL.md"),
"---\nname: shared\ndescription: From npx skills add\n---\n",
);
write(&home.join(".codex/skills/codexy/SKILL.md"), "---\nname: codexy\ndescription: Codex's\n---\n");
write(&home.join(".cursor/skills/cursory/SKILL.md"), "---\nname: cursory\ndescription: Cursor's\n---\n");
// A symlink to `dep` in the home (the same canonical folder): collapsed.
#[cfg(unix)]
{
std::fs::create_dir_all(home.join(".claude/skills")).unwrap();
std::os::unix::fs::symlink(repo.join(".agents/skills/dep"), home.join(".claude/skills/dep")).unwrap();
}
// Hidden folders and files are not skills.
write(&repo.join(".agents/skills/.stash/SKILL.md"), "---\nname: hidden\ndescription: x\n---\n");
write(&repo.join(".agents/skills/loose.txt"), "not a folder");
// Same name from a lower-precedence source: the workspace one wins.
write(&home.join(".cursor/skills/local/SKILL.md"), "---\nname: local\ndescription: from cursor\n---\n");
let found = discover_skills(&repo, Some(&home));
assert_eq!(
found.iter().map(|s| (s.name.as_str(), s.source)).collect::<Vec<_>>(),
[
("dep", AgentSkillSource::Workspace),
("local", AgentSkillSource::Workspace),
("claudey", AgentSkillSource::ClaudeWorkspace),
("gh", AgentSkillSource::GithubWorkspace),
("shared", AgentSkillSource::User),
("codexy", AgentSkillSource::CodexUser),
("cursory", AgentSkillSource::CursorUser),
],
"symlinks collapse and the first of a name wins"
);
assert!(found.iter().all(|s| s.valid), "{:?}", found.iter().flat_map(|s| &s.warnings).collect::<Vec<_>>());
}
#[test]
fn hub_discovery_validates_and_reports() {
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path().join("app");
std::fs::create_dir_all(&repo).unwrap();
write(&repo.join(".agents/skills/bad-name/SKILL.md"), "---\nname: Bad_Name\ndescription: x\n---\n");
write(&repo.join(".agents/skills/no-desc/SKILL.md"), "---\nname: no-desc\n---\n");
write(
&repo.join(".agents/skills/verbose/SKILL.md"),
&format!("---\nname: verbose\ndescription: {}\n---\n", "x".repeat(MAX_SKILL_DESCRIPTION + 1)),
);
let found = discover_skills(&repo, None);
let by = |n: &str| found.iter().find(|s| s.name == n).unwrap();
assert!(!by("Bad_Name").valid && !by("Bad_Name").warnings.is_empty());
assert!(!by("no-desc").valid && by("no-desc").warnings.len() == 1);
assert!(!by("verbose").valid);
}
#[test]
fn hub_resolution_precedence_and_trust() {
let root = PathBuf::from("/r");
let ws = skill("tdd", AgentSkillSource::Workspace, &root);
let user = skill("lint", AgentSkillSource::User, &root);
let claude = skill("claudey", AgentSkillSource::ClaudeWorkspace, &root);
let session = BTreeMap::from([("tdd".to_owned(), AgentSkillMode::Off)]);
let workspace = BTreeMap::from([
("tdd".to_owned(), policy(AgentSkillMode::SlashOnly).unwrap()),
("lint".to_owned(), policy(AgentSkillMode::Off).unwrap()),
]);
let user_policies = BTreeMap::from([
("lint".to_owned(), policy(AgentSkillMode::SlashOnly).unwrap()),
("claudey".to_owned(), policy(AgentSkillMode::Auto).unwrap()),
]);
// Session > workspace policy > user policy.
let resolved = resolve(vec![ws.clone(), user.clone()], Some(&session), &workspace, &user_policies, true);
assert_eq!((resolved[0].mode, resolved[0].origin), (AgentSkillMode::Off, AgentSkillOrigin::Session));
assert_eq!((resolved[1].mode, resolved[1].origin), (AgentSkillMode::Off, AgentSkillOrigin::Workspace));
// Without a workspace policy the user's applies.
let resolved = resolve(vec![user.clone()], None, &BTreeMap::new(), &user_policies, true);
assert_eq!((resolved[0].mode, resolved[0].origin), (AgentSkillMode::SlashOnly, AgentSkillOrigin::User));
// Untrusted: the workspace's own skills stay off whatever the session chose, its
// policies hold only when they turn a skill off, and user skills keep resolving.
let resolved = resolve(vec![ws, user, claude], Some(&session), &workspace, &user_policies, false);
assert_eq!((resolved[0].mode, resolved[0].origin), (AgentSkillMode::Off, AgentSkillOrigin::Trust));
assert_eq!((resolved[1].mode, resolved[1].origin), (AgentSkillMode::Off, AgentSkillOrigin::Workspace));
assert_eq!((resolved[2].mode, resolved[2].origin), (AgentSkillMode::Off, AgentSkillOrigin::Trust));
}
fn listed(dir: &Path) -> Vec<String> {
let mut names: Vec<String> =
std::fs::read_dir(dir).unwrap().flatten().map(|e| e.file_name().to_string_lossy().into_owned()).collect();
names.sort();
names
}
#[test]
fn hub_staging_hands_each_cli_its_own_tree() {
let tmp = tempfile::tempdir().unwrap();
// Discovery reports canonical paths (macOS's temp folder is a symlink).
let root = dunce::canonicalize(tmp.path()).unwrap();
let home = root.join("home");
let repo = root.join("app");
std::fs::create_dir_all(&repo).unwrap();
// The staged folders must exist: Windows copies them (symlinks need Developer Mode).
for path in [
repo.join(".agents/skills/tdd"),
repo.join(".agents/skills/off"),
repo.join(".github/skills/gh"),
home.join(".agents/skills/lint"),
home.join(".agents/skills/muted"),
home.join(".codex/skills/codexy"),
] {
std::fs::create_dir_all(path).unwrap();
}
let states = resolve(
vec![
skill("tdd", AgentSkillSource::Workspace, &repo.join(".agents/skills")),
skill("gh", AgentSkillSource::GithubWorkspace, &repo.join(".github/skills")),
skill("lint", AgentSkillSource::User, &home.join(".agents/skills")),
skill("codexy", AgentSkillSource::CodexUser, &home.join(".codex/skills")),
skill("muted", AgentSkillSource::User, &home.join(".agents/skills")),
skill("off", AgentSkillSource::Workspace, &repo.join(".agents/skills")),
],
None,
&BTreeMap::from([("muted".to_owned(), policy(AgentSkillMode::SlashOnly).unwrap())]),
&BTreeMap::from([("off".to_owned(), policy(AgentSkillMode::Off).unwrap())]),
true,
);
// Local (non-worktree) session: the project's GitHub skills are Copilot's own.
let farm = farm_dir(&root.join("store"), "task-1");
let delivery = stage(&farm, "claude", &states, &repo, Some(&home)).unwrap();
assert_eq!(delivery.claude_add_dir.as_deref(), Some(farm.as_path()));
let claude_tree = farm.join(".claude/skills");
let staged = listed(&claude_tree);
assert_eq!(
staged,
["codexy", "gh", "lint", "muted", "tdd"],
"everything but the off one: none is native to Claude here, and slash-only needs the folder"
);
let delivery = stage(&farm, "copilot", &states, &repo, Some(&home)).unwrap();
assert_eq!(delivery.copilot_skill_directories, [farm.join("copilot").to_string_lossy().into_owned()]);
assert_eq!(delivery.copilot_disabled_skills, ["muted", "off"]);
let copilot_staged = listed(&farm.join("copilot"));
assert_eq!(copilot_staged, ["codexy", "lint", "tdd"], "`gh` is native to a local Copilot session");
assert_eq!(
delivery.codex_off,
[("off".to_owned(), repo.join(".agents/skills").join("off").to_string_lossy().into_owned())]
);
// A worktree task: the repo's skills are untracked, so nothing is native any more.
let worktree = root.join("wt");
std::fs::create_dir_all(&worktree).unwrap();
let _ = stage(&farm, "copilot", &states, &worktree, Some(&home)).unwrap();
let copilot_staged = listed(&farm.join("copilot"));
assert!(copilot_staged.contains(&"gh".to_string()));
// Slash-only reaches Claude as `user-invocable-only`, off as `off`.
let delivery = stage(&farm, "claude", &states, &repo, Some(&home)).unwrap();
let settings: serde_json::Value = serde_json::from_str(delivery.claude_settings.as_deref().unwrap()).unwrap();
assert_eq!(settings["skillOverrides"]["muted"], "user-invocable-only");
assert_eq!(settings["skillOverrides"]["off"], "off");
// Restaging after a session turned `lint` off drops its link and leaves the skill.
let session = BTreeMap::from([("lint".to_owned(), AgentSkillMode::Off)]);
let restated = resolve(
states.iter().map(|s| s.skill.clone()).collect(),
Some(&session),
&BTreeMap::from([("muted".to_owned(), policy(AgentSkillMode::SlashOnly).unwrap())]),
&BTreeMap::from([("off".to_owned(), policy(AgentSkillMode::Off).unwrap())]),
true,
);
stage(&farm, "claude", &restated, &repo, Some(&home)).unwrap();
assert_eq!(listed(&claude_tree), ["codexy", "gh", "muted", "tdd"]);
assert!(home.join(".agents/skills/lint").is_dir());
assert!(farm.join("copilot").is_dir(), "restaging Claude's tree leaves Copilot's alone");
// An ACP agent gets no farm.
let delivery = stage(&farm, "cursor-acp", &states, &repo, Some(&home)).unwrap();
assert_eq!(delivery, Delivery::default());
// The farm goes away with the task.
remove_farm(&root.join("store"), "task-1");
assert!(!farm.exists());
}
#[test]
fn hub_menu_filters_off_and_keeps_the_agents_own() {
let root = PathBuf::from("/r");
let states = resolve(
vec![skill("tdd", AgentSkillSource::Workspace, &root), skill("lint", AgentSkillSource::User, &root)],
Some(&BTreeMap::from([("lint".to_owned(), AgentSkillMode::Off)])),
&BTreeMap::new(),
&BTreeMap::new(),
true,
);
let menu = menu_commands(vec![cmd("tdd", "from the agent itself")], &states);
assert_eq!(names(&menu), ["tdd"]);
assert_eq!(menu[0].description, "from the agent itself");
assert_eq!(menu[0].source, AgentCommandSource::Skill);
}
}
+2 -5
Переглянути файл
@@ -4532,7 +4532,6 @@ async fn per_session_mcp_overrides_filter_session_and_reload_when_idle() {
base: None,
mcp_overrides: BTreeMap::from([("slack".into(), false)]),
idle: false,
skill_overrides: BTreeMap::new(),
})
.await
.unwrap();
@@ -4661,7 +4660,6 @@ async fn copilot_falls_back_to_acp_when_headless_probe_session_or_prompt_fails()
base: None,
mcp_overrides: BTreeMap::new(),
idle: false,
skill_overrides: BTreeMap::new(),
})
.await
.unwrap();
@@ -4687,7 +4685,6 @@ async fn copilot_falls_back_to_acp_when_headless_probe_session_or_prompt_fails()
base: None,
mcp_overrides: BTreeMap::new(),
idle: false,
skill_overrides: BTreeMap::new(),
})
.await
.unwrap();
@@ -4766,10 +4763,10 @@ done
#[test]
fn session_params_name_the_servers_off() {
let mcp = McpForSession { servers: vec![json!({ "name": "docs" })], off: vec!["github".into()] };
let params = session_params("/p", &mcp, None);
let params = session_params("/p", &mcp);
assert_eq!(params["cwd"], "/p");
assert_eq!(params["mcpServers"][0]["name"], "docs");
assert_eq!(params["_meta"]["openidea"]["mcpServersOff"], json!(["github"]));
let none = McpForSession { servers: Vec::new(), off: Vec::new() };
assert!(session_params("/p", &none, None).get("_meta").is_none());
assert!(session_params("/p", &none).get("_meta").is_none());
}
-2
Переглянути файл
@@ -102,8 +102,6 @@ pub enum IdeEvent {
WorkspaceEditApplied {
id: u32,
paths: Vec<crate::IpcPath>,
/// Files the edit renamed, as the edit named them: editors open on them follow.
moves: Vec<crate::FileMove>,
/// Made by an agent through the MCP server's tools: undoable like a refactoring, but
/// not announced as one.
by_agent: bool,
-34
Переглянути файл
@@ -130,11 +130,6 @@ pub struct AgentSettings {
#[serde(deserialize_with = "or_default")]
#[specta(type = BTreeMap<String, AgentMcpServer>)]
pub mcp_servers: BTreeMap<String, AgentMcpServer>,
/// How agent skills may run, keyed by skill name (`[agents.skills.<name>]`); `SKILL.md`
/// files on disk are never modified.
#[serde(deserialize_with = "or_default")]
#[specta(type = BTreeMap<String, AgentSkillPolicy>)]
pub skills: BTreeMap<String, AgentSkillPolicy>,
}
impl Default for AgentSettings {
@@ -155,7 +150,6 @@ impl Default for AgentSettings {
new_task_approvals: NewTaskApprovals::Bypass,
defaults: BTreeMap::new(),
mcp_servers: BTreeMap::new(),
skills: BTreeMap::new(),
}
}
}
@@ -211,34 +205,6 @@ impl Default for AgentMcpServer {
}
}
/// How an agent skill may run (`[agents.skills.<name>] mode = …`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentSkillMode {
/// The model decides when to use it.
#[default]
Auto,
/// Only when the user invokes it with `/name`.
SlashOnly,
/// Never.
Off,
}
/// A skill's policy in Settings › Agents › Skills, stored without touching its `SKILL.md`.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct AgentSkillPolicy {
#[serde(deserialize_with = "or_default")]
#[specta(type = AgentSkillMode)]
pub mode: AgentSkillMode,
}
impl Default for AgentSkillPolicy {
fn default() -> Self {
Self { mode: AgentSkillMode::Auto }
}
}
/// A hand-edited value these settings don't know reads as the default, rather than
/// failing the whole settings file.
fn or_default<'de, D, T>(d: D) -> Result<T, D::Error>
-19
Переглянути файл
@@ -110,17 +110,6 @@ pub struct WorkspaceEditPrecondition {
}
impl WorkspaceEdit {
/// The files and folders the edit renames, in order.
pub fn moves(&self) -> Vec<FileMove> {
self.files
.iter()
.filter_map(|f| match f {
FileEdit::Rename { from, to } => Some(FileMove { from: from.clone(), to: to.clone() }),
_ => None,
})
.collect()
}
/// Coalesces aliases of the same file before applying edits against its original text.
/// Resource operations separate batches because later edits may use the new contents.
pub fn deduplicate(&mut self) {
@@ -195,14 +184,6 @@ pub enum FileEdit {
},
}
/// One file or folder move.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct FileMove {
pub from: crate::IpcPath,
pub to: crate::IpcPath,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum Severity {
-2
Переглянути файл
@@ -151,7 +151,6 @@ pub struct CommitSettings {
/// Commit from the Commit tool window; off = Local Changes in the Git tool
/// window and a Commit dialog.
pub non_modal: bool,
pub include_changes_by_default: bool,
/// Start with an empty message instead of the last one / the changelist's.
pub clear_initial_message: bool,
pub analyze_code: bool,
@@ -191,7 +190,6 @@ impl Default for CommitSettings {
fn default() -> Self {
Self {
non_modal: true,
include_changes_by_default: true,
clear_initial_message: false,
analyze_code: true,
check_todo: true,
+2 -2
Переглянути файл
@@ -72,7 +72,7 @@ pub struct Host {
/// Projects the MCP server serves without a window.
pub mcp_background: mcp::BackgroundProjects,
pub(crate) agent_catalogs: Arc<ide_agent::AgentCatalogs>,
pub trust: std::sync::Arc<trust::TrustStore>,
pub trust: trust::TrustStore,
pub(crate) mcp_approvals: Arc<trust::McpServerApprovals>,
pub config_dir: PathBuf,
/// Persistent user state, including credentials and recovery history.
@@ -169,7 +169,7 @@ impl Host {
mcp_agent_runs: Default::default(),
mcp_background: Default::default(),
agent_catalogs: Arc::default(),
trust: std::sync::Arc::new(trust::TrustStore::load(&config_dir, &data_dir)),
trust: trust::TrustStore::load(&config_dir, &data_dir),
mcp_approvals: Arc::new(trust::McpServerApprovals::load(&data_dir)),
proxy_password: ide_ssh::secrets::SecretFile::new(data_dir.join("proxy-password.json")),
proxy_session_password: Mutex::default(),
+3 -7
Переглянути файл
@@ -668,8 +668,8 @@ async fn text_search(call: Call, is_regex: bool) -> IdeResult<Output> {
if hits.len() > limit {
break;
}
// Find in Files reports a very long line in windows cut around its matches: such lines
// are matched again in the file's whole text, so a match keeps its real end.
// Find in Files keeps a window of very long lines and drops the matches outside it:
// such lines are matched again in the file's whole text.
let long = |m: &ide_search::LineMatch| m.text_offset > 0 || m.text.encode_utf16().count() + 1 >= LINE_WINDOW;
let whole = if file.matches.iter().any(long) {
crate::ops::fs::fs_read_text(&host, call.window(), file.path.0.clone())
@@ -679,15 +679,11 @@ async fn text_search(call: Call, is_regex: bool) -> IdeResult<Output> {
} else {
None
};
// One window per far-apart match: a line is expanded once.
let mut expanded = std::collections::HashSet::new();
for m in &file.matches {
if let Some((ranges, text)) = &whole
&& long(m)
{
if expanded.insert(m.line) {
hits.extend(line_hits(path, text, ranges, m.line));
}
hits.extend(line_hits(path, text, ranges, m.line));
continue;
}
let line_end = m.text_offset + m.text.encode_utf16().count() as u32;
+2 -148
Переглянути файл
@@ -7,9 +7,8 @@ use ide_agent::registry::{AgentRegistry, RegistryPaths};
use ide_agent::{
AcpImportOutcome, AgentAcceptOutcome, AgentChange, AgentChanges, AgentChangesView, AgentCliOffer,
AgentCliUpdateResult, AgentCommand, AgentContextUsage, AgentEntry, AgentEvent, AgentModelCatalog, AgentProbe,
AgentPrompt, AgentProvider, AgentQueued, AgentSkillMode, AgentSkillPolicy, AgentSkillState, AgentTask,
CustomAgentInput, ExternalSession, McpExternalSource, McpImportSelection, McpProbeResult, McpScope, McpServer,
McpServerInput, McpTransport, NewAgentTask, SkillsPolicy,
AgentPrompt, AgentProvider, AgentQueued, AgentTask, CustomAgentInput, ExternalSession, McpExternalSource,
McpImportSelection, McpProbeResult, McpScope, McpServer, McpServerInput, McpTransport, NewAgentTask,
};
use ide_command::command;
use ide_core::error::ErrorKind;
@@ -1029,148 +1028,6 @@ pub fn agent_set_mcp_overrides(
host.project(window)?.agents.set_mcp_overrides(&task, overrides)
}
/// Updates per-session skill modes on `task`.
#[command(trust = always)]
pub fn agent_set_skill_overrides(
host: &Host,
window: &str,
task: String,
overrides: std::collections::BTreeMap<String, AgentSkillMode>,
) -> IdeResult<AgentTask> {
host.project(window)?.agents.set_skill_overrides(&task, overrides)
}
/// Every skill discovered in the project and the user's folders, with the mode a session
/// of this project runs it with (without any session's own overrides).
#[command(trust = always)]
pub async fn agent_skills_list(host: &Host, window: &str) -> IdeResult<Vec<AgentSkillState>> {
let project = host.project(window)?;
let root = project.root.clone();
let (policy, home) = (skills_policy(&project), dirs::home_dir());
tokio::task::spawn_blocking(move || {
Ok(ide_agent::skills::resolve(
ide_agent::skills::discover_skills(&root, home.as_deref()),
None,
&policy.workspace,
&policy.user,
policy.workspace_trusted,
))
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?
}
/// Sets how `name` may run in `scope`, in the settings file of that scope, and returns the
/// updated list. `SKILL.md` files are never touched; the default `auto` removes the entry.
#[command(trust = always)]
pub fn agent_skills_set_mode(
host: &Host,
window: &str,
name: String,
scope: McpScope,
mode: AgentSkillMode,
) -> IdeResult<Vec<AgentSkillState>> {
let name = name.trim().to_owned();
if name.is_empty() {
return Err(IdeError::invalid("a skill needs a name"));
}
let project = host.project(window).ok().filter(|p| !p.light);
let (mut user, mut workspace) = skills_maps(host, project.as_ref());
match scope {
McpScope::User => {
let changed = if mode == AgentSkillMode::Auto {
user.remove(&name).is_some()
} else {
user.insert(name, AgentSkillPolicy { mode }).map(|p| p.mode) != Some(mode)
};
if changed {
persist_skills_map(host, None, scope, &user)?;
}
}
McpScope::Workspace => {
let map =
workspace.as_mut().ok_or_else(|| IdeError::invalid("Open a project to configure workspace skills"))?;
let changed = if mode == AgentSkillMode::Auto {
map.remove(&name).is_some()
} else {
map.insert(name, AgentSkillPolicy { mode }).map(|p| p.mode) != Some(mode)
};
if changed {
let map = map.clone();
persist_skills_map(host, project.as_ref(), scope, &map)?;
}
}
}
match project {
Some(project) => {
let root = project.root.clone();
let policy = skills_policy(&project);
let home = dirs::home_dir();
Ok(ide_agent::skills::resolve(
ide_agent::skills::discover_skills(&root, home.as_deref()),
None,
&policy.workspace,
&policy.user,
policy.workspace_trusted,
))
}
None => Ok(Vec::new()),
}
}
/// The user's and the workspace's skill policies (`[agents.skills.<name>]`).
fn skills_maps(
host: &Host,
project: Option<&std::sync::Arc<crate::Project>>,
) -> (std::collections::BTreeMap<String, AgentSkillPolicy>, Option<std::collections::BTreeMap<String, AgentSkillPolicy>>)
{
let user = host.global_settings.effective().agents.skills.clone();
let workspace =
project.map(|p| p.settings.layer(ide_workspace::settings::SettingsScope::Project).agents.skills.clone());
(user, workspace)
}
/// Saves `map` into its scope's settings and tells the windows.
fn persist_skills_map(
host: &Host,
project: Option<&std::sync::Arc<crate::Project>>,
scope: McpScope,
map: &std::collections::BTreeMap<String, AgentSkillPolicy>,
) -> IdeResult<()> {
let value = if map.is_empty() {
serde_json::Value::Null
} else {
serde_json::to_value(map).map_err(|e| IdeError::invalid(e.to_string()))?
};
let event = IdeEvent::SettingsChanged { key: "agents.skills".into() };
match scope {
McpScope::User => {
host.global_settings.set(ide_workspace::settings::SettingsScope::Global, "agents.skills", value)?;
for p in host.projects() {
p.settings.reload();
p.agents.notify_mcp_servers_changed();
p.sink.emit(event.clone());
}
}
McpScope::Workspace => {
let p = project.ok_or_else(|| IdeError::invalid("Open a project to configure workspace skills"))?;
p.settings.set(ide_workspace::settings::SettingsScope::Project, "agents.skills", value)?;
p.agents.notify_mcp_servers_changed();
p.sink.emit(event);
}
}
Ok(())
}
/// The skill policies a session of `project` resolves against.
fn skills_policy(project: &crate::Project) -> SkillsPolicy {
SkillsPolicy {
user: project.settings.layer(ide_workspace::settings::SettingsScope::Global).agents.skills.clone(),
workspace: project.settings.layer(ide_workspace::settings::SettingsScope::Project).agents.skills.clone(),
workspace_trusted: project.trusted.load(std::sync::atomic::Ordering::Acquire),
}
}
fn validate_project_root(root: &std::path::Path, requested: Option<&std::path::Path>) -> IdeResult<std::path::PathBuf> {
let Some(requested) = requested else {
return Ok(root.to_path_buf());
@@ -1326,9 +1183,6 @@ ide_command::domain!(
agent_set_config,
agent_set_env,
agent_set_mcp_overrides,
agent_set_skill_overrides,
agent_skills_list,
agent_skills_set_mode,
agent_stop_background,
agent_subscribe,
agent_unarchive,
+3 -6
Переглянути файл
@@ -85,7 +85,7 @@ pub async fn doc_set_line_ending(host: &Host, window: &str, doc: DocId, line_end
}
/// Structure view: LSP document symbols when available (with tree-sitter
/// visibility and type-alias kinds), tree-sitter otherwise.
/// visibility), tree-sitter otherwise.
/// Tree-sitter answers come from the per-document tree cache (incremental
/// re-parse); large documents get no syntax structure.
#[command(trust = always)]
@@ -113,13 +113,10 @@ pub async fn doc_outline(host: &Host, window: &str, doc: DocId) -> IdeResult<Vec
};
let syntax = || project.syntax.outline(doc, &snap.language, snap.version, &snap.text);
Ok(match lsp {
// Server symbols carry no visibility, nor a kind for type aliases; borrow them from
// the syntax tree.
// Server symbols carry no visibility; borrow it from the syntax tree.
Some(mut items) => {
if !snap.large {
let syntax = syntax();
ide_language::merge_visibility(&mut items, &syntax);
ide_language::merge_kinds(&mut items, &syntax);
ide_language::merge_visibility(&mut items, &syntax());
}
items
}
-6
Переглянути файл
@@ -335,12 +335,6 @@ pub fn set_settings(
project.agents.notify_mcp_servers_changed();
}
}
// A skill policy change re-resolves the modes; an idle session restarts to pick them up.
if key == "agents" || key == "agents.skills" || key.starts_with("agents.skills.") {
for project in affected() {
project.agents.notify_mcp_servers_changed();
}
}
// A new interpreter / toolchain / server executable restarts the language servers it affects.
// So do inspections that are compiler options (`ide-sdk` `configure_java_compiler`).
let code_style = key == "editor"
+4 -12
Переглянути файл
@@ -22,17 +22,6 @@ pub fn literal_range(l: ide_language::Literal) -> ide_search::LiteralRange {
ide_search::LiteralRange { start: l.start, end: l.end, kind }
}
/// Comments and string literals of `text`, for the search context of Find and Replace in Files.
pub(crate) fn literals_of(
project: &crate::project::Project,
syntax: &ide_language::Syntax,
path: &Path,
text: &str,
) -> Option<Vec<ide_search::LiteralRange>> {
let language = project.languages.detect(path, text.lines().next());
Some(syntax.literals(&language, text)?.into_iter().map(literal_range).collect())
}
/// Find in Files. Results stream through `on_event`; ends with `Done`.
/// Cancel with `cancel_request(request)`.
#[command(trust = always)]
@@ -109,7 +98,10 @@ pub(crate) fn search_project(
Some(ProjectFileSet::Test) => roots.is_test(rel),
_ => true,
};
let literals = |path: &Path, text: &str| literals_of(project, syntax, path, text);
let literals = |path: &Path, text: &str| {
let language = project.languages.detect(path, text.lines().next());
Some(syntax.literals(&language, text)?.into_iter().map(literal_range).collect())
};
let defaults = project.documents.file_defaults();
let decode = |path: &Path, bytes: &[u8]| ide_vfs::decode_text(bytes, defaults.fallback_for(path));
let mut total = SearchSummary::default();
+3 -13
Переглянути файл
@@ -75,19 +75,9 @@ pub async fn replace_in_files(
let summary = tokio::task::spawn_blocking(move || {
let targets = if all_in_scope { scope_targets(&project, &syntax, &query, targets, &cancel)? } else { targets };
let host = DocumentsHost(&project.documents);
let literals = |path: &Path, text: &str| super::literals_of(&project, &syntax, path, text);
ide_search::replace_files_in_context(
&host,
&query,
&replacement,
preserve_case,
&targets,
Some(&literals),
&cancel,
&|e| {
let _ = events.send(e);
},
)
ide_search::replace_files(&host, &query, &replacement, preserve_case, &targets, &cancel, &|e| {
let _ = events.send(e);
})
})
.await
.map_err(|e| ide_core::IdeError::internal(e.to_string()));
-13
Переглянути файл
@@ -738,19 +738,6 @@ impl Host {
let approvals = self.mcp_approvals.clone();
let secrets = self.agent_secrets.clone();
let root = root.to_path_buf();
// The skill policies sessions resolve against: both settings layers and the
// workspace's trust as it stands when a session starts.
let skill_settings = settings.clone();
let skill_root = root.clone();
let trust = self.trust.clone();
agents.set_skills_policy_hook(Box::new(move || {
let layer = |scope| skill_settings.layer(scope).agents.skills.clone();
ide_agent::SkillsPolicy {
user: layer(ide_workspace::settings::SettingsScope::Global),
workspace: layer(ide_workspace::settings::SettingsScope::Project),
workspace_trusted: trust.trusted(&skill_root).unwrap_or(false),
}
}));
agents.set_mcp_servers_hook(Box::new(move || {
crate::ops::agent::session_mcp_servers(&settings, &approvals, &secrets, &root)
}));
-13
Переглянути файл
@@ -187,19 +187,6 @@ async fn reads_unsaved_text_and_searches_the_overlay_with_a_limit() {
assert_eq!(std::fs::read_to_string(h.root.join("src/a.txt")).unwrap(), "old text\nneedle needle\n");
}
#[tokio::test(flavor = "multi_thread")]
async fn every_match_of_a_long_line_is_found_once() {
let h = Harness::new();
std::fs::write(
h.root.join("src/min.js"),
format!("a=1;{}b='longneedle';{}longneedle\n", "x".repeat(2000), "y".repeat(2000)),
)
.unwrap();
let found = h.json("search_text", json!({"q":"longneedle","limit":20})).await;
let columns: Vec<_> = found["items"].as_array().unwrap().iter().map(|i| i["startColumn"].clone()).collect();
assert_eq!(columns, [json!(2008), json!(4020)], "{found}");
}
#[tokio::test(flavor = "multi_thread")]
async fn window_reports_supply_editor_selection_and_problems_then_disappear_on_close() {
let h = Harness::new();
-53
Переглянути файл
@@ -195,56 +195,3 @@ async fn replace_all_saves_open_buffers_without_unsaved_changes() {
assert_eq!(project.documents.text_snapshot(edited).unwrap().text, "DONE\nmore\n");
host.close_project("main");
}
/// Replace All past the limit replaces what the search lists: only the matches its Search
/// Context keeps (comments, string literals or code), as below the limit.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn replace_all_past_the_limit_keeps_to_the_search_context() {
use ide_search::SearchContext as C;
let comments = |word: &str| lines(2001, &format!("// {word}"));
let code = |name: &str, string: &str| format!("fn {name}() -> &'static str {{ \"{string}\" }}\n");
let original = format!("{}{}", comments("tok"), code("tok", "tok"));
let cases = [
(C::Any, format!("{}{}", comments("X"), code("X", "X"))),
(C::InComments, format!("{}{}", comments("X"), code("tok", "tok"))),
(C::InStringLiterals, format!("{}{}", comments("tok"), code("tok", "X"))),
(C::ExceptComments, format!("{}{}", comments("tok"), code("X", "X"))),
(C::ExceptStringLiterals, format!("{}{}", comments("X"), code("X", "tok"))),
(C::ExceptCommentsAndStringLiterals, format!("{}{}", comments("tok"), code("X", "tok"))),
];
for (context, expected) in cases {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
std::fs::create_dir_all(&root).unwrap();
std::fs::write(root.join("lib.rs"), &original).unwrap();
let host = Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(NullSink)),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
});
host.trust.decide(&root, true, false).unwrap();
host.open_project("main", &root).unwrap();
ops::search::replace_in_files(
&host,
"main",
RequestId::next(),
SearchQuery { context, ..query("tok", false) },
"X".into(),
false,
vec![],
true,
ops::Channel::new(|_| {}),
)
.await
.unwrap();
assert_eq!(std::fs::read_to_string(root.join("lib.rs")).unwrap(), expected, "{context:?}");
host.close_project("main");
}
}
+1 -1
Переглянути файл
@@ -25,7 +25,7 @@ pub use syntax::{
CSS_CLASS, CSS_ID, CSS_VARIABLE, ClassBases, ConfigurationKey, ExternalFold, ExternalSymbol, ExternalSyntax,
ExternalToken, FileReference, Literal, LiteralKind, MAX_CACHED_TREES, MAX_PARSE_BYTES, ParsedTree, SpellingKind,
SpellingRegion, Syntax, SyntaxCache, SyntaxCacheStats, SyntaxHighlightKind, SyntaxHighlights, TreeError,
VueComponentImport, VueRefAccess, VueRefElement, WebReference, WebReferenceKind, merge_kinds, merge_visibility,
VueComponentImport, VueRefAccess, VueRefElement, WebReference, WebReferenceKind, merge_visibility,
set_external_syntax, shift_pos, shift_range,
};
pub use syntax::{MethodBody, PhpAlignment, PythonClassFacts, PythonFacts, PythonMethodFacts};
+1 -1
Переглянути файл
@@ -28,7 +28,7 @@ use ide_core::{LanguageId, OutlineItem, Pos, Range};
pub use inheritance::ClassBases;
pub use lines::{shift_pos, shift_range};
pub use literals::{Literal, LiteralKind, SpellingKind, SpellingRegion};
pub use outline::{merge_kinds, merge_visibility};
pub use outline::merge_visibility;
pub use php_align::PhpAlignment;
pub use python_facts::{MethodBody, PythonClassFacts, PythonFacts, PythonMethodFacts};
use std::cell::RefCell;
-30
Переглянути файл
@@ -495,36 +495,6 @@ pub fn merge_visibility(target: &mut [OutlineItem], source: &[OutlineItem]) {
}
}
/// Takes the syntax tree's kind where a server reported a declared type as a value or a type
/// parameter: LSP has no kind for type aliases, so servers fall back to one of those
/// (typescript-language-server: Variable; rust-analyzer, sourcekit-lsp: TypeParameter).
/// Matched by name and position like [`merge_visibility`].
pub fn merge_kinds(target: &mut [OutlineItem], source: &[OutlineItem]) {
fn index(items: &[OutlineItem], out: &mut HashMap<(ide_core::Pos, String), SymbolKind>) {
for i in items {
if i.kind.is_type_like() {
out.insert((i.selection_range.start, i.name.clone()), i.kind);
}
index(&i.children, out);
}
}
fn apply(items: &mut [OutlineItem], map: &HashMap<(ide_core::Pos, String), SymbolKind>) {
for i in items {
if matches!(i.kind, SymbolKind::Variable | SymbolKind::TypeParameter)
&& let Some(&kind) = map.get(&(i.selection_range.start, i.name.clone()))
{
i.kind = kind;
}
apply(&mut i.children, map);
}
}
let mut map = HashMap::new();
index(source, &mut map);
if !map.is_empty() {
apply(target, &map);
}
}
/// End of `node` without trailing whitespace (C macros and others include the newline).
fn trimmed_end(node: &Node, text: &str) -> usize {
let (s, e) = (node.start_byte(), node.end_byte());
-82
Переглянути файл
@@ -1476,88 +1476,6 @@ fn merge_visibility_matches_by_name_and_position() {
assert_eq!(lsp[1].visibility, None);
}
#[test]
fn merge_kinds_names_types_a_server_reported_as_values_or_type_parameters() {
fn kinds(items: &[OutlineItem], out: &mut Vec<(String, SymbolKind)>) {
for i in items {
out.push((i.name.clone(), i.kind));
kinds(&i.children, out);
}
}
/// The syntax outline with each kind replaced as a server reports it.
fn as_server(ts: &[OutlineItem], server: &[(&str, SymbolKind)]) -> Vec<OutlineItem> {
fn set(items: &mut [OutlineItem], server: &[(&str, SymbolKind)], at: &mut usize) {
for i in items {
i.kind = server[*at].1;
assert_eq!(i.name, server[*at].0);
*at += 1;
set(&mut i.children, server, at);
}
}
let mut lsp = ts.to_vec();
set(&mut lsp, server, &mut 0);
lsp
}
fn merged(language: &str, src: &str, server: &[(&str, SymbolKind)]) -> Vec<(String, SymbolKind)> {
let ts = syntax().outline(&lang(language), src);
let mut lsp = as_server(&ts, server);
crate::merge_kinds(&mut lsp, &ts);
let mut out = Vec::new();
kinds(&lsp, &mut out);
out
}
use SymbolKind as K;
let owned = |v: &[(&str, SymbolKind)]| v.iter().map(|(n, k)| (n.to_string(), *k)).collect::<Vec<_>>();
// typescript-language-server: a type alias is a Variable; `const` is one too.
let ts = "type Cents = number;\ninterface Shape {}\nconst rate = 1;\n";
assert_eq!(
merged("typescript", ts, &[("Cents", K::Variable), ("Shape", K::Interface), ("rate", K::Variable)]),
owned(&[("Cents", K::TypeAlias), ("Shape", K::Interface), ("rate", K::Variable)]),
);
// rust-analyzer: type aliases and associated types are TypeParameters, a trait an Interface.
let rs = "pub type Meters = u32;\ntrait Measure { type Unit; }\nstruct Rope;\nimpl Measure for Rope { type Unit = Meters; }\n";
assert_eq!(
merged(
"rust",
rs,
&[
("Meters", K::TypeParameter),
("Measure", K::Interface),
("Unit", K::TypeParameter),
("Rope", K::Struct),
("impl Measure for Rope", K::Variable),
("Unit", K::TypeParameter),
],
),
owned(&[
("Meters", K::TypeAlias),
("Measure", K::Interface),
("Unit", K::TypeAlias),
("Rope", K::Struct),
("impl Measure for Rope", K::Variable),
("Unit", K::TypeAlias),
]),
);
// sourcekit-lsp: typealias and associatedtype are TypeParameters.
let swift = "typealias Meters = Int\nprotocol Measure { associatedtype Unit }\n";
assert_eq!(
merged("swift", swift, &[("Meters", K::TypeParameter), ("Measure", K::Interface), ("Unit", K::TypeParameter)]),
owned(&[("Meters", K::TypeAlias), ("Measure", K::Interface), ("Unit", K::TypeAlias)]),
);
// A type kind the server chose stays: clangd's Class for a typedef, gopls's Struct.
let c = "typedef unsigned int meters;\n";
assert_eq!(merged("c", c, &[("meters", K::Class)]), owned(&[("meters", K::Class)]));
let go = "package p\n\ntype Point struct{}\n";
assert_eq!(
merged("go", go, &[("p", K::Package), ("Point", K::Struct)]),
owned(&[("p", K::Package), ("Point", K::Struct)])
);
}
#[test]
fn spelling_regions_cover_declared_names_only() {
let src = "// note\nfn parse_input(raw_text: &str) -> Value { let mut counter = helper(raw_text); \"hi\" }\n";
+12 -8
Переглянути файл
@@ -1,12 +1,13 @@
//! Parallel walk + per-file search.
use crate::iter::for_each_match;
use crate::line::line_matches;
use crate::line::line_match;
use crate::mask::FileMask;
use crate::pattern::ScopePattern;
use crate::query::{Compiled, line_terminator};
use crate::{
FileMatches, LineMatch, LiteralRange, Literals, PathFilter, SearchContext, SearchScope, SearchSummary, TextSource,
FileMatches, LineMatch, LiteralKind, LiteralRange, Literals, PathFilter, SearchContext, SearchScope, SearchSummary,
TextSource,
};
use grep_regex::RegexMatcher;
use grep_searcher::{BinaryDetection, Searcher, SearcherBuilder, Sink, SinkMatch};
@@ -51,7 +52,6 @@ struct Control<'a> {
matches: AtomicU32,
files: AtomicU32,
max: u32,
whole_word: bool,
}
impl Control<'_> {
@@ -131,7 +131,6 @@ pub(crate) fn run(req: Request<'_>) -> IdeResult<SearchSummary> {
matches: AtomicU32::new(0),
files: AtomicU32::new(0),
max: if req.max_matches == 0 { DEFAULT_MAX_MATCHES } else { req.max_matches },
whole_word: req.compiled.whole_word,
},
};
let mut searcher_builder = SearcherBuilder::new();
@@ -463,6 +462,12 @@ impl<'a> FileSink<'a> {
}
}
/// Kind of the comment or string literal containing byte `pos` (`literals` sorted).
fn literal_at(literals: &[LiteralRange], pos: usize) -> Option<LiteralKind> {
let i = literals.partition_point(|l| l.start <= pos);
literals[..i].last().filter(|l| pos < l.end).map(|l| l.kind)
}
impl Sink for FileSink<'_> {
type Error = io::Error;
@@ -483,12 +488,12 @@ impl Sink for FileSink<'_> {
let mut found = std::mem::take(&mut self.found);
let mut ranges = std::mem::take(&mut self.ranges);
found.clear();
for_each_match(self.matcher, self.ctl.whole_word, &buffer[..range.end], range.start, |mm| {
for_each_match(self.matcher, &buffer[..range.end], range.start, |mm| {
found.push((mm.start() - range.start, mm.end() - range.start));
});
if let Some((context, literals)) = self.context {
let block_start = usize::try_from(m.absolute_byte_offset()).unwrap_or(usize::MAX);
found.retain(|&(a, _)| context.keeps(literals, block_start.saturating_add(a)));
found.retain(|&(a, _)| context.accepts(literal_at(literals, block_start.saturating_add(a))));
}
let mut next = found.iter().copied().peekable();
@@ -516,7 +521,7 @@ impl Sink for FileSink<'_> {
if !ranges.is_empty() {
self.count = self.count.saturating_add(u32::try_from(ranges.len()).unwrap_or(u32::MAX));
let line_no = u32::try_from(line_no).unwrap_or(u32::MAX);
line_matches(line_no, &block[line_start..content_end], &ranges, &mut self.lines);
self.lines.push(line_match(line_no, &block[line_start..content_end], &ranges));
}
line_start = line_end_incl;
line_no += 1;
@@ -701,7 +706,6 @@ mod budget_tests {
matches: AtomicU32::new(0),
files: AtomicU32::new(0),
max,
whole_word: false,
}
}
+7 -70
Переглянути файл
@@ -1,27 +1,16 @@
//! Match iteration that never splits a UTF-8 sequence after an empty match
//! (`grep-matcher`'s iterators advance by a single byte), and that applies
//! IDEA's whole-word rule.
//! (`grep-matcher`'s iterators advance by a single byte).
use grep_matcher::{Captures, Match, Matcher};
use grep_regex::{RegexCaptures, RegexMatcher};
/// Calls `f` for each non-overlapping match in `haystack[at..]`; `haystack[..at]`
/// is only used as look-behind context. With `whole_word`, only [`is_whole_word`] matches.
pub(crate) fn for_each_match(
matcher: &RegexMatcher,
whole_word: bool,
haystack: &[u8],
at: usize,
mut f: impl FnMut(Match),
) {
/// is only used as look-behind context.
pub(crate) fn for_each_match(matcher: &RegexMatcher, haystack: &[u8], at: usize, mut f: impl FnMut(Match)) {
let mut at = at;
let mut last_end = None;
while at <= haystack.len() {
let Ok(Some(m)) = matcher.find_at(haystack, at) else { break };
if whole_word && !is_whole_word(haystack, m) {
at = next_char(haystack, m.start());
continue;
}
at = advance(haystack, m);
if m.is_empty() && last_end == Some(m.end()) {
continue;
@@ -34,7 +23,6 @@ pub(crate) fn for_each_match(
/// Like [`for_each_match`] but with capture groups.
pub(crate) fn for_each_captures(
matcher: &RegexMatcher,
whole_word: bool,
haystack: &[u8],
caps: &mut RegexCaptures,
mut f: impl FnMut(&RegexCaptures),
@@ -46,10 +34,6 @@ pub(crate) fn for_each_captures(
break;
}
let Some(m) = caps.get(0) else { break };
if whole_word && !is_whole_word(haystack, m) {
at = next_char(haystack, m.start());
continue;
}
at = advance(haystack, m);
if m.is_empty() && last_end == Some(m.end()) {
continue;
@@ -61,59 +45,12 @@ pub(crate) fn for_each_captures(
/// Where to resume after `m`: its end, or past the next char for empty matches.
fn advance(haystack: &[u8], m: Match) -> usize {
if !m.is_empty() { m.end() } else { next_char(haystack, m.end()) }
}
/// The start of the char after the one at `at`.
fn next_char(haystack: &[u8], at: usize) -> usize {
let mut next = at + 1;
if !m.is_empty() {
return m.end();
}
let mut next = m.end() + 1;
while next < haystack.len() && (haystack[next] & 0xC0) == 0x80 {
next += 1;
}
next
}
/// IDEA's whole word (`FindManagerBase.isWholeWord`): an edge where the match has an
/// identifier character must not touch another one, unless it follows an escape such as
/// `\n`; an edge with another character only must not repeat that character (`==` is not
/// in `===`).
fn is_whole_word(haystack: &[u8], m: Match) -> bool {
let (start, end) = (m.start(), m.end());
let word_start = match (char_before(haystack, start), char_at(haystack, start)) {
(Some(prev), Some(first)) if is_identifier(first) => {
let escaped = char_before(haystack, start - prev.len_utf8()) == Some('\\');
!is_identifier(prev) || escaped
}
(Some(prev), Some(first)) => prev != first,
_ => true,
};
let word_end = match (char_at(haystack, end), char_before(haystack, end)) {
(Some(next), Some(last)) if is_identifier(last) => !is_identifier(next),
(Some(next), Some(last)) => next != last,
(Some(_), None) | (None, _) => true,
};
word_start && word_end
}
/// Java's identifier part, near enough: letters, digits, `_` and `$`.
fn is_identifier(c: char) -> bool {
c.is_alphanumeric() || c == '_' || c == '$'
}
/// The char starting at byte `at` (`None` at the end or in invalid UTF-8).
fn char_at(haystack: &[u8], at: usize) -> Option<char> {
let rest = haystack.get(at..)?;
let len = rest.len().min(4);
let s = match std::str::from_utf8(&rest[..len]) {
Ok(s) => s,
Err(e) => std::str::from_utf8(&rest[..e.valid_up_to()]).ok()?,
};
s.chars().next()
}
/// The char ending at byte `at` (`None` at the start or in invalid UTF-8).
fn char_before(haystack: &[u8], at: usize) -> Option<char> {
let head = haystack.get(..at)?;
let from = head.len().saturating_sub(4);
(from..head.len()).find_map(|i| std::str::from_utf8(&head[i..]).ok().and_then(|s| s.chars().next_back()))
}
+5 -15
Переглянути файл
@@ -22,7 +22,7 @@ pub use mask::FileMask;
pub use pattern::ScopePattern;
pub use replace::{
ReplaceEvent, ReplaceHost, ReplacePreview, ReplaceSummary, ReplaceTarget, apply_edits, preserve_case, preview,
replace_files, replace_files_in_context, replacement_edits,
replace_files, replacement_edits,
};
pub use words::{WordFiles, WordQuery, files_with_word};
@@ -99,15 +99,8 @@ impl SearchContext {
}
}
/// Whether a match starting at byte `at` is kept, given the file's sorted comments and
/// string literals. Find and Replace both filter with it, so they keep the same matches.
pub fn keeps(self, literals: &[LiteralRange], at: usize) -> bool {
let i = literals.partition_point(|l| l.start <= at);
self.accepts(literals[..i].last().filter(|l| at < l.end).map(|l| l.kind))
}
/// Only matches inside comments / string literals: files without any are skipped.
pub(crate) fn needs_literals(self) -> bool {
fn needs_literals(self) -> bool {
matches!(self, Self::InComments | Self::InStringLiterals)
}
}
@@ -167,8 +160,7 @@ pub type PathFilter<'a> = &'a (dyn Fn(&str) -> bool + Sync);
pub struct LineMatch {
/// 0-based line.
pub line: u32,
/// Line text, truncated around the matches for very long lines: such a line comes as one
/// `LineMatch` per window, so the same `line` can repeat.
/// Line text, truncated around the match for very long lines.
pub text: String,
/// UTF-16 column ranges within `text`.
pub ranges: Vec<(u32, u32)>,
@@ -293,9 +285,7 @@ pub fn match_ranges(text: &str, query: &SearchQuery) -> IdeResult<Vec<(usize, us
}
let compiled = query::compile(query)?;
let mut out = Vec::new();
iter::for_each_match(&compiled.matcher, compiled.whole_word, text.as_bytes(), 0, |m| {
out.push((m.start(), m.end()))
});
iter::for_each_match(&compiled.matcher, text.as_bytes(), 0, |m| out.push((m.start(), m.end())));
Ok(out)
}
@@ -318,7 +308,7 @@ pub fn replace_in_text(text: &str, query: &SearchQuery, replacement: &str) -> Id
let mut out = Vec::with_capacity(text.len());
let mut count = 0u32;
let mut last = 0;
iter::for_each_captures(matcher, compiled.whole_word, haystack, &mut caps, |caps| {
iter::for_each_captures(matcher, haystack, &mut caps, |caps| {
let Some(m) = caps.get(0) else { return };
out.extend_from_slice(&haystack[last..m.start()]);
last = m.end();
+14 -65
Переглянути файл
@@ -1,6 +1,5 @@
//! Turns a matched line plus byte ranges into [`LineMatch`]es with UTF-16
//! columns. A very long line is cut into windows: one around its first match
//! and the matches that fit with it, then one around each match left out.
//! Turns a matched line plus byte ranges into a [`LineMatch`] with UTF-16
//! columns, truncating very long lines to a window around the first match.
use crate::LineMatch;
@@ -9,57 +8,33 @@ pub(crate) const MAX_LINE_LEN: usize = 500;
/// How much text before the first match a truncated line keeps.
const CONTEXT_BEFORE: usize = 100;
/// Appends the matches of one line to `out`: a single [`LineMatch`], or one per window of a
/// very long line. `line` excludes the line terminator; `ranges` are sorted, non-overlapping
/// `line` excludes the line terminator; `ranges` are sorted, non-overlapping
/// byte ranges within `line`.
pub(crate) fn line_matches(line_no: u32, line: &[u8], ranges: &[(usize, usize)], out: &mut Vec<LineMatch>) {
pub(crate) fn line_match(line_no: u32, line: &[u8], ranges: &[(usize, usize)]) -> LineMatch {
match std::str::from_utf8(line) {
Ok(s) => from_str(line_no, s, ranges, out),
Ok(s) => from_str(line_no, s, ranges),
Err(_) => {
let (s, mapped) = lossy(line, ranges);
from_str(line_no, &s, &mapped, out)
from_str(line_no, &s, &mapped)
}
}
}
#[cfg(test)]
fn line_match(line_no: u32, line: &[u8], ranges: &[(usize, usize)]) -> LineMatch {
let mut out = Vec::new();
line_matches(line_no, line, ranges, &mut out);
out.swap_remove(0)
}
fn from_str(line_no: u32, s: &str, ranges: &[(usize, usize)], out: &mut Vec<LineMatch>) {
if s.len() <= MAX_LINE_LEN || utf16_len(s.as_bytes()) <= MAX_LINE_LEN {
out.push(in_window(line_no, s, ranges, (0, s.len())).0);
return;
}
let mut rest = ranges;
loop {
let bounds = window(s, floor_boundary(s, rest.first().map_or(0, |r| r.0.min(s.len()))));
let (m, used) = in_window(line_no, s, rest, bounds);
out.push(m);
rest = &rest[used.max(1)..];
if rest.is_empty() {
break;
}
}
}
/// The [`LineMatch`] of the text in `bounds` with the leading `ranges` that end inside it (at
/// least the first one, cut to the window), and how many ranges it took.
fn in_window(line_no: u32, s: &str, ranges: &[(usize, usize)], (start, end): (usize, usize)) -> (LineMatch, usize) {
fn from_str(line_no: u32, s: &str, ranges: &[(usize, usize)]) -> LineMatch {
let (start, end) = if s.len() <= MAX_LINE_LEN || utf16_len(s.as_bytes()) <= MAX_LINE_LEN {
(0, s.len())
} else {
window(s, floor_boundary(s, ranges.first().map_or(0, |r| r.0.min(s.len()))))
};
let text = &s[start..end];
let text_offset = if start == 0 { 0 } else { utf16_len(&s.as_bytes()[..start]) };
let mut out = Vec::with_capacity(ranges.len());
let (mut pos, mut col) = (start, 0usize);
let mut used = 0;
for &(a, b) in ranges {
if a > end || (a == end && b > a) || (used > 0 && b > end) {
if a > end || (a == end && b > a) {
break;
}
used += 1;
let (a, b) = (floor_boundary(s, a.max(start)), ceil_boundary(s, b.min(end)));
if a < pos {
continue;
@@ -70,7 +45,7 @@ fn in_window(line_no: u32, s: &str, ranges: &[(usize, usize)], (start, end): (us
pos = b;
out.push((col_a as u32, col as u32));
}
(LineMatch { line: line_no, text: text.to_owned(), ranges: out, text_offset: text_offset as u32 }, used)
LineMatch { line: line_no, text: text.to_owned(), ranges: out, text_offset: text_offset as u32 }
}
/// Byte window `[start, end)` of at most `MAX_LINE_LEN` UTF-16 units that
@@ -211,30 +186,4 @@ mod tests {
assert_eq!(m.ranges, vec![(100, 106)]);
assert!(utf16_len(m.text.as_bytes()) <= MAX_LINE_LEN);
}
#[test]
fn matches_outside_the_first_window_get_their_own() {
// Two matches 100 apart share a window; the one 1000 further gets another.
let s = format!("{}ab{}cd{}ef{}", "x".repeat(1000), "x".repeat(100), "x".repeat(1000), "x".repeat(10));
let at = |needle: &str| s.find(needle).unwrap();
let ranges = [(at("ab"), at("ab") + 2), (at("cd"), at("cd") + 2), (at("ef"), at("ef") + 2)];
let mut out = Vec::new();
line_matches(7, s.as_bytes(), &ranges, &mut out);
let found: Vec<Vec<u32>> =
out.iter().map(|m| m.ranges.iter().map(|&(a, _)| m.text_offset + a).collect()).collect();
let col = |needle: &str| at(needle) as u32;
assert_eq!(found, vec![vec![col("ab"), col("cd")], vec![col("ef")]]);
assert!(out.iter().all(|m| m.line == 7 && utf16_len(m.text.as_bytes()) <= MAX_LINE_LEN));
assert_eq!(&out[1].text[out[1].ranges[0].0 as usize..out[1].ranges[0].1 as usize], "ef");
}
#[test]
fn a_match_longer_than_the_window_is_cut_to_it() {
let s = format!("{}{}tail", "x".repeat(100), "y".repeat(1000));
let mut out = Vec::new();
line_matches(0, s.as_bytes(), &[(100, 1100), (1100, 1104)], &mut out);
assert_eq!(out.len(), 2);
assert_eq!(out[0].ranges, vec![(100, 500)]);
assert_eq!(out[1].text_offset + out[1].ranges[0].0, 1100);
}
}
+3 -7
Переглянути файл
@@ -9,8 +9,6 @@ use ide_core::{IdeError, IdeResult};
pub(crate) struct Compiled {
pub matcher: RegexMatcher,
pub multi_line: bool,
/// Keep only whole-word matches ([`crate::iter`] checks IDEA's rule on each match).
pub whole_word: bool,
}
/// The line terminator shared by the matcher and the searcher. CRLF mode lets
@@ -21,13 +19,12 @@ pub(crate) fn line_terminator() -> LineTerminator {
pub(crate) fn compile(query: &SearchQuery) -> IdeResult<Compiled> {
let multi_line = needs_multi_line(query);
let whole_word = query.whole_word;
match build(query, multi_line) {
Ok(matcher) => Ok(Compiled { matcher, multi_line, whole_word }),
Ok(matcher) => Ok(Compiled { matcher, multi_line }),
// Patterns such as `[\n]` or `\x0A` can only match across lines;
// retry in multi-line mode before reporting an error.
Err(err) if !multi_line => match build(query, true) {
Ok(matcher) => Ok(Compiled { matcher, multi_line: true, whole_word }),
Ok(matcher) => Ok(Compiled { matcher, multi_line: true }),
Err(_) => Err(invalid_pattern(query, &err)),
},
Err(err) => Err(invalid_pattern(query, &err)),
@@ -38,8 +35,7 @@ fn build(query: &SearchQuery, multi_line: bool) -> Result<RegexMatcher, grep_reg
let mut b = RegexMatcherBuilder::new();
b.case_smart(false)
.case_insensitive(!query.case_sensitive)
// Not `.word()`: ripgrep's rule wants a non-word character on both sides even of
// `foo(`, IDEA's (in `iter`) only beside the match's identifier characters.
.word(query.whole_word)
.fixed_strings(!query.is_regex)
.unicode(true)
// `^`/`$` always mean start/end of line, as in IDEA and ripgrep.
+7 -35
Переглянути файл
@@ -3,7 +3,7 @@
//! (the document layer in the app, so open editors update and each file is one
//! undoable step).
use crate::{LiteralRange, Literals, SearchContext, SearchQuery, iter, query};
use crate::{SearchQuery, iter, query};
use grep_matcher::{Captures, Matcher};
use ide_core::{CancellationToken, IdeError, IdeResult, Pos, Range, TextEdit};
use serde::{Deserialize, Serialize};
@@ -128,11 +128,10 @@ pub fn replacement_edits(
preserve: bool,
only: Option<&[Pos]>,
) -> IdeResult<Vec<TextEdit>> {
edits_except(text, query, replacement, preserve, only, None, None)
edits_except(text, query, replacement, preserve, only, None)
}
/// [`replacement_edits`] leaving out the matches that start at `skip` and, given the text's
/// comments and string literals, those outside the query's [`crate::SearchContext`].
/// [`replacement_edits`] leaving out the matches that start at `skip`.
fn edits_except(
text: &str,
query: &SearchQuery,
@@ -140,7 +139,6 @@ fn edits_except(
preserve: bool,
only: Option<&[Pos]>,
skip: Option<&[Pos]>,
literals: Option<&[LiteralRange]>,
) -> IdeResult<Vec<TextEdit>> {
if query.pattern.is_empty() {
return Ok(Vec::new());
@@ -155,13 +153,10 @@ fn edits_except(
let mut caps = matcher.new_captures().map_err(|e| IdeError::internal(e.to_string()))?;
let mut edits = Vec::new();
let mut buf = Vec::new();
iter::for_each_captures(matcher, compiled.whole_word, haystack, &mut caps, |caps| {
iter::for_each_captures(matcher, haystack, &mut caps, |caps| {
let Some(m) = caps.get(0) else { return };
let start = lines.pos(m.start());
if only.as_ref().is_some_and(|o| !o.contains(&start))
|| skip.contains(&start)
|| literals.is_some_and(|l| !query.context.keeps(l, m.start()))
{
if only.as_ref().is_some_and(|o| !o.contains(&start)) || skip.contains(&start) {
return;
}
let mut new_text = if query.is_regex {
@@ -232,23 +227,6 @@ pub fn replace_files(
cancel: &CancellationToken,
on_event: &dyn Fn(ReplaceEvent),
) -> IdeResult<ReplaceSummary> {
replace_files_in_context(host, query, replacement, preserve, targets, None, cancel, on_event)
}
/// [`replace_files`] honouring [`SearchQuery::context`] with the comments and string literals
/// `literals` finds, as [`crate::search_in_context`] does; without it every match is plain code.
#[allow(clippy::too_many_arguments)]
pub fn replace_files_in_context(
host: &dyn ReplaceHost,
query: &SearchQuery,
replacement: &str,
preserve: bool,
targets: &[ReplaceTarget],
literals: Option<Literals<'_>>,
cancel: &CancellationToken,
on_event: &dyn Fn(ReplaceEvent),
) -> IdeResult<ReplaceSummary> {
let literals = literals.filter(|_| query.context != SearchContext::Any);
// Fail fast on an invalid pattern instead of once per file.
if !query.pattern.is_empty() {
query::compile(query)?;
@@ -266,14 +244,8 @@ pub fn replace_files_in_context(
if only.is_some_and(|o| o.is_empty()) {
continue;
}
let result = host.edit_file(&target.path, &mut |text| {
let found = match literals.map(|l| l(&target.path, text)) {
// No syntax tree: nothing is in a comment or string, as in the search.
Some(None) if query.context.needs_literals() => return Ok(Vec::new()),
found => found.map(Option::unwrap_or_default),
};
edits_except(text, query, replacement, preserve, only, skip, found.as_deref())
});
let result =
host.edit_file(&target.path, &mut |text| edits_except(text, query, replacement, preserve, only, skip));
match result {
Ok(n) => {
if n > 0 {
+2 -45
Переглянути файл
@@ -1,7 +1,7 @@
use ide_core::{CancellationToken, IdeError, IdeResult, Pos, TextEdit};
use ide_search::{
LiteralKind, LiteralRange, ReplaceEvent, ReplaceHost, ReplaceTarget, SearchQuery, SearchScope, preserve_case,
preview, replace_files, replace_files_in_context, replacement_edits,
ReplaceEvent, ReplaceHost, ReplaceTarget, SearchQuery, SearchScope, preserve_case, preview, replace_files,
replacement_edits,
};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
@@ -169,46 +169,3 @@ fn replace_files_respects_selected_matches_and_invalid_patterns() {
let err = replace_files(&docs, &regex("("), "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:?}");
}
}
-65
Переглянути файл
@@ -132,36 +132,6 @@ fn whole_word() {
assert_eq!(views[0].matches[0].ranges, vec![(0, 3), (27, 30), (32, 35)]);
}
/// IDEA's whole word: a word boundary is needed only at an edge where the match has an
/// identifier character; a punctuation edge only needs a different character beside it.
#[test]
fn whole_word_needs_a_boundary_only_at_identifier_edges() {
let starts = |text: &str, q: SearchQuery| -> Vec<usize> {
let q = SearchQuery { whole_word: true, ..q };
ide_search::match_ranges(text, &q).unwrap().into_iter().map(|r| r.0).collect()
};
let text = "doWork(arg); redoWork(x); list: string[] = [];";
assert_eq!(starts(text, query("doWork(")), [0]);
assert_eq!(starts(text, query("(arg)")), [6]);
assert_eq!(starts(text, query("[]")), [38, 43]);
assert_eq!(starts(text, query("list")), [26]);
assert_eq!(starts("a == b; c === d", query("==")), [2]);
// `$` is part of an identifier (Java, Kotlin, JavaScript).
assert_eq!(starts("foo$bar foo", query("foo")), [8]);
// After an escape such as `\n`, a word starts.
assert_eq!(starts(r#"s = "\nfoo";"#, query("foo")), [7]);
assert_eq!(starts("é1 1 éé", query("1")), [4]);
// Regex matches follow the same rule.
assert_eq!(starts(text, regex(r"\w+\(")), [0, 13]);
assert_eq!(starts(text, regex(r"\[\]")), [38, 43]);
let p = project(&[("a.ts", text.as_bytes())]);
let (views, summary) = run(p.path(), &SearchQuery { whole_word: true, ..query("[]") });
assert_eq!((summary.matches, views[0].matches[0].ranges.clone()), (2, vec![(38, 40), (43, 45)]));
let (out, n) = replace_in_text(text, &SearchQuery { whole_word: true, ..query("doWork(") }, "run(").unwrap();
assert_eq!((out.as_str(), n), ("run(arg); redoWork(x); list: string[] = [];", 1));
}
#[test]
fn invalid_regex_is_reported() {
let p = project(&[("a.txt", b"x\n")]);
@@ -461,41 +431,6 @@ fn long_lines_are_truncated() {
assert_eq!(second.text, "short needle");
}
#[test]
fn every_match_of_a_long_line_is_reported_in_its_own_window() {
let long = format!("a='needle';{}b='needle';{}needle!\n", "x".repeat(2000), "y".repeat(2000));
let p = project(&[("min.js", long.as_bytes())]);
let (views, summary) = run(p.path(), &query("needle"));
assert_eq!(summary.matches, 3);
let lines = &views[0].matches;
assert_eq!(lines.len(), 3, "one window per far-apart match");
let line_utf16: Vec<u16> = long.trim_end().encode_utf16().collect();
let mut starts = Vec::new();
for m in lines {
assert_eq!(m.line, 0);
assert!(m.text.encode_utf16().count() <= 500);
let [(a, b)] = m.ranges[..] else { panic!("{:?}", m.ranges) };
let text: Vec<u16> = m.text.encode_utf16().collect();
assert_eq!(String::from_utf16(&text[a as usize..b as usize]).unwrap(), "needle");
let col = (m.text_offset + a) as usize;
assert_eq!(String::from_utf16(&line_utf16[col..col + 6]).unwrap(), "needle");
starts.push(ide_core::Pos::new(0, m.text_offset + a));
}
// The reported positions are the ones Replace takes: all of them are replaced.
let edits = ide_search::replacement_edits(&long, &query("needle"), "pin", false, Some(&starts)).unwrap();
assert_eq!(edits.len(), 3);
assert!(!ide_search::apply_edits(&long, &edits).contains("needle"));
}
#[test]
fn match_limit_counts_every_match_of_a_long_line() {
let long = format!("needle{}needle{}needle\n", "x".repeat(1000), "y".repeat(1000));
let p = project(&[("min.js", long.as_bytes())]);
let (views, summary) = run(p.path(), &SearchQuery { max_matches: 2, ..query("needle") });
assert!(summary.limit_hit);
assert_eq!((summary.matches, total(&views)), (2, 2));
}
#[test]
fn multi_line_matches() {
let p = project(&[("a.rs", b"fn foo() {\n bar();\n}\nfoo\nbar\n")]);
+2 -31
Переглянути файл
@@ -235,12 +235,6 @@ fn gix_status(r: &Repo, ignored: &IgnoredNames) -> IdeResult<Entries> {
Ok((map, conflicts))
}
/// Keeps `git status` from rewriting the index with refreshed stat data. Such a write is not
/// one of ours to the watcher, so it would schedule another refresh, which runs git again (#4792).
fn read_only() -> [(&'static str, &'static std::ffi::OsStr); 1] {
[("GIT_OPTIONAL_LOCKS", std::ffi::OsStr::new("0"))]
}
/// `git status --porcelain=v2`: what git lists, unreadable directories skipped.
/// In Restricted Mode git compares content without the repository's clean/process
/// filters and doesn't ask submodules for their own status (which runs their config).
@@ -251,7 +245,7 @@ fn cli_status(r: &Repo, ignored: &IgnoredNames) -> IdeResult<Entries> {
if !crate::execution_allowed() {
args.push("--ignore-submodules=dirty");
}
let out = crate::cli::run_env(r.root(), &args, None, &read_only())?;
let out = crate::cli::run(r.root(), &args, None)?;
Ok(parse_porcelain_v2(&String::from_utf8_lossy(&out.stdout), ignored))
}
@@ -266,7 +260,7 @@ fn cli_status_paths(r: &Repo, ignored: &IgnoredNames, paths: &[String]) -> IdeRe
}
args.push("--");
args.extend(paths.iter().map(String::as_str));
let out = crate::cli::run_env(r.root(), &args, None, &read_only())?;
let out = crate::cli::run(r.root(), &args, None)?;
Ok(parse_porcelain_v2(&String::from_utf8_lossy(&out.stdout), ignored))
}
@@ -403,29 +397,6 @@ mod tests {
assert!(staged.stdout.is_empty(), "{}", String::from_utf8_lossy(&staged.stdout));
}
/// #4792: the dirty-scope `git status` must not rewrite the index after refreshing stale
/// stat data, or the watcher sees a foreign index write and refreshes again.
#[test]
fn git_status_of_paths_leaves_the_index_alone() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
git(dir, &["init", "-q"]);
git(dir, &["config", "user.name", "Test User"]);
git(dir, &["config", "user.email", "[email protected]"]);
git(dir, &["config", "commit.gpgsign", "false"]);
std::fs::write(dir.join("a.txt"), "a\n").unwrap();
commit_all(dir, "base");
// Same content, new stat data: plain `git status` would refresh and write the index.
std::thread::sleep(std::time::Duration::from_millis(1100));
std::fs::write(dir.join("a.txt"), "a\n").unwrap();
let index = dir.join(".git/index");
let before = std::fs::read(&index).unwrap();
let repo = Repo::discover(dir).unwrap().expect("repository found");
assert!(status_paths(&repo, &["a.txt".to_owned()]).unwrap().is_empty());
assert_eq!(std::fs::read(&index).unwrap(), before, "git status rewrote the index");
}
/// git's porcelain answer (used when gitoxide can't read the tree) matches gitoxide's.
#[test]
fn git_and_gitoxide_report_the_same_status() {
+1 -3
Переглянути файл
@@ -422,8 +422,6 @@ impl Documents {
}
// Validate project rules before path resolution can erase linked components.
crate::file_ops::validate_workspace_edit_paths(edit)?;
// Editors know the paths as the edit named them, before link resolution.
let moves = edit.moves();
let mut edit = normalize_edit(edit)?;
let captured = !edit.preconditions.is_empty();
crate::file_ops::expand_workspace_edit(&mut edit)?;
@@ -503,7 +501,7 @@ impl Documents {
});
}
history.prune(SystemTime::now(), MAX_HISTORY_BYTES, MAX_HISTORY_AGE);
self.sink.emit(IdeEvent::WorkspaceEditApplied { id, paths: affected, moves, by_agent });
self.sink.emit(IdeEvent::WorkspaceEditApplied { id, paths: affected, by_agent });
}
Ok(())
}
+8 -1
Переглянути файл
@@ -4,13 +4,20 @@
use crate::documents::Documents;
use crate::history::LocalHistory;
pub use ide_core::FileMove;
use ide_core::{FileEdit, IdeError, IdeResult, WorkspaceEdit};
use parking_lot::Mutex;
use serde::{Deserialize, Serialize};
use specta::Type;
use std::path::{Path, PathBuf};
/// One file or folder move.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct FileMove {
pub from: ide_core::IpcPath,
pub to: ide_core::IpcPath,
}
/// What [`FileMoves::undo`] did.
#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
-10
Переглянути файл
@@ -898,16 +898,6 @@ mod tests {
);
}
#[test]
fn commit_default_inclusion_persists() {
let tmp = tempfile::tempdir().unwrap();
let store = SettingsStore::load(tmp.path(), None);
assert!(store.effective().vcs.commit.include_changes_by_default);
let settings = store.set(SettingsScope::Global, "vcs.commit.includeChangesByDefault", json!(false)).unwrap();
assert!(!settings.vcs.commit.include_changes_by_default);
assert!(!SettingsStore::load(tmp.path(), None).effective().vcs.commit.include_changes_by_default);
}
#[test]
fn inspection_profiles_live_in_their_layers() {
let tmp = tempfile::tempdir().unwrap();
+1 -40
Переглянути файл
@@ -1,4 +1,4 @@
use ide_core::{ChangeSet, FileEdit, FileMove, LanguageId, NullSink, Pos, Range, TextChange, TextEdit, WorkspaceEdit};
use ide_core::{ChangeSet, FileEdit, LanguageId, NullSink, Pos, Range, TextChange, TextEdit, WorkspaceEdit};
use ide_core::{IdeEvent, error::ErrorKind};
use ide_workspace::Documents;
use parking_lot::Mutex;
@@ -162,45 +162,6 @@ fn undo_id(events: &Mutex<Vec<IdeEvent>>) -> u32 {
.expect("successful transaction has one undo record")
}
#[test]
fn applied_event_lists_the_files_the_edit_renamed() {
for by_agent in [false, true] {
let tmp = tempfile::tempdir().unwrap();
let from = tmp.path().join("ListPrice.java");
let to = tmp.path().join("BasePrice.java");
let user = tmp.path().join("BulkDiscount.java");
std::fs::write(&from, "old").unwrap();
std::fs::write(&user, "old\n").unwrap();
let (docs, events) = recorded_documents();
let edit = WorkspaceEdit {
files: vec![edit(&user, "new"), FileEdit::Rename { from: from.clone().into(), to: to.clone().into() }],
..Default::default()
};
if by_agent { docs.apply_agent_workspace_edit(&edit) } else { docs.apply_workspace_edit(&edit) }.unwrap();
let moves = events
.lock()
.iter()
.find_map(|event| match event {
IdeEvent::WorkspaceEditApplied { moves, .. } => Some(moves.clone()),
_ => None,
})
.unwrap();
assert_eq!(moves, vec![FileMove { from: from.into(), to: to.into() }], "by_agent: {by_agent}");
}
}
#[test]
fn applied_event_lists_no_moves_for_text_edits() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("a.txt");
std::fs::write(&path, "old\n").unwrap();
let (docs, events) = recorded_documents();
docs.apply_workspace_edit(&WorkspaceEdit { files: vec![edit(&path, "new")], ..Default::default() }).unwrap();
assert!(
events.lock().iter().any(|e| matches!(e, IdeEvent::WorkspaceEditApplied { moves, .. } if moves.is_empty()))
);
}
#[test]
fn undo_keeps_the_encoding_chosen_for_a_file_opened_after_the_edit() {
let tmp = tempfile::tempdir().unwrap();
-8
Переглянути файл
@@ -139,14 +139,6 @@ Tasks are saved per project and survive restarts. When the agent supports resumi
- **Agent Configs**: discovers servers already configured in `~/.copilot/mcp-config.json` (and installed Copilot CLI plugins), `~/.claude.json`, `~/.codex/config.toml`, `~/.cursor/mcp.json`, `~/.gemini/settings.json`, `~/.jetbrains/mcp/mcp.json`, `.mcp.json`, and `.vscode/mcp.json` so you can import them into Global or Project settings with one click. You can also add or edit servers via structured fields or raw `mcpServers` JSON (**Add from JSON**), and run **Test Connection** to inspect the tools a server advertises.
- **Per-session (`MCP` / `/mcp`)**: in both **New Agent Task** and active task conversations, open **MCP** in the composer toolbar (or run `/mcp`) to enable or disable individual servers—including the built-in `openidea` server—for that task only, or click **Reset** to return to the inherited defaults.
### Agent skills
**Settings › Agents › Skills** lists every skill (`SKILL.md` folders) in one place, grouped by the folder it was found in: the project's `.agents/skills` and `.openidea/skills`, your `~/.agents/skills` (what `npx skills add` fills), and each CLI's own folders (`.claude/skills`, `.github/skills`, `.codex/skills`, `.cursor/skills`, `~/.claude/skills`, `~/.copilot/skills` and its installed plugins, `~/.codex/skills`, `~/.cursor/skills`). Symlinked copies of the same skill appear once, and expanding a row shows its canonical path and the `SKILL.md` validation result.
Each skill runs in one of three modes, set globally or per workspace without ever editing the skill's files: **Auto** (the model decides), **Slash only** (just `/name`), or **Off**. A workspace can turn a global skill off without prose rules in `AGENTS.md`; a skill the settings keep off shows as **Enable in Settings** in the session picker.
In the composer, `/skills` (or the **Add Context** menu) opens the per-session picker next to the MCP one: turn individual skills off for this task only, or **Reset** to the inherited modes. The `/` menu offers the active skills of every agent, and Claude Code, Copilot and Codex all receive the same set. Agents that only speak ACP keep their own `/` menu, so turning a skill off there stops OpenIDEA from offering it but is otherwise best-effort.
While the agent works, the line under the conversation says what it is doing: thinking, reading, editing, running a command, writing its reply.
## Add a custom agent
-8
Переглянути файл
@@ -139,14 +139,6 @@ agent 运行过一个任务后,新任务会以它自动批准所有操作的
- **智能体配置**:自动发现 `~/.copilot/mcp-config.json`(及已安装的 Copilot CLI 插件)、`~/.claude.json`、`~/.codex/config.toml`、`~/.cursor/mcp.json`、`~/.gemini/settings.json`、`~/.jetbrains/mcp/mcp.json`、`.mcp.json` 和 `.vscode/mcp.json` 中已配置的服务器,可一键导入到全局或项目设置。添加或编辑服务器时既可使用表单,也可直接粘贴 `mcpServers` JSON(**从 JSON 添加**),并可通过 **测试连接** 查看服务器声明的工具列表。
- **按会话覆盖(`MCP` / `/mcp`)**:在 **新建 Agent 任务** 和进行中的任务对话中,单击输入框工具栏的 **MCP**(或输入 `/mcp`),即可仅针对当前任务开启或关闭任意服务器(包括内置的 `openidea` 服务器),或点击 **重置** 恢复继承的默认状态。
### 智能体技能
**设置 › 智能体 › 技能** 把所有技能(`SKILL.md` 文件夹)汇总在一个列表里,并按发现它们的文件夹分组:项目的 `.agents/skills` 与 `.openidea/skills`、你的 `~/.agents/skills`(即 `npx skills add` 填充的目录),以及各 CLI 自己的文件夹(`.claude/skills`、`.github/skills`、`.codex/skills`、`.cursor/skills`、`~/.claude/skills`、`~/.copilot/skills` 及其已安装插件、`~/.codex/skills`、`~/.cursor/skills`)。同一技能的符号链接副本只显示一次,展开一行可以看到其规范路径与 `SKILL.md` 的校验结果。
每个技能有三种运行模式,可全局或按工作区设置,且从不改动技能自身的文件:**自动**(由模型决定)、**仅斜杠**(只通过 `/名称` 调用)或 **关闭**。工作区可以关闭一个全局技能,而无需在 `AGENTS.md` 里写文字规则;被设置关闭的技能在会话选择器中会显示为 **在设置中启用**。
在输入框中,`/skills`(或 **添加上下文** 菜单)会打开与 MCP 并排的会话技能选择器:仅为当前任务关闭单个技能,或点击 **重置** 恢复继承的模式。`/` 菜单会列出所有智能体的活动技能,Claude Code、Copilot 与 Codex 收到的是同一套技能。只讲 ACP 协议的智能体保留自己的 `/` 菜单,因此在那里关闭技能只会让 OpenIDEA 不再提供它,其余尽力而为。
agent 工作时,对话下方的状态行显示它正在做什么:思考、读取、编辑、运行命令、输出回复。
## 添加自定义 agent
-88
Переглянути файл
@@ -1,88 +0,0 @@
import type { Page } from "@playwright/test";
import { expect, test } from "./fixtures";
async function openSaveActions(page: Page) {
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("Optimize imports");
await settings.getByRole("treeitem", { name: "Actions on Save", exact: true }).click();
await search.clear();
return settings;
}
test("Actions on Save aligns each enabled action with its trigger in wide and narrow panes", async ({
workbench: page,
}) => {
const settings = await openSaveActions(page);
const table = settings.getByRole("table", { name: "Actions on Save", exact: true });
const action = table.getByRole("columnheader", { name: "Action", exact: true });
const heading = table.getByRole("columnheader", { name: "Activated on", exact: true });
const format = table.getByRole("row", { name: /Reformat code/ });
const imports = table.getByRole("row", { name: /Optimize imports/ });
const cleanup = table.getByRole("row", { name: /Run code cleanup/ });
const trigger = (action: typeof format) => action.getByRole("cell").nth(1);
await expect(table.getByRole("row")).toHaveCount(4);
await format.getByRole("checkbox").check();
await imports.getByRole("checkbox").press("Space");
await expect(trigger(format)).toHaveText("Save or Save All");
await expect(trigger(imports)).toHaveText("Save or Save All");
await expect(trigger(cleanup)).toBeEmpty();
for (const width of [1120, 520]) {
await page.setViewportSize({ width, height: 740 });
await expect(heading).toBeInViewport({ ratio: 1 });
await expect(trigger(imports)).toBeInViewport({ ratio: 1 });
const column = (await heading.boundingBox())!;
expect((await action.boundingBox())!.width).toBeGreaterThan(column.width);
expect(
await trigger(imports).evaluate((cell) => {
const range = document.createRange();
range.selectNodeContents(cell.firstElementChild!);
return range.getClientRects().length;
}),
).toBe(1);
for (const row of [format, imports, cleanup]) {
const cell = (await trigger(row).boundingBox())!;
expect(Math.abs(column.x - cell.x)).toBeLessThan(1);
expect(Math.abs(column.width - cell.width)).toBeLessThan(1);
}
expect(await table.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await expect(settings.getByRole("button", { name: "Editor › General", exact: true })).toBeInViewport();
}
await format.getByRole("checkbox").uncheck();
await expect(trigger(format)).toBeEmpty();
await expect(trigger(imports)).toHaveText("Save or Save All");
});
test("Actions on Save stages the same preferences as Editor General and honors Apply and Cancel", async ({
workbench: page,
}) => {
const settings = await openSaveActions(page);
const format = settings.getByRole("checkbox", { name: "Reformat code", exact: true });
const imports = settings.getByRole("checkbox", { name: "Optimize imports", exact: true });
const cleanup = settings.getByRole("checkbox", { name: "Run code cleanup", exact: true });
const apply = settings.getByRole("button", { name: "Apply", exact: true });
const cancel = settings.getByRole("button", { name: "Cancel", exact: true });
await format.check();
await imports.check();
await settings.getByRole("button", { name: "Editor › General", exact: true }).click();
await expect(settings.getByRole("checkbox", { name: "Reformat code on save", exact: true })).toBeChecked();
await settings.getByRole("button", { name: "Back", exact: true }).click();
await expect(format).toBeChecked();
await expect(imports).toBeChecked();
await apply.click();
await expect(apply).toBeDisabled();
await cancel.click();
await openSaveActions(page);
await expect(format).toBeChecked();
await expect(imports).toBeChecked();
await cleanup.check();
await cancel.click();
await openSaveActions(page);
await expect(cleanup).not.toBeChecked();
await expect(format).toBeChecked();
await expect(imports).toBeChecked();
});
+2 -62
Переглянути файл
@@ -1,18 +1,7 @@
import type { Page } from "@playwright/test";
import type { BuildModel, BuildTool, MavenDependency } from "../src/platform/ipc";
import type { BuildModel, BuildTool } from "../src/platform/ipc";
import { expect, stubDesktop, test } from "./fixtures";
const jsonCore: MavenDependency = {
groupId: "com.example.json",
artifactId: "json-core",
version: "2.1.0",
type: "jar",
classifier: null,
scope: "compile",
optional: false,
children: [],
};
const model: BuildModel = {
maven: {
projects: [
@@ -28,14 +17,7 @@ const model: BuildModel = {
modules: [],
aggregated: false,
plugins: [],
dependencies: [
jsonCore,
{
...jsonCore,
artifactId: "json-mapper",
children: [{ ...jsonCore, version: "2.0.0", omitted: "conflict", conflictWith: "2.1.0" }],
},
],
dependencies: [],
profiles: [],
javaVersion: 21,
command: "mvn",
@@ -115,45 +97,3 @@ for (const tool of ["maven", "gradle"] as const) {
await expect(menu).toBeHidden();
});
}
test("Dependency Analyzer pairs its pane controls and stacks usages in a narrow editor", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 1360, height: 780 });
await showTool(page, "maven");
const toolActions = page.getByRole("toolbar", { name: "Maven actions" });
await toolActions.getByRole("button", { name: "More Actions", exact: true }).click();
await page.getByRole("menuitem", { name: "Analyze Dependencies…", exact: true }).click();
const filters = page.getByRole("toolbar", { name: "Dependency Analyzer", exact: true });
const resolved = page.getByRole("heading", { name: "Resolved Dependencies", exact: true });
const usages = page.getByRole("heading", { name: "Usages of com.example.json:json-core:2.1.0", exact: true });
const dependencies = page.getByRole("tree", { name: "Dependencies", exact: true });
const core = dependencies.getByRole("treeitem", { name: /^com\.example\.json:json-core\b/ });
const treeMode = page.getByRole("button", { name: "Show as Tree", exact: true });
const conflicts = filters.getByRole("button", { name: "Show conflicts only", exact: true });
await expect(resolved).toBeVisible();
await expect(filters.getByRole("button", { name: "Show as Tree" })).toHaveCount(0);
await treeMode.click();
await expect(treeMode).toHaveAttribute("aria-pressed", "true");
await page.getByRole("button", { name: "Show as List", exact: true }).click();
await conflicts.press("Space");
await expect(conflicts).toHaveAttribute("aria-pressed", "true");
await expect(dependencies.getByRole("treeitem")).toHaveCount(1);
await core.click();
await expect(usages).toBeVisible();
await expect(page.getByText("omitted for conflict with 2.1.0")).toBeVisible();
const wideLeft = (await resolved.boundingBox())!;
const wideRight = (await usages.boundingBox())!;
expect(Math.abs(wideLeft.y - wideRight.y)).toBeLessThan(1);
expect(wideRight.x).toBeGreaterThan(wideLeft.x + wideLeft.width);
await page.setViewportSize({ width: 790, height: 780 });
await expect
.poll(async () => (await usages.boundingBox())!.y - (await resolved.boundingBox())!.y)
.toBeGreaterThan(100);
expect(Math.abs((await usages.boundingBox())!.x - (await resolved.boundingBox())!.x)).toBeLessThan(1);
expect(await filters.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await expect(core).toHaveAttribute("aria-selected", "true");
await expect(page.getByRole("button", { name: "Copy Coordinates" })).toBeInViewport({ ratio: 1 });
});
-80
Переглянути файл
@@ -1,80 +0,0 @@
import type { Page } from "@playwright/test";
import { expect, test } from "./fixtures";
async function openCompletionSettings(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("First letter only");
await dialog.getByRole("treeitem", { name: "Code Completion", exact: true }).click();
await search.clear();
return dialog;
}
test("Code Completion puts both case-matching choices beside the checkbox and keeps them in view", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 1120, height: 740 });
const dialog = await openCompletionSettings(page);
const matchCase = dialog.getByRole("checkbox", { name: "Match case:", exact: true });
const choices = dialog.getByRole("radiogroup", { name: "Match case:", exact: true });
const first = choices.getByRole("radio", { name: "First letter only", exact: true });
const all = choices.getByRole("radio", { name: "All letters", exact: true });
await expect(first).toBeChecked();
await expect(all).not.toBeChecked();
const matchBox = (await matchCase.boundingBox())!;
const firstBox = (await first.boundingBox())!;
const allBox = (await all.boundingBox())!;
expect(Math.abs(matchBox.y - firstBox.y)).toBeLessThan(1);
expect(Math.abs(firstBox.y - allBox.y)).toBeLessThan(1);
expect(firstBox.x).toBeGreaterThan(matchBox.x + matchBox.width);
expect(allBox.x).toBeGreaterThan(firstBox.x + firstBox.width);
for (const width of [580, 520]) {
await page.setViewportSize({ width, height: 740 });
await expect(matchCase).toBeInViewport({ ratio: 1 });
await expect(first).toBeInViewport({ ratio: 1 });
await expect(all).toBeInViewport({ ratio: 1 });
await expect(dialog.getByText("All letters", { exact: true })).toBeInViewport({ ratio: 1 });
}
});
test("Code Completion preserves case and popup delay preferences across Apply and Cancel", async ({
workbench: page,
}) => {
const dialog = await openCompletionSettings(page);
const matchCase = dialog.getByRole("checkbox", { name: "Match case:", exact: true });
const first = dialog.getByRole("radio", { name: "First letter only", exact: true });
const all = dialog.getByRole("radio", { name: "All letters", exact: true });
await matchCase.uncheck();
await expect(first).toBeDisabled();
await expect(all).toBeDisabled();
await expect(first).toBeChecked();
await matchCase.check();
await first.press("ArrowRight");
await expect(all).toBeChecked();
const docs = dialog.getByRole("textbox", { name: "Show the documentation popup in", exact: true });
const params = dialog.getByRole("textbox", { name: "Show the parameter info popup in", exact: true });
await dialog.getByRole("checkbox", { name: "Show the documentation popup in", exact: true }).check();
await dialog.getByRole("checkbox", { name: "Show the parameter info popup in", exact: true }).check();
await docs.fill("750");
await params.fill("1250");
const apply = dialog.getByRole("button", { name: "Apply", exact: true });
const cancel = dialog.getByRole("button", { name: "Cancel", exact: true });
await apply.click();
await expect(apply).toBeDisabled();
await cancel.click();
await openCompletionSettings(page);
await expect(all).toBeChecked();
await expect(docs).toHaveValue("750");
await expect(params).toHaveValue("1250");
await matchCase.uncheck();
await expect(all).toBeDisabled();
await expect(all).toBeChecked();
await cancel.click();
await openCompletionSettings(page);
await expect(matchCase).toBeChecked();
await expect(all).toBeChecked();
});
-28
Переглянути файл
@@ -76,34 +76,6 @@ test("⌘K commits the checked changes with the typed message", async ({ workben
await expect(changes.getByRole("checkbox", { name: "Include build.gradle.kts in commit" })).toBeHidden();
});
test("turning off default inclusion starts Commit with all files unchecked", async ({ workbench: page }) => {
await page.keyboard.press("Meta+,");
const settings = page.getByRole("dialog", { name: "Settings", exact: true });
const label = "Include changes in the commit by default";
await settings.getByRole("textbox", { name: "Search settings" }).fill(label);
await settings.getByRole("treeitem", { name: "Commit", exact: true }).click();
const toggle = settings.getByRole("checkbox", { name: label, exact: true });
await expect(toggle).toBeChecked();
await toggle.click();
await settings.getByRole("button", { name: "OK", exact: true }).click();
await expect(settings).not.toBeVisible();
await stubRepository(page);
await page.keyboard.press("Meta+k");
const panel = page.getByRole("region", { name: "Commit", exact: true });
const changes = panel.getByRole("tree", { name: "Changes" });
const tracked = changes.getByRole("checkbox", { name: "Include build.gradle.kts in commit" });
await expect(tracked).toHaveAttribute("aria-checked", "false");
await expect(changes.getByRole("checkbox", { name: "Include Unversioned Files in commit" })).not.toBeChecked();
await tracked.click();
await expect(tracked).toBeChecked();
await panel.getByRole("textbox", { name: "Commit message" }).fill("Commit the selected file");
await panel.getByRole("button", { name: "Commit", exact: true }).click();
await expect.poll(() => ipcCalls(page, "vcs_commit")).toHaveLength(1);
const [committed] = await ipcCalls(page, "vcs_commit");
expect(committed!.options).toMatchObject({ stage: [`${ROOT}/build.gradle.kts`] });
});
test("commit message history opens above the message without an empty icon column", async ({ workbench: page }) => {
await stubRepository(page);
await page.keyboard.press("Meta+k");
+104
Переглянути файл
@@ -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();
});
-41
Переглянути файл
@@ -1,41 +0,0 @@
import { expect, openFromTree, test } from "./fixtures";
test("Quick Switch Scheme stays centered and opens its numbered choices without leaving the editor", async ({
workbench: page,
}) => {
const editor = await openFromTree(page, "build.gradle.kts");
const content = editor.locator(".cm-content");
await content.focus();
const root = page.locator("html");
const theme = await root.getAttribute("data-theme");
const colorTheme = await root.getAttribute("data-color-theme");
await page.keyboard.press("Control+Backquote");
const menu = page.getByRole("menu", { name: /^(Switch Scheme|Context menu)$/ });
await expect(menu).toBeVisible();
for (const { width, height } of [
{ width: 1120, height: 680 },
{ width: 620, height: 540 },
]) {
await page.setViewportSize({ width, height });
await expect(async () => {
const bounds = await menu.locator("xpath=..").boundingBox();
expect(Math.abs(bounds!.x + bounds!.width / 2 - width / 2)).toBeLessThan(1);
expect(Math.abs(bounds!.y + bounds!.height / 2 - height / 2)).toBeLessThan(1);
}).toPass({ timeout: 3000 });
}
await expect(menu.getByText("Switch Scheme", { exact: true })).toBeVisible();
await expect(menu.getByRole("menuitem", { name: "Editor Color Scheme" })).toBeFocused();
await expect(menu.locator("[data-menu-number]")).toHaveText(["1", "2", "3", "4"]);
await page.keyboard.press("4");
const light = page.getByRole("menuitemcheckbox", { name: "Solarized Light" });
await light.hover();
await expect(root).toHaveAttribute("data-color-theme", "solarized-light");
await page.keyboard.press("Escape");
await expect(light).toBeHidden();
await expect(menu).toBeVisible();
await page.keyboard.press("Escape");
await expect(menu).toBeHidden();
await expect(content).toBeFocused();
await expect.poll(() => root.getAttribute("data-theme")).toBe(theme);
await expect.poll(() => root.getAttribute("data-color-theme")).toBe(colorTheme);
});
-20
Переглянути файл
@@ -65,26 +65,6 @@ for (const locale of ["en", "zh"]) {
});
}
test("keeps Open project in options within narrow System Settings", async ({ workbench: page }) => {
await page.keyboard.press("Meta+,");
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
await expect(dialog).toBeVisible();
await selectPage(page, "general");
const group = dialog.getByRole("radiogroup", { name: "Open project in", exact: true });
const longest = group.getByRole("radio", { name: "New tab in current window", exact: true });
await expect(longest).toBeVisible();
await page.setViewportSize({ width: 520, height: 760 });
const overflow = await longest.evaluate(async (radio) => {
await new Promise<void>((resolve) => requestAnimationFrame(() => requestAnimationFrame(() => resolve())));
const label = radio.closest("label")!;
const group = radio.closest('[role="radiogroup"]')!;
const text = document.createRange();
text.selectNodeContents(label);
return text.getBoundingClientRect().right - group.getBoundingClientRect().right;
});
expect(overflow).toBeLessThanOrEqual(1);
});
test("settings sidebar resizes with mouse and keyboard and remembers its width", async ({ workbench: page }) => {
await page.keyboard.press("Meta+,");
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
-3
Переглянути файл
@@ -46,10 +46,7 @@ agent_set_command trusted project_host bin
agent_set_config trusted project_host bindings async
agent_set_env trusted project_host bindings sync
agent_set_mcp_overrides always project_host bindings sync
agent_set_skill_overrides always project_host bindings sync
agent_shell trusted project_host bindings async
agent_skills_list always project_host bindings async
agent_skills_set_mode always project_host bindings sync
agent_stop_background always project_host bindings async
agent_subscribe always project_host bindings sync
agent_unarchive always project_host bindings sync
+2 -114
Переглянути файл
@@ -143,23 +143,11 @@ export const commands = {
agentSetEnv: (id: string, env: { [key in string]: string }) => typedError<null, IdeError>(__TAURI_INVOKE("agent_set_env", { id, env })),
/** Updates per-session MCP server enable/disable overrides on `task`. */
agentSetMcpOverrides: (task: string, overrides: { [key in string]: boolean }) => typedError<AgentTask_Serialize, IdeError>(__TAURI_INVOKE("agent_set_mcp_overrides", { task, overrides })),
/** Updates per-session skill modes on `task`. */
agentSetSkillOverrides: (task: string, overrides: { [key in string]: AgentSkillMode }) => typedError<AgentTask_Serialize, IdeError>(__TAURI_INVOKE("agent_set_skill_overrides", { task, overrides })),
/**
* Runs a `!` line of the composer in the task's folder with the user's shell, without
* starting a turn; its output goes to the agent with the next message.
*/
agentShell: (task: string, command: string, request: RequestId) => typedError<null, IdeError>(__TAURI_INVOKE("agent_shell", { task, command, request })),
/**
* Every skill discovered in the project and the user's folders, with the mode a session
* of this project runs it with (without any session's own overrides).
*/
agentSkillsList: () => typedError<AgentSkillState[], IdeError>(__TAURI_INVOKE("agent_skills_list")),
/**
* Sets how `name` may run in `scope`, in the settings file of that scope, and returns the
* updated list. `SKILL.md` files are never touched; the default `auto` removes the entry.
*/
agentSkillsSetMode: (name: string, scope: McpScope, mode: AgentSkillMode) => typedError<AgentSkillState[], IdeError>(__TAURI_INVOKE("agent_skills_set_mode", { name, scope, mode })),
/** Stops one of the task's background tasks. */
agentStopBackground: (task: string, background: string) => typedError<null, IdeError>(__TAURI_INVOKE("agent_stop_background", { task, background })),
/**
@@ -550,7 +538,7 @@ export const commands = {
docOpenVirtual: (uri: string) => typedError<DocumentInfo, IdeError>(__TAURI_INVOKE("doc_open_virtual", { uri })),
/**
* Structure view: LSP document symbols when available (with tree-sitter
* visibility and type-alias kinds), tree-sitter otherwise.
* visibility), tree-sitter otherwise.
* Tree-sitter answers come from the per-document tree cache (incremental
* re-parse); large documents get no syntax structure.
*/
@@ -2700,11 +2688,6 @@ export type AgentSettings_Deserialize = {
* keyed by server name (`[agents.mcpServers.<name>]`).
*/
mcpServers?: { [key in string]: AgentMcpServer_Deserialize },
/**
* How agent skills may run, keyed by skill name (`[agents.skills.<name>]`); `SKILL.md`
* files on disk are never modified.
*/
skills?: { [key in string]: AgentSkillPolicy_Deserialize },
};
/** Settings › Agents: what the conversation shows and how messages are sent. */
@@ -2745,89 +2728,6 @@ export type AgentSettings_Serialize = {
* keyed by server name (`[agents.mcpServers.<name>]`).
*/
mcpServers: { [key in string]: AgentMcpServer_Serialize },
/**
* How agent skills may run, keyed by skill name (`[agents.skills.<name>]`); `SKILL.md`
* files on disk are never modified.
*/
skills: { [key in string]: AgentSkillPolicy_Serialize },
};
/** One discovered skill: a folder with a `SKILL.md`. */
export type AgentSkill = {
/** The frontmatter `name`, else the folder's name. */
name: string,
description: string,
/** Canonical folder holding `SKILL.md` (symlinks resolved, so duplicates collapse). */
path: IpcPath,
source: AgentSkillSource,
/** The `SKILL.md` passes validation (`name` matches its folder, `description` present). */
valid: boolean,
/** What validation found (`name` mismatch, missing or over-long description…). */
warnings: string[],
};
/** How an agent skill may run (`[agents.skills.<name>] mode = …`). */
export type AgentSkillMode =
/** The model decides when to use it. */
"auto" |
/** Only when the user invokes it with `/name`. */
"slashOnly" |
/** Never. */
"off";
/** Which layer decided a skill's [`AgentSkillState::mode`]. */
export type AgentSkillOrigin = "none" | "session" | "workspace" | "user" |
/** An untrusted workspace's skills and policies may only turn skills off. */
"trust";
/** A skill's policy in Settings › Agents › Skills, stored without touching its `SKILL.md`. */
export type AgentSkillPolicy = AgentSkillPolicy_Serialize | AgentSkillPolicy_Deserialize;
/** A skill's policy in Settings › Agents › Skills, stored without touching its `SKILL.md`. */
export type AgentSkillPolicy_Deserialize = {
mode?: AgentSkillMode,
};
/** A skill's policy in Settings › Agents › Skills, stored without touching its `SKILL.md`. */
export type AgentSkillPolicy_Serialize = {
mode: AgentSkillMode,
};
/** Which CLI's own folders a skill was discovered in (Settings › Agents › Skills groups by it). */
export type AgentSkillSource =
/** The project's `.agents/skills` and `.openidea/skills`. */
"workspace" |
/** The user's `~/.agents/skills` (what `npx skills add` fills). */
"user" |
/** The project's `.claude/skills`. */
"claudeWorkspace" |
/** `~/.claude/skills`. */
"claudeUser" |
/** The project's `.github/skills` (Copilot's repository skills). */
"githubWorkspace" |
/** `~/.copilot/skills` and `~/.copilot/installed-plugins/*`. */
"copilotUser" |
/** The project's `.codex/skills`. */
"codexWorkspace" |
/** `~/.codex/skills`. */
"codexUser" |
/** The project's `.cursor/skills`. */
"cursorWorkspace" |
/** `~/.cursor/skills`. */
"cursorUser";
/**
* A skill as Settings › Agents › Skills shows it: discovery plus the effective mode and
* which layer decided it.
*/
export type AgentSkillState = {
skill: AgentSkill,
mode: AgentSkillMode,
/**
* What set `mode`: a session override, the workspace, the user's settings, workspace
* trust, or nothing (the default `auto`).
*/
origin: AgentSkillOrigin,
};
/** Where an agent comes from. */
@@ -2902,8 +2802,6 @@ export type AgentTask_Deserialize = {
background?: AgentBackgroundTask[],
/** Per-session MCP server enable/disable overrides (`server_name` -> `enabled`), including `"openidea"`. */
mcpOverrides?: { [key in string]: boolean },
/** Per-session skill modes (`skill name` -> mode), on top of the settings' policies. */
skillOverrides?: { [key in string]: AgentSkillMode },
/** Token counts of the last turn and context compressions, when the agent reports them. */
stats?: AgentSessionStats,
};
@@ -2954,8 +2852,6 @@ export type AgentTask_Serialize = {
background: AgentBackgroundTask[],
/** Per-session MCP server enable/disable overrides (`server_name` -> `enabled`), including `"openidea"`. */
mcpOverrides?: { [key in string]: boolean },
/** Per-session skill modes (`skill name` -> mode), on top of the settings' policies. */
skillOverrides?: { [key in string]: AgentSkillMode },
/** Token counts of the last turn and context compressions, when the agent reports them. */
stats: AgentSessionStats,
};
@@ -3906,7 +3802,6 @@ export type CommitSettings = {
* window and a Commit dialog.
*/
nonModal?: boolean,
includeChangesByDefault?: boolean,
/** Start with an empty message instead of the last one / the changelist's. */
clearInitialMessage?: boolean,
analyzeCode?: boolean,
@@ -7231,8 +7126,6 @@ version: number } |
{ type: "docDiskConflict"; doc: DocId; path: string } |
/** A complete workspace edit can be undone as one operation. */
{ type: "workspaceEditApplied"; id: number; paths: IpcPath[];
/** Files the edit renamed, as the edit named them: editors open on them follow. */
moves: FileMove[];
/**
* Made by an agent through the MCP server's tools: undoable like a refactoring, but
* not announced as one.
@@ -8268,10 +8161,7 @@ export type LineMarkerInfo = {
export type LineMatch = {
/** 0-based line. */
line: number,
/**
* Line text, truncated around the matches for very long lines: such a line comes as one
* `LineMatch` per window, so the same `line` can repeat.
*/
/** Line text, truncated around the match for very long lines. */
text: string,
/** UTF-16 column ranges within `text`. */
ranges: ([number, number])[],
@@ -9124,8 +9014,6 @@ export type NewAgentTask = {
base: string | null,
/** Per-session MCP server enable/disable overrides (`server_name` -> `enabled`). */
mcpOverrides?: { [key in string]: boolean },
/** Per-session skill modes (`skill name` -> mode). */
skillOverrides?: { [key in string]: AgentSkillMode },
/**
* Creates the task without sending `prompt` (it only names the task): the composer's
* `!` command runs in it first.
-3
Переглянути файл
@@ -571,10 +571,7 @@ describe("DocumentManager + slots", () => {
if (id === a.doc) throw new Error("disk full");
await save(id);
});
const logged = vi.spyOn(console, "error").mockImplementation(() => {});
await expect(manager.saveAll("explicit")).rejects.toThrow("disk full");
expect(logged).toHaveBeenCalledWith("saving /p/a.txt failed", expect.objectContaining({ message: "disk full" }));
logged.mockRestore();
expect(backend.files.get("/p/a.txt")).toBe("a\n");
expect(backend.files.get("/p/b.txt")).toBe("changed b\n");
expect(a.getMeta().dirty).toBe(true);
+1 -3
Переглянути файл
@@ -927,7 +927,7 @@ export class DocumentManager {
try {
await model.save("auto");
} catch (e) {
logError(`autosave of ${model.path} failed`, e);
console.warn(`autosave of ${model.path} failed`, e);
}
}
// As in IDEA, a file whose changes are not saved (autosave off, or a failed save) stays
@@ -985,8 +985,6 @@ export class DocumentManager {
.filter((m) => !(skipUntitled && isUntitledUri(m.path)))
.map((m) =>
m.save(reason).catch((e) => {
// The notification shows the message only; the log keeps the stack for reports.
logError(`saving ${m.path} failed`, e);
errors.push(e);
}),
),
+3 -68
Переглянути файл
@@ -1,14 +1,9 @@
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { redo, redoDepth, undo, undoDepth, history } from "@codemirror/commands";
import { EditorView } from "@codemirror/view";
import { _provideOpenEditorPaths, workspaceEditHistory } from "@/editor/api";
import { workspaceEditHistory } from "@/editor/api";
import { installWorkspaceEditUndo } from "@/features/code-insight/workspaceUndo";
import {
provideEditorService,
provideNotificationService,
type EditorService,
type NotificationService,
} from "@/workbench/contributions";
import { provideNotificationService, type NotificationService } from "@/workbench/contributions";
import { emitLocalIdeEvent } from "@/platform/ipc";
import { createMemoryBackend, type MemoryBackend } from "../backend";
import { _resetLanguages } from "../cm/languages";
@@ -66,7 +61,6 @@ async function rename() {
type: "workspaceEditApplied",
id: 9,
paths: ["/p/A.java", "/p/B.java", "/p/closed.java"],
moves: [],
byAgent: false,
});
}
@@ -194,13 +188,7 @@ it("rebuilds multiple redo markers in order when a closed file opens", async ()
const a = await open("/p/A.java");
await rename();
await replace("alt");
emitLocalIdeEvent({
type: "workspaceEditApplied",
id: 10,
paths: ["/p/A.java", "/p/B.java"],
moves: [],
byAgent: true,
});
emitLocalIdeEvent({ type: "workspaceEditApplied", id: 10, paths: ["/p/A.java", "/p/B.java"], byAgent: true });
commands.undoWorkspaceEdit.mockImplementation(async (id: number) => {
await replace(id === 10 ? "new" : "old");
return { status: "ok", data: null };
@@ -269,56 +257,3 @@ it("keeps refactoring markers current while a secondary view is unmounted", asyn
expect(commands.undoWorkspaceEdit).toHaveBeenCalledOnce();
att.release();
});
it("editors on a file the edit renamed reopen at its new path, through Undo and Redo", async () => {
const live = () => slots.filter((s) => !closed.has(s));
const closed = new Set<EditorSlot>();
const openFile = vi.fn(async (path: string) => {
if (!live().some((s) => s.model.path === path)) await open(path);
});
const closePath = vi.fn(async (path: string) => {
for (const s of live())
if (s.model.path === path) {
closed.add(s);
s.dispose();
}
return true;
});
provideEditorService({
openFile,
closePath,
activePath: () => live().at(-1)?.model.path ?? null,
saveAll: vi.fn(),
} as unknown as EditorService);
_provideOpenEditorPaths(() => live().map((s) => s.model.path));
backend.files.set("/p/Renamed.java", "old");
const moved = async (from: string, to: string, run: () => Promise<unknown>) => {
openFile.mockClear();
await run();
await vi.waitFor(() => expect(openFile).toHaveBeenCalledExactlyOnceWith(to, { focus: false }));
expect(closePath).toHaveBeenCalledWith(from);
expect(live().map((s) => s.model.path)).toEqual(["/p/B.java", to]);
};
try {
await open("/p/B.java");
await open("/p/A.java");
await moved("/p/A.java", "/p/Renamed.java", async () => {
await replace("new");
emitLocalIdeEvent({
type: "workspaceEditApplied",
id: 11,
paths: ["/p/A.java", "/p/Renamed.java", "/p/B.java"],
moves: [{ from: "/p/A.java", to: "/p/Renamed.java" }],
byAgent: false,
});
});
// Reopened editors take part in the refactoring's history like the ones they replace.
await moved("/p/Renamed.java", "/p/A.java", () => workspaceEditHistory(11));
await moved("/p/A.java", "/p/Renamed.java", () => workspaceEditHistory(11, true));
await moved("/p/Renamed.java", "/p/A.java", () => workspaceEditHistory(11));
expect(notify).not.toHaveBeenCalled();
} finally {
provideEditorService(undefined as unknown as EditorService);
_provideOpenEditorPaths(() => []);
}
});
+12 -22
Переглянути файл
@@ -3,8 +3,7 @@ import { invertedEffects, isolateHistory, redo, undo } from "@codemirror/command
import { EditorState, Prec, StateEffect, type Transaction, type Extension } from "@codemirror/state";
import { EditorView, keymap } from "@codemirror/view";
import { _emitWorkspaceEditHistory, _provideWorkspaceHistory, isExternalChange } from "@/editor/api";
import { editorsFollowAppliedMoves, reversedMoves, withEditorsFollowing } from "@/editor/fileMoves";
import { call, commands, onIdeEvent, type FileMove } from "@/platform/ipc";
import { call, commands, onIdeEvent } from "@/platform/ipc";
import { useProject } from "@/platform/project";
interface Marker {
@@ -21,7 +20,7 @@ export interface WorkspaceHistoryTarget {
export class WorkspaceHistory {
private targets = new Set<WorkspaceHistoryTarget>();
private records = new Map<number, { paths: string[]; moves: FileMove[]; undone: boolean }>();
private records = new Map<number, { paths: string[]; undone: boolean }>();
private project = useProject.getState().project;
private busy = false;
private moving = false;
@@ -32,7 +31,7 @@ export class WorkspaceHistory {
) {}
start(): () => void {
const stop = onIdeEvent("workspaceEditApplied", ({ id, paths, moves }) => {
const stop = onIdeEvent("workspaceEditApplied", ({ id, paths }) => {
if (this.project !== useProject.getState().project) {
this.records.clear();
this.project = useProject.getState().project;
@@ -44,11 +43,9 @@ export class WorkspaceHistory {
record.paths.some((path) => this.affects(paths, path) || paths.some((root) => root.startsWith(`${path}/`)))
)
this.records.delete(key);
this.records.set(id, { paths, moves, undone: false });
this.records.set(id, { paths, undone: false });
while (this.records.size > 20) this.records.delete(this.records.keys().next().value!);
for (const target of this.targets) if (this.affects(paths, target.path)) this.mark(target, id);
// Now, before the file watcher reports the old paths gone and their tabs close.
void editorsFollowAppliedMoves(moves);
});
const unprovide = _provideWorkspaceHistory((id, redo) => this.run(id, redo));
return () => {
@@ -157,21 +154,14 @@ export class WorkspaceHistory {
for (const target of targets)
if (!this.step(target, id, forward))
throw new Error("Undo newer editor changes before undoing this refactoring");
await withEditorsFollowing(
async () => {
await call(forward ? commands.redoWorkspaceEdit(id) : commands.undoWorkspaceEdit(id));
await this.synced();
for (const target of targets) {
if (!this.targets.has(target)) continue;
const tr = this.step(target, id, forward);
if (tr) target.dispatch(tr);
}
// Editors reopened at moved paths build their history from the record: settle it first.
record.undone = !forward;
},
() => (forward ? record.moves : reversedMoves(record.moves)),
{ save: false },
);
await call(forward ? commands.redoWorkspaceEdit(id) : commands.undoWorkspaceEdit(id));
await this.synced();
for (const target of targets) {
if (!this.targets.has(target)) continue;
const tr = this.step(target, id, forward);
if (tr) target.dispatch(tr);
}
record.undone = !forward;
_emitWorkspaceEditHistory({ id, undone: record.undone });
} catch (error) {
// A refused backend restore must leave the initiating editor's history intact.
-59
Переглянути файл
@@ -1,59 +0,0 @@
import { afterEach, expect, it } from "vitest";
import { onIdeEvent } from "@/platform/ipc";
import { provideEditorService, type EditorService } from "@/workbench/contributions";
import { createMemoryBackend } from "./core/backend";
import { EditorController, useTabs } from "./core/controller";
import { initialTabsState } from "./core/model/tabs";
import { editorsFollowAppliedMoves } from "./fileMoves";
let ctrl: EditorController | null = null;
afterEach(() => {
ctrl?.stop();
ctrl = null;
useTabs.setState(initialTabsState(), true);
});
function setup(files: Record<string, string>) {
const backend = createMemoryBackend(files);
backend.onFsChanged = (h) => onIdeEvent("fsChanged", h);
const controller = new EditorController(backend);
controller.start();
ctrl = controller;
provideEditorService({
openFile: (path, o) => controller.openFile(path, o),
activePath: () => controller.activePath(),
closePath: (path) => controller.closePath(path),
saveAll: async () => {},
} as Partial<EditorService> as EditorService);
return { controller, backend };
}
const tabPaths = () =>
Object.values(useTabs.getState().panes).flatMap((pane) => pane.tabs.map((tab) => tab.input.path));
it("a renamed active file stays the active editor", async () => {
const { controller, backend } = setup({ "/p/A.java": "class A {}", "/p/B.java": "class B {}" });
await controller.openFile("/p/B.java", { focus: false });
await controller.openFile("/p/A.java", { focus: false });
backend.files.set("/p/Renamed.java", backend.files.get("/p/A.java")!);
backend.files.delete("/p/A.java");
await editorsFollowAppliedMoves([{ from: "/p/A.java", to: "/p/Renamed.java" }]);
expect(tabPaths()).toEqual(["/p/B.java", "/p/Renamed.java"]);
expect(controller.activePath()).toBe("/p/Renamed.java");
});
it("a renamed background file leaves the active editor in place", async () => {
const { controller, backend } = setup({ "/p/A.java": "class A {}", "/p/B.java": "class B {}" });
await controller.openFile("/p/A.java", { focus: false });
await controller.openFile("/p/B.java", { focus: false });
backend.files.set("/p/Renamed.java", backend.files.get("/p/A.java")!);
backend.files.delete("/p/A.java");
await editorsFollowAppliedMoves([{ from: "/p/A.java", to: "/p/Renamed.java" }]);
expect(tabPaths().sort()).toEqual(["/p/B.java", "/p/Renamed.java"]);
expect(controller.activePath()).toBe("/p/B.java");
});
-81
Переглянути файл
@@ -1,81 +0,0 @@
/** IDEA keeps editors on files that a refactoring moves or renames: they reopen at the new paths. */
import type { FileMove } from "@/bindings";
import { openEditorPaths } from "@/editor/api";
import { notifyFilesMoved, trackFileMove } from "@/platform/fileOps";
import { emitLocalIdeEvent } from "@/platform/ipc";
import { isSameOrInside } from "@/platform/paths";
import { useProject } from "@/platform/project";
import { maybeEditorService } from "@/workbench/contributions";
export async function saveAllQuietly(editor: { saveAll(): Promise<void> }) {
try {
await editor.saveAll();
} catch {
/* unsaved files are reported by the editor */
}
}
/** `path` after `moves`. */
export function movedPath(path: string, moves: readonly FileMove[]): string {
let p = path;
for (const m of moves) if (isSameOrInside(p, m.from)) p = m.to + p.slice(m.from.length);
return p;
}
/** Moves in the opposite direction, last first: what Undo of `moves` does. */
export function reversedMoves(moves: readonly FileMove[]): FileMove[] {
return [...moves].reverse().map((m) => ({ from: m.to, to: m.from }));
}
/**
* Runs `run`, which moves the files `done` names, with the editors following: unsaved changes
* are saved first (unless `save` is false), tabs reopen at the new paths.
*/
export async function withEditorsFollowing<T>(
run: () => Promise<T>,
done: (r: T) => readonly FileMove[],
{ save = true }: { save?: boolean } = {},
): Promise<T> {
const projectRoot = () => useProject.getState().project?.root ?? null;
const root = projectRoot();
const editor = maybeEditorService();
const openBefore = editor ? openEditorPaths() : [];
if (editor && save) await saveAllQuietly(editor);
const active = editor?.activePath() ?? null;
const { result, applied } = await trackFileMove(root, async () => {
const result = await run();
const applied = done(result);
if (root === projectRoot()) await notifyFilesMoved(applied);
return { result, applied };
});
if (root !== projectRoot()) return result;
const open = openBefore.filter((p) => applied.some((m) => isSameOrInside(p, m.from)));
if (applied.length)
emitLocalIdeEvent({
type: "fsChanged",
created: applied.map((m) => m.to),
modified: [],
removed: applied.map((m) => m.from),
});
if (!editor || !open.length) return result;
// The editor closes tabs of removed files in a queue; an open that starts before an
// active tab's close counts as superseded and stays in the background.
for (const p of open) await editor.closePath?.(p).catch(() => false);
const ordered = active && open.includes(active) ? [...open.filter((p) => p !== active), active] : open;
for (const p of ordered) await editor.openFile(movedPath(p, applied), { focus: false }).catch(() => {});
if (active && !open.includes(active)) await editor.openFile(active, { focus: false }).catch(() => {});
return result;
}
/**
* Editors follow `moves` that a workspace edit already made (a server's rename, Move, a quick
* fix): called when the backend reports the edit, before the file watcher closes their tabs.
*/
export function editorsFollowAppliedMoves(moves: readonly FileMove[]): Promise<void> {
if (!moves.length) return Promise.resolve();
return withEditorsFollowing(
() => Promise.resolve(),
() => moves,
{ save: false },
);
}
-16
Переглянути файл
@@ -323,22 +323,6 @@ describe("applying completions", () => {
}
});
it("puts the caret inside the parentheses of a server-inserted call that takes arguments", async () => {
setInvokeRoute(() => Promise.resolve(null));
try {
const { view, req } = setup("x.rea|\n", "", [completionExtension()]);
view.dispatch({ effects: StateEffect.appendConfig.of(lspDoc.of({ doc: 1 } as EditorDocContext)) });
const command = { title: "Apply Completion", command: "jetbrains.kotlin.completion.apply", arguments: ["1"] };
const kotlin = item({ label: "read", kind: "method", labelDetail: "(name: String)", insertText: "", command });
applyLspCompletion(view, makeCompletion(kotlin, req), 5, 5, "insert");
view.dispatch({ changes: { from: 5, insert: "d()" }, annotations: remoteChange.of(true) });
expect(view.state.doc.toString()).toBe("x.read()\n");
expect(view.state.selection.main.head).toBe(7);
} finally {
setInvokeRoute(null);
}
});
it("completes at every caret whose typed prefix matches the main caret's", () => {
const { view, req } = setup("a.cr|\nb.cr\nc.xy", "", [EditorState.allowMultipleSelections.of(true)]);
// Carets after both `cr`s (the main one first) and after `xy`.
+3 -20
Переглянути файл
@@ -462,8 +462,6 @@ async function applyLateEdits(view: EditorView, c: LspCompletion, insertedAt: nu
interface ServerInsert {
at: number;
others: readonly number[];
/** The item is a call that takes arguments: the caret goes inside an inserted `()`. */
inside?: boolean;
}
const awaitServerInsert = StateEffect.define<ServerInsert | null>();
const serverInsertAt = StateField.define<ServerInsert | null>({
@@ -472,11 +470,7 @@ const serverInsertAt = StateField.define<ServerInsert | null>({
for (const e of tr.effects) if (e.is(awaitServerInsert)) return e.value;
// The edit landed, or the caret moved on before it did.
if (value === null || tr.annotation(remoteChange) || tr.selection) return null;
return {
at: tr.changes.mapPos(value.at, -1),
others: value.others.map((p) => tr.changes.mapPos(p, -1)),
inside: value.inside,
};
return { at: tr.changes.mapPos(value.at, -1), others: value.others.map((p) => tr.changes.mapPos(p, -1)) };
},
});
@@ -547,9 +541,7 @@ const caretAfterServerInsert = EditorState.transactionFilter.of((tr) => {
if (tr.changes.touchesRange(from, to)) continue;
others.push({ from: tr.changes.mapPos(from, 1), to: tr.changes.mapPos(to, -1) });
}
const inside =
pending.inside && /\(\)$/.test(landed.insert) && tr.newDoc.sliceString(mainAfter - 2, mainAfter) === "()";
const selection = EditorSelection.cursor(inside ? mainAfter - 1 : mainAfter);
const selection = EditorSelection.cursor(mainAfter);
if (!others.length) return [tr, { selection, sequential: true }];
// Not part of this transaction: a remote one is not sent back to the document model.
const changes = others
@@ -561,12 +553,6 @@ const caretAfterServerInsert = EditorState.transactionFilter.of((tr) => {
/** Client-side commands handled by the editor itself (VS Code ids servers commonly send). */
const CLIENT_COMMANDS = new Set(["editor.action.triggerParameterHints", "editor.action.triggerSuggest"]);
/** A function or method whose signature lists parameters (`(name: String)`), as far as the item tells. */
function takesArguments(item: Pick<CompletionItem, "kind" | "labelDetail" | "detail">): boolean {
if (item.kind && !CALLABLE.has(item.kind)) return false;
return /^\s*\(\s*[^)\s]/.test(item.labelDetail ?? item.detail ?? "");
}
/** kotlin-lsp inserts the item itself (`jetbrains.kotlin.completion.apply`): nothing goes in here. */
function serverInserts(item: CompletionItem): boolean {
const cmd = item.command?.command;
@@ -578,10 +564,7 @@ function runCommand(view: EditorView, item: CompletionItem, others: readonly num
if (!command?.command) return;
const cmd = command.command;
const serverInserted = serverInserts(item);
if (serverInserted)
view.dispatch({
effects: awaitServerInsert.of({ at: view.state.selection.main.head, others, inside: takesArguments(item) }),
});
if (serverInserted) view.dispatch({ effects: awaitServerInsert.of({ at: view.state.selection.main.head, others }) });
if (cmd === "editor.action.triggerParameterHints") setTimeout(() => triggerSignatureHelp(view), 0);
else if (cmd === "editor.action.triggerSuggest") setTimeout(() => startCompletion(view), 0);
else if (!CLIENT_COMMANDS.has(cmd) && !cmd.startsWith("editor.")) {
-90
Переглянути файл
@@ -205,96 +205,6 @@ describe("locationItems", () => {
expect((await locationItems([target("/p/src/a.py", "refresh", 3)]))[0]!.label).toBe("refresh");
});
describe("takes the container only from a type whose body holds the target", () => {
const cart = [
'import { type Cents } from "./money.ts";',
"",
"export interface Product {",
" id: string;",
" price: Cents;",
"}",
"",
"export interface CartLine {",
" product: Product;",
" quantity: number;",
"}",
"",
'export type Discount = { kind: "percent"; percent: number } | { kind: "fixed"; amount: Cents };',
"",
"export class Cart {",
" private discount: Discount | null = null;",
"",
" total(): Cents {",
" return 0;",
" }",
"}",
];
const at = (line: number, col: number) => ({
path: "/p/src/cart.ts",
uri: null,
range: { start: { line, col }, end: { line, col: col + 1 } },
});
beforeEach(() => {
readManyFileLines.mockResolvedValue(new Map([["/p/src/cart.ts", cart]]));
project("/p");
});
it("anonymous targets after a closed interface", async () => {
const union = cart[12]!;
const items = await locationItems([at(12, union.indexOf("{")), at(12, union.lastIndexOf("{ kind"))]);
expect(items.map((i) => [i.label, i.detail])).toEqual([
["cart.ts", "src/cart.ts:13"],
["cart.ts", "src/cart.ts:13"],
]);
});
it("a named target after a closed interface", async () => {
const item = (await locationItems([at(7, cart[7]!.indexOf("CartLine"))]))[0]!;
expect([item.label, item.detail]).toEqual(["CartLine", "src/cart.ts:8"]);
});
it("a member after a closed type, inside its own class", async () => {
const item = (await locationItems([at(17, cart[17]!.indexOf("total"))]))[0]!;
expect([item.label, item.detail]).toEqual(["total", "Cart · src/cart.ts:18"]);
});
it("indentation-delimited bodies: a function after a class, a method after a dict literal", async () => {
const lines = [
"class Config:",
" defaults = {}",
"",
" def load(self) -> None:",
" pass",
"",
"def main() -> None:",
" pass",
];
readManyFileLines.mockResolvedValue(new Map([["/p/src/mod.py", lines]]));
const items = await locationItems([target("/p/src/mod.py", "load", 3), target("/p/src/mod.py", "main", 6)]);
expect(items.map((i) => i.detail)).toEqual(["Config · src/mod.py:4", "src/mod.py:7"]);
const main = {
...target("/p/src/mod.py", "main", 6),
range: { start: { line: 6, col: 0 }, end: { line: 6, col: 3 } },
};
expect((await locationItems([main]))[0]!.detail).toBe("src/mod.py:7");
});
it("Go: a method's container is its receiver, declared outside the struct's body", async () => {
const lines = [
"type Square struct {",
"\tside float64",
"}",
"",
"func (s *Square) Area() float64 {",
"\treturn 0",
"}",
];
readManyFileLines.mockResolvedValue(new Map([["/p/shapes.go", lines]]));
const at = { path: "/p/shapes.go", uri: null, range: { start: { line: 4, col: 17 }, end: { line: 4, col: 21 } } };
expect((await locationItems([at]))[0]!.detail).toBe("Square · shapes.go:5");
});
});
it("does not query the index for index symbols, which carry their container", async () => {
readManyFileLines.mockResolvedValue(new Map());
project("/p");
+13 -61
Переглянути файл
@@ -172,89 +172,41 @@ const GO_RECEIVER = /^\s*func\s*\(\s*(?:[\p{L}_][\p{L}\p{N}_]*\s+)?\*?\s*([\p{L}
const FENCES = [`"""`, `'''`];
/** Code of a line without comments, strings and docstring text; null for a line with no code. */
type CodeLine = string | null;
/**
* Name of the type a target sits in (the nearest type declaration above it whose body is still
* open at the target); null without one.
* Name of the type a target sits in (the nearest type declaration above it); null without one.
* Text heuristic: docstrings (`"""` / `'''` fences) and line comments (`#`, `//`, `*`…) cannot
* declare a type, so "the base class does all that is needed" in a comment is not one.
*/
export function enclosingType(lines: readonly string[] | null | undefined, target: Location): string | null {
if (!lines) return null;
const targetLine = lines[target.range.start.line] ?? "";
const receiver = GO_RECEIVER.exec(targetLine)?.[1];
if (receiver) return receiver;
const from = Math.max(0, target.range.start.line - 2000);
const code: CodeLine[] = [];
const declarations: { line: number; end: number; name: string }[] = [];
let container: string | null = null;
let fence: string | null = null;
for (let l = from; l < target.range.start.line; l++) {
for (let l = Math.max(0, target.range.start.line - 2000); l < target.range.start.line; l++) {
const line = lines[l] ?? "";
code.push(null);
if (fence) {
if ((line.split(fence).length - 1) % 2 === 1) fence = null;
continue;
}
// Comments first: a `#`/`//` line cannot open a docstring fence either.
const text = line.replace(/(^|\s)(#|\/\/).*$/, "$1");
if (!text.trim()) continue;
const opened = FENCES.find((f) => (text.split(f).length - 1) % 2 === 1);
const code = line.replace(/(^|\s)(#|\/\/).*$/, "$1");
if (!code.trim()) continue;
const opened = FENCES.find((f) => (code.split(f).length - 1) % 2 === 1);
if (opened) {
fence = opened;
continue;
}
// A single-line docstring (fences open and close on the line) is text too.
if (FENCES.some((f) => text.includes(f)) || /^\s*(\*|\/\*)/.test(line)) continue;
code[l - from] = text;
const m = TYPE_DECLARATION.exec(text);
if (m) declarations.push({ line: l - from, end: m.index + m[0].length, name: (m[1] ?? m[2])! });
if (FENCES.some((f) => code.includes(f))) continue;
const m = TYPE_DECLARATION.exec(code);
if (m && !/^\s*(\*|\/\*)/.test(line)) container = (m[1] ?? m[2])!;
}
code.push(targetLine);
const col = target.range.start.col;
for (const d of declarations.reverse()) if (bodyHolds(code, d.line, d.end, col)) return d.name;
return null;
return container;
}
const STRING_LITERAL = /"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`/g;
/**
* Whether the body of the declaration on `code[line]` (ending at `end`) is still open at `col`
* of the last entry of `code` (the target's line): braces when the body opens with one on the
* declaration's line or the next (Allman style), else indentation (Python, Ruby, a declaration
* without a body).
*/
function bodyHolds(code: readonly CodeLine[], line: number, end: number, col: number): boolean {
const last = code.length - 1;
const next = code.findIndex((c, i) => i > line && i < last && c !== null);
const braced = code[line]!.slice(end).includes("{") || (next > 0 && /^\s*\{/.test(code[next]!));
if (braced) {
let depth = 0;
let opened = false;
for (let i = line; i <= last; i++) {
const text = (i === line ? code[i]!.slice(end) : i === last ? code[i]!.slice(0, col) : code[i]) ?? "";
for (const c of text.replace(STRING_LITERAL, "")) {
if (c === "{") {
depth++;
opened = true;
} else if (c === "}" && --depth === 0 && opened) return false;
}
}
return depth > 0;
}
const indent = (s: string) => s.length - s.trimStart().length;
const own = indent(code[line]!);
for (let i = line + 1; i < code.length; i++) {
const text = code[i];
// A wrapped header (`) : Base {`) continues the declaration.
if (text?.trim() && indent(text) <= own && !/^\s*[)\]]/.test(text)) return false;
}
return true;
}
/** Name of the type a target sits in: the type declaration around it, else the file name. */
/** Name of the type a target sits in: the nearest type declaration above it, else the file name. */
export function enclosingTypeName(lines: readonly string[] | null | undefined, target: Location): string {
const receiver = GO_RECEIVER.exec(lines?.[target.range.start.line] ?? "")?.[1];
if (receiver) return receiver;
const found = enclosingType(lines, target);
if (found) return found;
const file = target.path.split(/[\\/]/).pop() ?? target.path;
+11 -44
Переглянути файл
@@ -130,8 +130,6 @@ export interface ComposerProps {
onSubmit: (now: boolean) => void;
/** Opens the per-session MCP servers picker when `/mcp` is run. */
onOpenMcp?: () => void;
/** Opens the per-session skills picker when `/skills` is run. */
onOpenSkills?: () => void;
disabled?: boolean;
autoFocus?: boolean;
/** A request from this host to focus its input without changing the selection. */
@@ -516,26 +514,17 @@ export function Composer(props: ComposerProps) {
...rest,
];
}
const openPickerCommands: AgentCommand[] = [];
if (props.onOpenMcp && !props.commands.some((c) => c.name === "mcp")) {
openPickerCommands.push({
name: "mcp",
description: tx("Configure MCP servers for this session"),
hint: null,
source: "command" as const,
});
}
if (props.onOpenSkills && !props.commands.some((c) => c.name === "skills")) {
openPickerCommands.push({
name: "skills",
description: tx("Configure skills for this session"),
hint: null,
source: "command" as const,
});
}
const availableCommands =
completion.query.length > 0 && openPickerCommands.length > 0
? [...openPickerCommands, ...props.commands]
props.onOpenMcp && completion.query.length > 0 && !props.commands.some((c) => c.name === "mcp")
? [
{
name: "mcp",
description: tx("Configure MCP servers for this session"),
hint: null,
source: "command" as const,
},
...props.commands,
]
: props.commands;
const out: Item[] = [];
let source: "command" | "skill" | undefined;
@@ -548,18 +537,7 @@ export function Composer(props: ComposerProps) {
out.push({ kind: "command", command });
}
return out;
}, [
completion,
files,
shellFound,
shellQuery,
recentCommands,
props.history,
props.commands,
props.onOpenMcp,
props.onOpenSkills,
tx,
]);
}, [completion, files, shellFound, shellQuery, recentCommands, props.history, props.commands, props.onOpenMcp, tx]);
const activeIndex = items[active] && !isSection(items[active]!) ? active : firstSelectable(items, isSection);
const open = !!completion && items.some((item) => !isSection(item));
const anchorAt = open ? completion.to : null;
@@ -651,11 +629,6 @@ export function Composer(props: ComposerProps) {
setCompletion(null);
props.onOpenMcp();
return;
} else if (item.command.name === "skills" && props.onOpenSkills) {
replace(completion.from, completion.to, "");
setCompletion(null);
props.onOpenSkills();
return;
} else {
const next = applyCompletion(current, completion, `/${item.command.name}`);
setText(next.text, next.caret);
@@ -1007,12 +980,6 @@ export function Composer(props: ComposerProps) {
props.onOpenMcp();
return handled();
}
if (props.onOpenSkills && view.state.doc.toString().trim() === "/skills") {
setText("");
setCompletion(null);
props.onOpenSkills();
return handled();
}
if (!props.disabled) props.onSubmit(send === "now");
recalled.current = { index: -1, stash: "" };
return handled();
+1 -22
Переглянути файл
@@ -15,7 +15,6 @@ import { canSend, emptyDraft } from "./composerModel";
import { ConfigPickers } from "./ConfigPickers";
import { HermesProfilePicker } from "./HermesProfilePicker";
import { McpPicker } from "./McpPicker";
import { SkillsPicker } from "./SkillsPicker";
import { useEffortFocus } from "./effortFocus";
import { useAgentFontZoomSurface } from "./fontZoom";
import { HOME_KEY, providerIcon } from "./model";
@@ -28,7 +27,6 @@ import {
refreshProviders,
refreshModels,
setDraftMcpOverrides,
setDraftSkillOverrides,
setDraftOption,
startTask,
updateDraft,
@@ -68,7 +66,6 @@ export function HomeEditor({ docked = false, input }: { docked?: boolean; input?
const [error, setError] = useState<string | null>(null);
const [starting, setStarting] = useState(false);
const [mcpOpenRequest, setMcpOpenRequest] = useState(0);
const [skillsOpenRequest, setSkillsOpenRequest] = useState(0);
// Kept mounted while another tab shows: what changed meanwhile is read again when it shows.
const shown = useEditorShown();
@@ -166,7 +163,6 @@ export function HomeEditor({ docked = false, input }: { docked?: boolean; input?
(!project?.workspace || repoState?.root === root);
const openMcp = () => setMcpOpenRequest((n) => n + 1);
const openSkills = () => setSkillsOpenRequest((n) => n + 1);
// The agent shows as its icon; its name and version are in the tooltip.
const agentTitle = [provider?.name ?? tx("Agent"), probe?.version].filter(Boolean).join(" ");
@@ -212,16 +208,8 @@ export function HomeEditor({ docked = false, input }: { docked?: boolean; input?
onConfig={setDraftOption}
onSubmit={start}
onOpenMcp={openMcp}
onOpenSkills={openSkills}
disabled={!canStart}
addMenu={
provider
? [
{ id: "mcp", label: "MCP Servers…", icon: "plugin", run: openMcp },
{ id: "skills", label: "Skills…", icon: "bulb", run: openSkills },
]
: undefined
}
addMenu={provider ? [{ id: "mcp", label: "MCP Servers…", icon: "plugin", run: openMcp }] : undefined}
toolbar={
<>
<span className={styles.agentPicker} {...tooltipAttrs(agentTitle, undefined, true)}>
@@ -282,15 +270,6 @@ export function HomeEditor({ docked = false, input }: { docked?: boolean; input?
hideTrigger
/>
)}
{provider && (
<SkillsPicker
provider={provider.id}
overrides={draft.skillOverrides}
onChange={setDraftSkillOverrides}
openRequest={skillsOpenRequest}
hideTrigger
/>
)}
</>
}
actions={
-53
Переглянути файл
@@ -357,56 +357,3 @@ describe("SessionAssets component", () => {
expect(await screen.findByRole("button", { name: "1 Artifact" })).toBeInTheDocument();
});
});
describe("SessionAssets binary file artifacts", () => {
const entries: AgentEntry[] = [
{
type: "tool",
id: "t-doc",
title: "Write spec",
kind: "edit",
status: "completed",
locations: ["/repo/spec.docx"],
output: null,
diffs: [{ path: "/repo/spec.docx", added: 1, removed: 0 }],
},
];
beforeEach(() => {
vi.clearAllMocks();
resetSessionAssetsCacheForTests();
clearDismissedAssets("task-1");
useAgents.setState({ composers: new Map([["task-1", emptyDraft()]]) });
vi.spyOn(ipc, "isTauri").mockReturnValue(true);
vi.spyOn(ipc, "call").mockImplementation(async (promise) => promise);
vi.spyOn(ipc.commands, "vcsRemotes").mockResolvedValue([] as never);
});
afterEach(() => {
vi.restoreAllMocks();
});
async function openArtifact() {
render(<SessionAssets task={makeTask()} entries={entries} head="feat/session" />);
fireEvent.click(await screen.findByRole("button", { name: "1 Artifact" }));
const dialog = await screen.findByRole("dialog", { name: "Artifacts" });
fireEvent.click(within(dialog).getByText("spec.docx"));
}
it("opens a binary file with its application through the backend's checked command", async () => {
const open = vi.spyOn(ipc.commands, "fsOpenWithSystem").mockResolvedValue(null as never);
await openArtifact();
await waitFor(() => expect(open).toHaveBeenCalledWith("/repo/spec.docx"));
expect(openFileMock).not.toHaveBeenCalled();
});
it("falls back to the editor when the backend refuses the launch", async () => {
vi.spyOn(console, "warn").mockImplementation(() => {});
const open = vi
.spyOn(ipc.commands, "fsOpenWithSystem")
.mockRejectedValue({ kind: "unavailable", message: "Project is in Restricted Mode." } as never);
await openArtifact();
await waitFor(() => expect(openFileMock).toHaveBeenCalledWith("/repo/spec.docx", { focus: true }));
expect(open).toHaveBeenCalledWith("/repo/spec.docx");
});
});
+9 -2
Переглянути файл
@@ -5,7 +5,6 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { AgentEntry, AgentTask, PullRequestSummary } from "@/bindings";
import { call, commands, isTauri, onIdeEvent } from "@/platform/ipc";
import { openWithSystemApp } from "@/platform/fileManager";
import { useTx } from "@/platform/i18n";
import { openExternalUrl } from "@/platform/openUrl";
import { useProject } from "@/platform/project";
@@ -149,7 +148,15 @@ function issueIcon(state: IssueAssetState | undefined): IconName {
}
async function openFileArtifact(artifact: Extract<SessionArtifact, { kind: "file" }>) {
if (artifact.externalBinary && (await openWithSystemApp(artifact.path))) return;
if (artifact.externalBinary && isTauri()) {
try {
const { openPath } = await import("@tauri-apps/plugin-opener");
await openPath(artifact.path);
return;
} catch {
/* fall back to editor */
}
}
await editorService().openFile(artifact.path, { focus: true });
}
-334
Переглянути файл
@@ -1,334 +0,0 @@
.page {
display: flex;
flex-direction: column;
gap: var(--space-2);
font-size: var(--fs-ui);
color: var(--fg-strong);
}
.header {
display: flex;
align-items: center;
justify-content: space-between;
flex-wrap: wrap;
gap: var(--space-2);
}
.headerActions {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: var(--space-1-5);
}
.title {
margin: 0;
font-size: 16px;
font-weight: 600;
color: var(--fg-strong);
}
.lead {
margin: 0;
color: var(--fg-muted);
line-height: 1.45;
}
.link {
padding: 0;
border: none;
background: none;
color: var(--link);
font: inherit;
cursor: pointer;
}
.link:hover {
text-decoration: underline;
}
.topControls {
display: flex;
flex-direction: column;
gap: var(--space-2);
}
.tabBar {
border-bottom: 1px solid var(--border);
}
.search {
width: 100%;
}
.error {
display: flex;
align-items: flex-start;
gap: var(--space-1-5);
padding: 6px 8px;
border-radius: var(--radius-control);
background: color-mix(in srgb, var(--danger) 12%, transparent);
color: var(--danger);
font-size: var(--fs-small);
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.sections {
display: flex;
flex-direction: column;
gap: var(--space-3);
}
.section {
display: flex;
flex-direction: column;
gap: var(--space-1-5);
}
.sectionBar {
display: flex;
align-items: center;
justify-content: space-between;
min-height: 28px;
padding: 2px 2px;
gap: var(--space-2);
}
.sectionToggle {
display: flex;
align-items: center;
gap: var(--space-1-5);
flex: 1;
min-width: 0;
padding: 4px 2px;
border: none;
background: none;
color: var(--fg-strong);
font: inherit;
font-weight: 600;
text-align: left;
cursor: pointer;
}
.chevron {
color: var(--fg-muted);
flex-shrink: 0;
}
.sectionTitle {
font-size: var(--fs-ui);
font-weight: 600;
}
.sectionHint {
color: var(--fg-muted);
font-size: var(--fs-small);
font-weight: 400;
}
.badge {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 18px;
height: 18px;
padding: 0 6px;
border-radius: 999px;
background: var(--bg-hover);
color: var(--fg-muted);
font-size: 11px;
font-weight: 600;
line-height: 1;
}
.sectionBody {
display: flex;
flex-direction: column;
gap: var(--space-1-5);
}
.emptyBox {
padding: 12px 14px;
border-radius: var(--radius-control);
background: var(--bg-elev);
box-shadow: inset 0 0 0 1px var(--border);
color: var(--fg-muted);
font-size: var(--fs-small);
}
/* Expandable skill card, mirroring the MCP server card. */
.card {
display: flex;
flex-direction: column;
border-radius: var(--radius-control);
background: var(--bg-elev);
box-shadow: inset 0 0 0 1px var(--border);
overflow: hidden;
}
.cardHeader {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-2);
padding: 8px 10px;
}
.cardHeader:hover {
background: var(--bg-hover);
}
.cardExpandBtn {
display: flex;
align-items: center;
gap: var(--space-2);
flex: 1;
min-width: 0;
padding: 0;
border: 0;
background: none;
color: inherit;
font: inherit;
text-align: left;
cursor: pointer;
}
.cardMain {
display: flex;
flex-direction: column;
gap: var(--space-0-5);
min-width: 0;
flex: 1;
}
.cardTitleRow {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: var(--space-1-5);
min-width: 0;
}
.skillName {
font-weight: 600;
color: var(--fg-strong);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.tag {
display: inline-flex;
align-items: center;
gap: var(--space-1);
height: 18px;
padding: 0 6px;
border-radius: var(--radius-small, 3px);
background: var(--bg-floating-toolbar);
color: var(--fg-secondary);
font-size: var(--fs-tiny);
font-weight: 500;
white-space: nowrap;
}
.tagAccent {
background: color-mix(in srgb, var(--accent) 18%, var(--bg-elev));
color: var(--link);
}
.tagWarning {
background: color-mix(in srgb, var(--warning) 18%, var(--bg-elev));
color: var(--warning);
}
.subtitle {
color: var(--fg-muted);
font-size: var(--fs-small);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.rowActions {
display: flex;
align-items: center;
gap: var(--space-2);
flex-shrink: 0;
}
.modeControls {
display: flex;
align-items: center;
gap: var(--space-1-5);
}
.modeSelect {
min-width: 96px;
}
.scopeSelect {
min-width: 104px;
}
.statusDot {
width: 8px;
height: 8px;
border-radius: 50%;
flex-shrink: 0;
background: var(--control-off);
}
.statusOn {
background: var(--success);
}
.cardDrawer {
display: flex;
flex-direction: column;
gap: var(--space-2);
padding: 8px 12px 10px 28px;
border-top: 1px solid var(--border);
background: var(--bg-app);
font-size: var(--fs-small);
}
.metaGrid {
display: grid;
grid-template-columns: max-content minmax(0, 1fr);
gap: var(--space-1) var(--space-3);
align-items: baseline;
}
.metaLabel {
color: var(--fg-muted);
white-space: nowrap;
}
.metaValue {
color: var(--fg);
font-family: var(--font-mono);
overflow-wrap: anywhere;
}
.drawerFooter {
display: flex;
align-items: center;
justify-content: space-between;
flex-wrap: wrap;
gap: var(--space-2);
padding-top: 4px;
}
.drawerButtons {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: var(--space-1-5);
}
.hint {
color: var(--fg-muted);
font-size: var(--fs-small);
line-height: 1.4;
}
-139
Переглянути файл
@@ -1,139 +0,0 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import type { AgentSkillMode, AgentSkillSource, AgentSkillState, McpScope, ProjectInfo } from "@/bindings";
import { useProject } from "@/platform/project";
import { SkillsPage, type SkillsBackend } from "./SkillsPage";
const state = (
name: string,
source: AgentSkillSource,
mode: AgentSkillMode = "auto",
partial: Partial<AgentSkillState["skill"]> = {},
): AgentSkillState => ({
skill: {
name,
description: `${name} helps with ${name} things`,
path: `/skills/${name}`,
source,
valid: true,
warnings: [],
...partial,
},
mode,
origin: mode === "off" ? "user" : mode === "slashOnly" ? "workspace" : "none",
});
const SKILLS: AgentSkillState[] = [
state("tdd", "workspace"),
state("impeccable", "user", "off"),
state("ux-flow", "claudeWorkspace", "slashOnly"),
state("playwright", "copilotUser"),
];
function backend(): SkillsBackend & { setModeCalls: Array<{ name: string; scope: McpScope; mode: AgentSkillMode }> } {
const setModeCalls: Array<{ name: string; scope: McpScope; mode: AgentSkillMode }> = [];
return {
setModeCalls,
list: vi.fn(async () => SKILLS),
setMode: vi.fn(async (name: string, scope: McpScope, mode: AgentSkillMode) => {
setModeCalls.push({ name, scope, mode });
return SKILLS.map((s) => (s.skill.name === name ? { ...s, mode } : s));
}),
};
}
/** Opens one row's select and picks an option by text. */
function pick(triggerLabel: string, option: string) {
fireEvent.click(screen.getByRole("button", { name: triggerLabel }));
fireEvent.click(within(screen.getByRole("listbox")).getByText(option));
}
afterEach(() => useProject.setState({ project: null }));
describe("SkillsPage", () => {
it("groups skills by source with their mode and validation tags", async () => {
render(<SkillsPage backend={backend()} />);
await waitFor(() => expect(screen.getByText("tdd")).toBeInTheDocument());
const workspace = screen.getByRole("region", { name: "Workspace" });
expect(within(workspace).getByText("tdd")).toBeInTheDocument();
expect(screen.getByRole("region", { name: "User" })).toBeInTheDocument();
expect(screen.getByRole("region", { name: "Claude Code" })).toBeInTheDocument();
expect(screen.getByRole("region", { name: "GitHub Copilot" })).toBeInTheDocument();
expect(screen.getAllByText("Slash only").length).toBeGreaterThan(0);
expect(screen.getByRole("button", { name: "Mode for impeccable" })).toHaveTextContent("Off");
expect(screen.queryByText("Valid")).not.toBeInTheDocument();
});
it("filters skills by search", async () => {
render(<SkillsPage backend={backend()} />);
await waitFor(() => expect(screen.getByText("tdd")).toBeInTheDocument());
fireEvent.change(screen.getByPlaceholderText("Type to search..."), { target: { value: "playwright" } });
expect(screen.getByText("playwright")).toBeInTheDocument();
expect(screen.queryByText("tdd")).not.toBeInTheDocument();
expect(screen.getByRole("region", { name: "GitHub Copilot" })).toBeInTheDocument();
expect(screen.queryByRole("region", { name: "Workspace" })).not.toBeInTheDocument();
});
it("limits the list to the chosen source tab", async () => {
render(<SkillsPage backend={backend()} />);
await waitFor(() => expect(screen.getByText("tdd")).toBeInTheDocument());
fireEvent.click(screen.getByRole("tab", { name: /Agent Folders/ }));
expect(screen.getByText("playwright")).toBeInTheDocument();
expect(screen.queryByText("tdd")).not.toBeInTheDocument();
expect(screen.queryByText("impeccable")).not.toBeInTheDocument();
});
it("sets a skill's mode in Global from its row", async () => {
const backendSpy = backend();
render(<SkillsPage backend={backendSpy} />);
await waitFor(() => expect(screen.getByText("tdd")).toBeInTheDocument());
pick("Mode for tdd", "Off");
await waitFor(() => expect(backendSpy.setModeCalls).toEqual([{ name: "tdd", scope: "user", mode: "off" }]));
await waitFor(() => expect(screen.getByRole("button", { name: "Mode for tdd" })).toHaveTextContent("Off"));
});
it("sets a skill's mode in the workspace scope", async () => {
const project = { root: "/proj", name: "Proj", trusted: true, isGit: true } as ProjectInfo;
useProject.setState({ project });
const backendSpy = backend();
render(<SkillsPage backend={backendSpy} />);
await waitFor(() => expect(screen.getByText("tdd")).toBeInTheDocument());
pick("Scope for tdd", "Workspace");
pick("Mode for tdd", "Slash only");
await waitFor(() =>
expect(backendSpy.setModeCalls).toEqual([{ name: "tdd", scope: "workspace", mode: "slashOnly" }]),
);
});
it("expands a row to its canonical path, validation result, and open action", async () => {
render(<SkillsPage backend={backend()} />);
await waitFor(() => expect(screen.getByText("tdd")).toBeInTheDocument());
fireEvent.click(screen.getByRole("button", { name: /^tdd/ }));
expect(await screen.findByText("/skills/tdd")).toBeInTheDocument();
expect(screen.getByText("SKILL.md is valid")).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Open SKILL.md" })).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Copy the path of tdd" })).toBeInTheDocument();
});
it("surfaces validation warnings of an invalid SKILL.md", async () => {
const invalid = [
state("broken", "workspace", "auto", {
valid: false,
warnings: ["the frontmatter name does not match the folder"],
}),
];
render(<SkillsPage backend={{ list: vi.fn(async () => invalid), setMode: vi.fn(async () => invalid) }} />);
await waitFor(() => expect(screen.getByText("broken")).toBeInTheDocument());
expect(screen.getByText("Invalid SKILL.md")).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: /^broken/ }));
expect(await screen.findByText(/does not match the folder/)).toBeInTheDocument();
expect(screen.queryByText("SKILL.md is valid")).not.toBeInTheDocument();
});
});
-420
Переглянути файл
@@ -1,420 +0,0 @@
/**
* Settings › Agents › Skills: every skill the CLI folders expose in one list, grouped by the
* source it was discovered in (workspace, user, and each CLI's own folders, symlinked copies
* collapsed by the backend), with the auto / slash-only / off modes settable globally or per
* workspace, and an expandable inspector showing the canonical path and SKILL.md validation.
*/
import clsx from "clsx";
import { useCallback, useEffect, useMemo, useState } from "react";
import type { AgentSkillMode, AgentSkillState, McpScope } from "@/bindings";
import { revealInFileManager, revealInFileManagerLabel } from "@/platform/fileManager";
import { formatMessage, useTx } from "@/platform/i18n";
import { useProject } from "@/platform/project";
import { Button, Icon, IconButton, SearchField, Select, Tabs, T } from "@/ui";
import { editorService } from "@/workbench/contributions";
import { providerIcon } from "./model";
import {
SKILL_SOURCE_GROUPS,
defaultSkillsBackend,
isDiscoveredSource,
useSkillsCatalog,
type SkillsBackend,
} from "./skillsModel";
import styles from "./SkillsPage.module.css";
export { defaultSkillsBackend, type SkillsBackend };
type SourceTab = "all" | "workspace" | "user" | "cli";
/** A key of the source-group table (and so, a skill source). */
type SkillSource = keyof typeof SKILL_SOURCE_GROUPS;
const MODE_OPTIONS: ReadonlyArray<{ value: AgentSkillMode; label: string }> = [
{ value: "auto", label: "Auto" },
{ value: "slashOnly", label: "Slash only" },
{ value: "off", label: "Off" },
];
/** Groups a tab shows, in source precedence order. */
function groupsForTab(tab: SourceTab): readonly SkillSource[] {
const order = Object.keys(SKILL_SOURCE_GROUPS) as SkillSource[];
if (tab === "all") return order;
if (tab === "workspace") return order.filter((s) => s === "workspace" || s.endsWith("Workspace"));
if (tab === "user") return order.filter((s) => s === "user" || s.endsWith("User"));
return order.filter(isDiscoveredSource);
}
export function SkillsPage({ backend = defaultSkillsBackend }: { backend?: SkillsBackend }) {
const tx = useTx();
const hasProject = useProject((s) => !!s.project?.root);
const [tab, setTab] = useState<SourceTab>("all");
const [skills, setSkills] = useState<AgentSkillState[]>([]);
const [query, setQuery] = useState("");
const [error, setError] = useState<string | null>(null);
const [busyName, setBusyName] = useState<string | null>(null);
const [expanded, setExpanded] = useState<Record<string, boolean>>({});
const [collapsed, setCollapsed] = useState<Record<string, boolean>>({});
// The scope the row's mode selector writes to; defaults follow where the mode came from.
const [scopes, setScopes] = useState<Record<string, McpScope>>({});
const syncCatalog = useCallback(
(next: AgentSkillState[]) => {
setSkills(next);
if (backend === defaultSkillsBackend) {
useSkillsCatalog.setState({ skills: next, loaded: true });
}
},
[backend],
);
const load = useCallback(() => {
backend
.list()
.then((list) => {
syncCatalog(list);
setError(null);
})
.catch((e: unknown) => setError(e instanceof Error ? e.message : String(e)));
}, [backend, syncCatalog]);
useEffect(() => {
load();
}, [load]);
const filtered = useMemo(() => {
const q = query.trim().toLowerCase();
if (!q) return skills;
return skills.filter(
(s) =>
s.skill.name.toLowerCase().includes(q) ||
s.skill.description.toLowerCase().includes(q) ||
s.skill.path.toLowerCase().includes(q),
);
}, [skills, query]);
const grouped = useMemo(() => {
const order = groupsForTab(tab);
const map = new Map<SkillSource, AgentSkillState[]>();
for (const source of order) {
const items = filtered.filter((s) => s.skill.source === source);
if (items.length > 0) map.set(source, items);
}
return [...map.entries()];
}, [filtered, tab]);
const tabCount = (tab: SourceTab): number => {
if (tab === "all") return skills.length;
const sources = groupsForTab(tab);
return skills.filter((s) => (sources as readonly SkillSource[]).includes(s.skill.source)).length;
};
const setMode = async (state: AgentSkillState, scope: McpScope, mode: AgentSkillMode) => {
setBusyName(state.skill.name);
setError(null);
try {
const next = await backend.setMode(state.skill.name, scope, mode);
syncCatalog(next);
} catch (e: unknown) {
setError(e instanceof Error ? e.message : String(e));
load();
} finally {
setBusyName(null);
}
};
const scopeOf = (state: AgentSkillState): McpScope =>
scopes[state.skill.name] ?? (state.origin === "workspace" || state.origin === "trust" ? "workspace" : "user");
return (
<div className={styles.page}>
<div className={styles.header}>
<h2 className={styles.title}>
<T>Skills</T>
</h2>
<div className={styles.headerActions}>
<Button variant="secondary" onClick={load}>
<Icon name="refresh" size={14} /> <T>Rescan</T>
</Button>
</div>
</div>
<p className={styles.lead}>
<T>
Skills are SKILL.md folders the coding agents load: the workspace's and your user folders first, then what
each CLI discovers on its own. A mode set here never edits the skill's files, and a repo can quiet a global
skill without rules in AGENTS.md.
</T>
</p>
<div className={styles.topControls}>
<div className={styles.tabBar}>
<Tabs
variant="compact"
aria-label={tx("Skill sources")}
activeId={tab}
onSelect={(id) => setTab(id as SourceTab)}
items={[
{
id: "all",
label: tx("All Sources"),
text: tx("All Sources"),
trailing: <span className={styles.badge}>{skills.length}</span>,
},
{
id: "workspace",
label: tx("Workspace"),
text: tx("Workspace"),
trailing: <span className={styles.badge}>{tabCount("workspace")}</span>,
},
{
id: "user",
label: tx("User"),
text: tx("User"),
trailing: <span className={styles.badge}>{tabCount("user")}</span>,
},
{
id: "cli",
label: tx("Agent Folders"),
text: tx("Agent Folders"),
trailing: <span className={styles.badge}>{tabCount("cli")}</span>,
},
]}
/>
</div>
<SearchField
className={styles.search}
value={query}
onChange={setQuery}
placeholder={tx("Type to search...")}
aria-label={tx("Search skills")}
/>
</div>
{error && (
<div className={styles.error} role="alert">
<Icon name="error" size={14} />
<span>{error}</span>
</div>
)}
<div className={styles.sections}>
{grouped.map(([source, items]) => {
const group = SKILL_SOURCE_GROUPS[source];
const isCollapsed = collapsed[source];
return (
<section key={source} className={styles.section} aria-label={tx(group.label)}>
<div className={styles.sectionBar}>
<button
type="button"
className={styles.sectionToggle}
aria-expanded={!isCollapsed}
onClick={() => setCollapsed((prev) => ({ ...prev, [source]: !prev[source] }))}
>
<Icon name={isCollapsed ? "chevron-right" : "chevron-down"} size={14} className={styles.chevron} />
<span className={styles.sectionTitle}>{tx(group.label)}</span>
<span className={styles.badge}>{items.length}</span>
<span className={styles.sectionHint}>{group.paths}</span>
</button>
</div>
{!isCollapsed && (
<div className={styles.sectionBody} role="list">
{items.map((state) => (
<SkillCard
key={`${state.skill.source}:${state.skill.name}`}
state={state}
scope={scopeOf(state)}
hasProject={hasProject}
busy={busyName === state.skill.name}
isExpanded={!!expanded[`${state.skill.source}:${state.skill.name}`]}
onToggleExpand={() =>
setExpanded((prev) => ({
...prev,
[`${state.skill.source}:${state.skill.name}`]:
!prev[`${state.skill.source}:${state.skill.name}`],
}))
}
onScopeChange={(scope) => setScopes((prev) => ({ ...prev, [state.skill.name]: scope }))}
onModeChange={(mode) => void setMode(state, scopeOf(state), mode)}
/>
))}
</div>
)}
</section>
);
})}
{grouped.length === 0 && !error && (
<div className={styles.emptyBox}>
<T>
No skills found in .agents/skills, .openidea/skills, ~/.agents/skills, or the CLI folders of Claude Code,
GitHub Copilot, Codex, and Cursor.
</T>
</div>
)}
</div>
</div>
);
}
function SkillCard({
state,
scope,
hasProject,
busy,
isExpanded,
onToggleExpand,
onScopeChange,
onModeChange,
}: {
state: AgentSkillState;
scope: McpScope;
hasProject: boolean;
busy: boolean;
isExpanded: boolean;
onToggleExpand: () => void;
onScopeChange: (scope: McpScope) => void;
onModeChange: (mode: AgentSkillMode) => void;
}) {
const tx = useTx();
const { skill } = state;
const group = SKILL_SOURCE_GROUPS[skill.source];
return (
<div role="listitem" className={styles.card}>
<div className={styles.cardHeader}>
<button type="button" className={styles.cardExpandBtn} aria-expanded={isExpanded} onClick={onToggleExpand}>
<Icon name={isExpanded ? "chevron-down" : "chevron-right"} size={13} className={styles.chevron} />
<div className={styles.cardMain}>
<div className={styles.cardTitleRow}>
<span className={styles.skillName}>{skill.name}</span>
{state.mode === "off" ? (
<span className={styles.tag}>
<T>Off</T>
</span>
) : state.mode === "slashOnly" ? (
<span className={styles.tag}>
<T>Slash only</T>
</span>
) : (
<span className={styles.tag}>
<T>Auto</T>
</span>
)}
{state.origin === "user" && (
<span className={styles.tag}>
<T>Global</T>
</span>
)}
{state.origin === "workspace" && (
<span className={clsx(styles.tag, styles.tagAccent)}>
<T>Workspace</T>
</span>
)}
{state.origin === "trust" && (
<span className={clsx(styles.tag, styles.tagWarning)}>
<T>Untrusted workspace</T>
</span>
)}
{isDiscoveredSource(skill.source) && (
<span className={styles.tag}>
<T>CLI-discovered</T>
</span>
)}
{!skill.valid && (
<span className={clsx(styles.tag, styles.tagWarning)}>
<T>Invalid SKILL.md</T>
</span>
)}
</div>
{skill.description && (
<span className={styles.subtitle} title={skill.description}>
{skill.description}
</span>
)}
</div>
</button>
<div className={styles.rowActions}>
<div className={styles.modeControls}>
<Select
className={styles.scopeSelect}
variant="framed"
aria-label={tx`Scope for ${skill.name}`}
value={scope}
disabled={busy}
options={[
{ value: "user", label: tx("Global") },
...(hasProject ? [{ value: "workspace" as McpScope, label: tx("Workspace") }] : []),
]}
onChange={onScopeChange}
/>
<Select
className={styles.modeSelect}
variant="framed"
aria-label={tx`Mode for ${skill.name}`}
value={state.mode}
disabled={busy}
options={MODE_OPTIONS.map((o) => ({ value: o.value, label: tx(o.label) }))}
onChange={onModeChange}
/>
</div>
<span
className={clsx(styles.statusDot, state.mode !== "off" && styles.statusOn)}
title={state.mode === "off" ? tx("Off") : tx("Active")}
/>
</div>
</div>
{isExpanded && (
<div className={styles.cardDrawer}>
<div className={styles.metaGrid}>
<span className={styles.metaLabel}>
<T>Path</T>
</span>
<span className={styles.metaValue}>{skill.path}</span>
<span className={styles.metaLabel}>
<T>Validation</T>
</span>
<span className={styles.metaValue}>
{skill.valid
? tx("SKILL.md is valid")
: (skill.warnings.length > 0 ? skill.warnings : [tx("SKILL.md failed validation")]).join("; ")}
</span>
</div>
{isDiscoveredSource(skill.source) && group.agent && (
<span className={styles.hint}>
<Icon name={providerIcon(group.agent)} size={12} />{" "}
<T>
This CLI discovers the folder itself: off hides the skill from OpenIDEA's / menu and applies only where
the CLI supports disabling.
</T>
</span>
)}
<div className={styles.drawerFooter}>
<div className={styles.drawerButtons}>
<Button
variant="secondary"
onClick={() => void editorService().openFile(`${skill.path}/SKILL.md`, { focus: true })}
>
<Icon name="file" size={12} /> <T>Open SKILL.md</T>
</Button>
<Button variant="secondary" onClick={() => void revealInFileManager(skill.path)}>
<Icon name="folder" size={12} /> {tx(revealInFileManagerLabel())}
</Button>
</div>
<IconButton
icon="copy"
size="small"
title={tx("Copy path")}
aria-label={formatMessage(tx("Copy the path of {name}"), { name: skill.name })}
onClick={() => void navigator.clipboard.writeText(skill.path)}
/>
</div>
</div>
)}
</div>
);
}
-225
Переглянути файл
@@ -1,225 +0,0 @@
.trigger {
display: inline-flex;
align-items: center;
gap: var(--space-1);
height: var(--h-control);
min-width: 0;
padding: 0 6px;
border: 0;
border-radius: var(--radius-control);
background: transparent;
color: var(--fg-secondary);
font: inherit;
white-space: nowrap;
cursor: pointer;
transition: background var(--dur-fast) var(--ease);
}
.trigger:hover,
.trigger[aria-expanded="true"] {
background: var(--bg-toolbar-hover);
color: var(--fg-strong);
}
.triggerLabel {
font-size: var(--fs-ui);
}
.triggerCount {
color: var(--fg-subtle);
font-size: var(--fs-small);
}
.overrideDot {
width: 6px;
height: 6px;
border-radius: 50%;
background: var(--accent);
flex-shrink: 0;
}
.popup {
width: min(352px, calc(100vw - 24px));
display: flex;
flex-direction: column;
padding: 8px 0 6px;
}
.header {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-2);
padding: 0 10px 6px 12px;
border-bottom: 1px solid var(--border);
}
.title {
font-weight: 600;
color: var(--fg-strong);
}
.headerActions {
display: flex;
align-items: center;
gap: var(--space-1);
}
.resetBtn {
padding: 2px 6px;
border: 0;
border-radius: var(--radius-small, 3px);
background: transparent;
color: var(--link);
font: inherit;
font-size: var(--fs-small);
cursor: pointer;
}
.resetBtn:hover {
background: var(--bg-hover);
}
.searchWrap {
padding: 6px 10px 2px;
}
.list {
display: flex;
flex-direction: column;
max-height: 340px;
overflow-y: auto;
padding: 4px 0;
}
.groupLabel {
padding: 6px 12px 2px;
color: var(--fg-muted);
font-size: var(--fs-tiny);
font-weight: 600;
letter-spacing: 0.03em;
text-transform: uppercase;
}
.row {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-2);
padding: 5px 10px 5px 12px;
}
.row:hover {
background: var(--bg-hover);
}
.rowInfo {
display: flex;
flex-direction: column;
gap: 1px;
min-width: 0;
flex: 1;
}
.rowTitle {
display: flex;
align-items: center;
gap: var(--space-1);
min-width: 0;
flex-wrap: wrap;
}
.name {
font-weight: 500;
color: var(--fg-strong);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.sub {
color: var(--fg-muted);
font-size: var(--fs-tiny);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.pill {
display: inline-flex;
align-items: center;
height: 16px;
padding: 0 5px;
border-radius: var(--radius-small, 3px);
background: var(--bg-floating-toolbar);
color: var(--fg-secondary);
font-size: 10px;
font-weight: 500;
}
.pillSession {
background: color-mix(in srgb, var(--accent) 20%, var(--bg-elev));
color: var(--link);
}
.rowControls {
display: flex;
align-items: center;
gap: var(--space-1-5);
flex-shrink: 0;
}
.dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--control-off);
flex-shrink: 0;
}
.dotOn {
background: var(--success);
}
.empty {
padding: 12px;
color: var(--fg-muted);
font-size: var(--fs-small);
text-align: center;
}
.inlineLink {
padding: 2px 6px;
border: 0;
border-radius: var(--radius-small, 3px);
background: var(--bg-elev);
box-shadow: inset 0 0 0 1px var(--border-button);
color: var(--fg-secondary);
font: inherit;
font-size: var(--fs-tiny);
cursor: pointer;
}
.inlineLink:hover {
background: var(--bg-hover);
color: var(--fg-strong);
}
.footer {
display: flex;
flex-direction: column;
gap: var(--space-1);
padding: 6px 12px 2px;
border-top: 1px solid var(--border);
color: var(--fg-muted);
font-size: var(--fs-tiny);
}
/* The composer is the nearest positioned box: its bottom-right corner. */
.hiddenAnchor {
position: absolute;
right: 0;
bottom: 0;
width: 0;
height: 0;
}
-141
Переглянути файл
@@ -1,141 +0,0 @@
import { useState } from "react";
import { describe, expect, it, vi } from "vitest";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import type { AgentSkillMode, AgentSkillSource, AgentSkillState } from "@/bindings";
import { SkillsPicker } from "./SkillsPicker";
import type { SkillsBackend } from "./skillsModel";
const state = (name: string, source: AgentSkillSource, mode: AgentSkillMode): AgentSkillState => ({
skill: {
name,
description: `${name} helps with ${name} things`,
path: `/skills/${name}`,
source,
valid: true,
warnings: [],
},
mode,
origin: mode === "off" ? "user" : "none",
});
const SKILLS: AgentSkillState[] = [
state("tdd", "workspace", "auto"),
state("verify", "workspace", "slashOnly"),
state("impeccable", "user", "off"),
state("playwright", "copilotUser", "auto"),
];
function Harness({
provider = "copilot",
backend,
skills = SKILLS,
}: {
provider?: string;
backend?: SkillsBackend;
skills?: AgentSkillState[];
}) {
const [overrides, setOverrides] = useState<Record<string, AgentSkillMode>>({});
return (
<SkillsPicker
provider={provider}
overrides={overrides}
onChange={setOverrides}
backend={backend}
testData={{ skills }}
/>
);
}
describe("SkillsPicker", () => {
it("shows active counts, groups skills by source, and marks slash-only modes", async () => {
render(<Harness />);
const trigger = screen.getByRole("button", { name: "Skills" });
expect(trigger).toHaveTextContent("Skills3/4");
fireEvent.click(trigger);
expect(await screen.findByText("Session Skills")).toBeInTheDocument();
expect(screen.getByText("Workspace")).toBeInTheDocument();
expect(screen.getByText("User")).toBeInTheDocument();
expect(screen.getByText("GitHub Copilot")).toBeInTheDocument();
expect(screen.getByText("/Slash")).toBeInTheDocument();
expect(screen.getByText("playwright helps with playwright things")).toBeInTheDocument();
});
it("turns a skill off for the session, shows the Session pill, and resets", async () => {
const backend: SkillsBackend = { list: vi.fn(async () => SKILLS), setMode: vi.fn(async () => SKILLS) };
render(<Harness backend={backend} />);
fireEvent.click(screen.getByRole("button", { name: "Skills" }));
const playwright = await screen.findByRole("switch", { name: "Enable playwright for this session" });
expect(playwright).toHaveAttribute("aria-checked", "true");
fireEvent.click(playwright);
await waitFor(() => expect(screen.getByRole("button", { name: "Skills" })).toHaveTextContent("Skills2/4"));
expect(screen.getAllByText("Session")).toHaveLength(1);
fireEvent.click(screen.getByRole("button", { name: "Reset" }));
await waitFor(() => expect(screen.getByRole("button", { name: "Skills" })).toHaveTextContent("Skills3/4"));
expect(screen.queryByText("Session")).not.toBeInTheDocument();
});
it("leaves a skill the settings keep off to the settings page", async () => {
render(<Harness />);
fireEvent.click(screen.getByRole("button", { name: "Skills" }));
expect(screen.queryByRole("switch", { name: "Enable impeccable for this session" })).not.toBeInTheDocument();
expect(await screen.findByRole("button", { name: "Enable in Settings" })).toBeInTheDocument();
});
it("brings a session-off skill back with its toggle", async () => {
render(<Harness />);
fireEvent.click(screen.getByRole("button", { name: "Skills" }));
const tdd = await screen.findByRole("switch", { name: "Enable tdd for this session" });
fireEvent.click(tdd);
expect(screen.getByRole("button", { name: "Skills" })).toHaveTextContent("Skills2/4");
fireEvent.click(tdd);
expect(screen.getByRole("button", { name: "Skills" })).toHaveTextContent("Skills3/4");
expect(screen.queryByText("Session")).not.toBeInTheDocument();
});
it("filters skills by name, description, and path", async () => {
const more = [...SKILLS, state("hex-review", "codexUser", "auto"), state("release-notes", "cursorUser", "auto")];
render(<Harness skills={more} />);
fireEvent.click(screen.getByRole("button", { name: "Skills" }));
fireEvent.change(await screen.findByPlaceholderText("Filter skills…"), { target: { value: "playwright" } });
expect(screen.getByText("playwright")).toBeInTheDocument();
expect(screen.queryByText("tdd")).not.toBeInTheDocument();
fireEvent.change(screen.getByPlaceholderText("Filter skills…"), { target: { value: "/skills/tdd" } });
expect(screen.getByText("tdd")).toBeInTheDocument();
expect(screen.queryByText("playwright")).not.toBeInTheDocument();
});
it("stays honest about ACP agents, whose / menu OpenIDEA only filters", async () => {
render(<Harness provider="cursor-acp" />);
fireEvent.click(screen.getByRole("button", { name: "Skills" }));
expect(
await screen.findByText("This agent keeps its own / menu: off only stops OpenIDEA offering the skill."),
).toBeInTheDocument();
});
it("says nothing special for non-ACP agents", async () => {
render(<Harness provider="claude" />);
fireEvent.click(screen.getByRole("button", { name: "Skills" }));
expect(
screen.queryByText("This agent keeps its own / menu: off only stops OpenIDEA offering the skill."),
).not.toBeInTheDocument();
});
it("shows an empty state without skills", async () => {
render(<Harness skills={[]} />);
fireEvent.click(screen.getByRole("button", { name: "Skills" }));
expect(await screen.findByText("No skills found.")).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Skills" })).toHaveTextContent("Skills0");
});
});
-314
Переглянути файл
@@ -1,314 +0,0 @@
/**
* Per-session skills picker for the New Task and Session composers: shows every discovered skill
* grouped by the folder it came from, lets the user turn skills off for this session only, reset
* session overrides, or jump to Settings › Agents › Skills.
*/
import clsx from "clsx";
import { useEffect, useMemo, useRef, useState } from "react";
import type { AgentSkillMode, AgentSkillState } from "@/bindings";
import { executeAction } from "@/platform/actions";
import { formatMessage, useTx } from "@/platform/i18n";
import { Icon, IconButton, Popup, SearchField, T, Toggle } from "@/ui";
import { SKILLS_PAGE } from "./model";
import { normalizeProviderId } from "./mcpModel";
import {
SKILL_SOURCE_GROUPS,
defaultSkillsBackend,
nextSkillOverrides,
refreshSkillsCatalog,
resolveSessionSkills,
useSkillsCatalog,
useSkillsCatalogSync,
type ResolvedSessionSkills,
type SessionSkillItem,
type SkillsBackend,
} from "./skillsModel";
import styles from "./SkillsPicker.module.css";
export interface SkillsPickerProps {
provider: string;
overrides: Readonly<Record<string, AgentSkillMode>> | undefined;
onChange: (nextOverrides: Record<string, AgentSkillMode>) => void;
disabled?: boolean;
/** True while the session is actively running a turn (changes apply on the next turn). */
busy?: boolean;
/** Bumped when `/skills` is invoked from the composer to open this popover. */
openRequest?: number;
/** No button of its own: opened only through `openRequest`, above the composer. */
hideTrigger?: boolean;
/** Optional overrides for unit tests. */
backend?: SkillsBackend;
testData?: {
skills: readonly AgentSkillState[];
};
}
/** The mode pill a row shows: what the session runs the skill as. */
function ModePill({ mode }: { mode: AgentSkillMode }) {
if (mode === "off") return null;
return <span className={styles.pill}>{mode === "slashOnly" ? <T>/Slash</T> : <T>Auto</T>}</span>;
}
export function SkillsPicker({
provider,
overrides,
onChange,
disabled = false,
busy = false,
openRequest = 0,
hideTrigger = false,
backend = defaultSkillsBackend,
testData,
}: SkillsPickerProps) {
const tx = useTx();
useSkillsCatalogSync(backend);
const catalogSkills = useSkillsCatalog((s) => s.skills);
const skills = testData?.skills ?? catalogSkills;
const [open, setOpen] = useState(false);
const [seenOpenRequest, setSeenOpenRequest] = useState(openRequest);
const [query, setQuery] = useState("");
const anchor = useRef<HTMLElement | null>(null);
const setAnchor = (el: HTMLElement | null) => {
anchor.current = el;
};
if (openRequest !== seenOpenRequest) {
setSeenOpenRequest(openRequest);
if (openRequest > 0 && !disabled) setOpen(true);
}
useEffect(() => {
if (openRequest > 0 && !disabled && !testData) {
void refreshSkillsCatalog(backend);
}
}, [openRequest, disabled, testData, backend]);
const toggleOpen = () => {
const next = !open;
if (next && !testData) void refreshSkillsCatalog(backend);
if (!next) setQuery("");
setOpen(next);
};
const resolved = useMemo(() => resolveSessionSkills(skills, overrides ?? {}), [skills, overrides]);
const q = query.trim().toLowerCase();
const matchesQuery = (item: SessionSkillItem) =>
!q ||
item.name.toLowerCase().includes(q) ||
item.state.skill.description.toLowerCase().includes(q) ||
item.state.skill.path.toLowerCase().includes(q);
const groups = resolved.groups
.map((group) => ({ ...group, items: group.items.filter(matchesQuery) }))
.filter((group) => group.items.length > 0);
const countLabel =
resolved.totalCount === 0
? "0"
: resolved.activeCount === resolved.totalCount
? String(resolved.activeCount)
: `${resolved.activeCount}/${resolved.totalCount}`;
const handleToggleItem = (item: Pick<SessionSkillItem, "name" | "defaultMode">, nextEnabled: boolean) => {
onChange(nextSkillOverrides(overrides, item, nextEnabled));
};
return (
<>
{hideTrigger ? (
// Pinned to the composer's bottom-right corner: the popover opens under the box, like its other pickers.
<span ref={setAnchor} className={styles.hiddenAnchor} aria-hidden />
) : (
<button
ref={setAnchor}
type="button"
disabled={disabled}
className={styles.trigger}
title={
resolved.overrideCount > 0
? formatMessage(tx("Skills ({active}/{total} active · {overrides} session overrides)"), {
active: resolved.activeCount,
total: resolved.totalCount,
overrides: resolved.overrideCount,
})
: formatMessage(tx("Skills ({active}/{total} active)"), {
active: resolved.activeCount,
total: resolved.totalCount,
})
}
aria-label={tx("Skills")}
aria-haspopup="dialog"
aria-expanded={open}
onClick={toggleOpen}
>
<Icon name="bulb" size={13} />
<span className={styles.triggerLabel}>Skills</span>
<span className={styles.triggerCount}>{countLabel}</span>
{resolved.overrideCount > 0 && <span className={styles.overrideDot} aria-hidden />}
</button>
)}
<Popup
open={open}
anchor={anchor}
placement={hideTrigger ? "bottom-end" : "top-start"}
offset={6}
onClose={() => {
setOpen(false);
setQuery("");
}}
aria-label={tx("Session Skills")}
className={styles.popup}
>
<div className={styles.header}>
<span className={styles.title}>
<T>Session Skills</T>
</span>
<div className={styles.headerActions}>
{resolved.overrideCount > 0 && (
<button type="button" className={styles.resetBtn} onClick={() => onChange({})}>
<T>Reset</T>
</button>
)}
<IconButton
icon="settings"
size="small"
title={tx("Skills…")}
aria-label={tx("Skills…")}
onClick={() => {
setOpen(false);
void executeAction("file.settings", SKILLS_PAGE);
}}
/>
</div>
</div>
{resolved.totalCount > 5 && (
<div className={styles.searchWrap}>
<SearchField
value={query}
onChange={setQuery}
placeholder={tx("Filter skills…")}
aria-label={tx("Filter skills")}
/>
</div>
)}
<div className={styles.list}>
{groups.map((group) => (
<GroupRows
key={group.source}
source={group.source}
items={group.items}
onToggle={(item, on) => handleToggleItem(item, on)}
onOpenSettings={() => {
setOpen(false);
void executeAction("file.settings", SKILLS_PAGE);
}}
/>
))}
{groups.length === 0 && (
<div className={styles.empty}>
{resolved.totalCount === 0 ? <T>No skills found.</T> : <T>No matching skills.</T>}
</div>
)}
</div>
<div className={styles.footer}>
<span>
{busy ? <T>Changes apply on the next message.</T> : <T>Toggles here apply to this session only.</T>}
</span>
{provider !== normalizeProviderId(provider) && (
<span>
<T>This agent keeps its own / menu: off only stops OpenIDEA offering the skill.</T>
</span>
)}
</div>
</Popup>
</>
);
}
function GroupRows({
source,
items,
onToggle,
onOpenSettings,
}: {
source: ResolvedSessionSkills["groups"][number]["source"];
items: readonly SessionSkillItem[];
onToggle: (item: SessionSkillItem, enabled: boolean) => void;
onOpenSettings: () => void;
}) {
const tx = useTx();
const group = SKILL_SOURCE_GROUPS[source];
return (
<>
<div className={styles.groupLabel} title={group.paths}>
{tx(group.label)}
</div>
{items.map((item) => (
<SessionSkillRow
key={item.name}
item={item}
onToggle={(on) => onToggle(item, on)}
onOpenSettings={onOpenSettings}
/>
))}
</>
);
}
function SessionSkillRow({
item,
onToggle,
onOpenSettings,
}: {
item: SessionSkillItem;
onToggle: (enabled: boolean) => void;
onOpenSettings: () => void;
}) {
const tx = useTx();
// The settings decide a skill that is off by default; the session only ever turns active skills off.
const locked = item.defaultMode === "off";
const enabled = item.mode !== "off";
return (
<div className={styles.row}>
<div className={styles.rowInfo}>
<div className={styles.rowTitle}>
<span className={styles.name}>{item.name}</span>
<ModePill mode={item.mode} />
{item.overridden && (
<span className={clsx(styles.pill, styles.pillSession)}>
<T>Session</T>
</span>
)}
</div>
{item.state.skill.description && (
<span className={styles.sub} title={item.state.skill.description}>
{item.state.skill.description}
</span>
)}
</div>
<div className={styles.rowControls}>
{locked ? (
<button type="button" className={styles.inlineLink} onClick={onOpenSettings}>
<T>Enable in Settings</T>
</button>
) : (
<>
<Toggle
checked={enabled}
aria-label={formatMessage(tx("Enable {name} for this session"), { name: item.name })}
onChange={onToggle}
/>
<span className={clsx(styles.dot, enabled && styles.dotOn)} aria-hidden />
</>
)}
</div>
</div>
);
}
-1
Переглянути файл
@@ -21,7 +21,6 @@ export const AGENT_SETTINGS_DEFAULTS: ResolvedAgentSettings = {
newTaskApprovals: "bypass",
defaults: {},
mcpServers: {},
skills: {},
};
export function resolveAgentSettings(s: AgentSettings | null | undefined): ResolvedAgentSettings {
-12
Переглянути файл
@@ -182,18 +182,6 @@ describe("New Task composer commands", () => {
expect(await screen.findByText("Session MCP Servers")).toBeInTheDocument();
});
it("opens the per-session skills picker when /skills is completed in the composer", async () => {
agentCommands.mockResolvedValue({ status: "ok", data: [] });
render(<HomeEditor />);
const box = screen.getByRole("textbox");
typeIn(box, "/sk");
const list = await screen.findByRole("listbox", { name: "Commands" });
expect(within(list).getByRole("option", { selected: true })).toHaveTextContent("/skills");
fireEvent.keyDown(box, { key: "Enter" });
expect(textOf(box)).toBe("");
expect(await screen.findByText("Session Skills")).toBeInTheDocument();
});
it("names the icon-only Start action and disables it while starting", async () => {
agentCommands.mockResolvedValue({ status: "ok", data: [] });
let finish!: (value: unknown) => void;
-2
Переглянути файл
@@ -13,8 +13,6 @@ export const REGISTRY_PAGE = "agents.list";
export const AGENTS_GROUP = "Agents";
/** Settings › Agents › External MCP Servers: User and Workspace MCP configurations. */
export const MCP_PAGE = "agents.mcpServers";
/** Settings › Agents › Skills: every CLI's SKILL.md folders and their modes. */
export const SKILLS_PAGE = "agents.skills";
/** Settings › Agents › Command Permissions. */
export const POLICY_PAGE = "agents.policy";
-23
Переглянути файл
@@ -10,7 +10,6 @@ import { Composer } from "../Composer";
import { ConfigPickers } from "../ConfigPickers";
import { HermesProfilePicker } from "../HermesProfilePicker";
import { McpPicker } from "../McpPicker";
import { SkillsPicker } from "../SkillsPicker";
import styles from "../Session.module.css";
import { SessionAssets } from "../SessionAssets";
import { SubmitButton } from "../SubmitButton";
@@ -28,7 +27,6 @@ import {
sendQueuedNow,
setTaskConfig,
setTaskMcpOverrides,
setTaskSkillOverrides,
stopBackgroundTask,
useAgentCommands,
useAgents,
@@ -199,7 +197,6 @@ export function SessionComposer({
const configChange = useRef<{ loadingModel: boolean } | null>(null);
const [configuring, setConfiguring] = useState<typeof configChange.current>(null);
const [mcpOpenRequest, setMcpOpenRequest] = useState(0);
const [skillsOpenRequest, setSkillsOpenRequest] = useState(0);
const [assetFocus, setAssetFocus] = useState(0);
const agentCommands = useAgentCommands(task.provider, task.id, task.commands);
const busy = isBusy(task.status);
@@ -266,7 +263,6 @@ export function SessionComposer({
});
};
const openMcp = () => setMcpOpenRequest((n) => n + 1);
const openSkills = () => setSkillsOpenRequest((n) => n + 1);
const shown = useEditorShown();
const effortAnnouncement = useEffortFocus(focusRoot, shown && task.status !== "archived", task.config, setOption);
return (
@@ -311,11 +307,9 @@ export function SessionComposer({
onConfig={setOption}
onSubmit={send}
onOpenMcp={openMcp}
onOpenSkills={openSkills}
disabled={task.status === "archived"}
addMenu={[
{ id: "mcp", label: "MCP Servers…", icon: "plugin", disabled: task.status === "archived", run: openMcp },
{ id: "skills", label: "Skills…", icon: "bulb", disabled: task.status === "archived", run: openSkills },
]}
toolbar={
<>
@@ -358,23 +352,6 @@ export function SessionComposer({
)
}
/>
<SkillsPicker
provider={task.provider}
overrides={task.skillOverrides}
disabled={task.status === "archived"}
busy={busy}
openRequest={skillsOpenRequest}
hideTrigger
onChange={(next) =>
void setTaskSkillOverrides(task.id, next).catch((e: unknown) =>
notifications().notify({
level: "error",
title: "Couldn't change the setting",
body: String(e),
}),
)
}
/>
</>
}
actions={
+2 -10
Переглянути файл
@@ -1,8 +1,8 @@
import { lazyComponent } from "@/ui";
import { registerSettingsPages } from "@/workbench/contributions";
import { AGENTS_GROUP, MCP_PAGE, POLICY_PAGE, REGISTRY_PAGE, SKILLS_PAGE } from "./model";
import { AGENTS_GROUP, MCP_PAGE, POLICY_PAGE, REGISTRY_PAGE } from "./model";
/** Settings › Agents › Coding Agents, External MCP Servers, Skills, and Command Permissions (also used by the Settings window). */
/** Settings › Agents › Coding Agents and Settings › Agents › External MCP Servers (also used by the Settings window). */
export function activateSettingsPages(): () => void {
return registerSettingsPages([
{
@@ -22,14 +22,6 @@ export function activateSettingsPages(): () => void {
keywords: ["mcp", "model context protocol", "servers", "tools", "agent"],
component: lazyComponent(() => import("./McpServersPage").then((m) => m.McpServersPage)),
},
{
id: SKILLS_PAGE,
title: "Skills",
group: AGENTS_GROUP,
order: 480,
keywords: ["skills", "skill", "skill.md", "agents", "slash commands", "auto", "slash only"],
component: lazyComponent(() => import("./SkillsPage").then((m) => m.SkillsPage)),
},
{
id: POLICY_PAGE,
title: "Command Permissions",
-140
Переглянути файл
@@ -1,140 +0,0 @@
/**
* Shared agent-skills model behind Settings › Agents › Skills and the composer Skills picker:
* the discovered skills of every CLI with their resolved modes, and the per-session overrides
* (`AgentTask.skill_overrides`) on top of them.
*/
import { useEffect } from "react";
import { create } from "zustand";
import type { AgentSkillMode, AgentSkillSource, AgentSkillState, McpScope } from "@/bindings";
import { call, commands, isTauri, onIdeEvent } from "@/platform/ipc";
import { useProject } from "@/platform/project";
export interface SkillsBackend {
list(): Promise<AgentSkillState[]>;
setMode(name: string, scope: McpScope, mode: AgentSkillMode): Promise<AgentSkillState[]>;
}
export const defaultSkillsBackend: SkillsBackend = {
list: () => (typeof commands.agentSkillsList === "function" ? call(commands.agentSkillsList()) : Promise.resolve([])),
setMode: (name, scope, mode) => call(commands.agentSkillsSetMode(name, scope, mode)),
};
/** Which folder family a skill came from, with the paths it is discovered in. */
export const SKILL_SOURCE_GROUPS: Record<AgentSkillSource, { label: string; paths: string; agent: string | null }> = {
workspace: { label: "Workspace", paths: ".agents/skills · .openidea/skills", agent: null },
user: { label: "User", paths: "~/.agents/skills", agent: null },
claudeWorkspace: { label: "Claude Code", paths: ".claude/skills", agent: "claude" },
claudeUser: { label: "Claude Code", paths: "~/.claude/skills", agent: "claude" },
githubWorkspace: { label: "GitHub Copilot", paths: ".github/skills", agent: "copilot" },
copilotUser: { label: "GitHub Copilot", paths: "~/.copilot/skills · installed plugins", agent: "copilot" },
codexWorkspace: { label: "Codex", paths: ".codex/skills", agent: "codex" },
codexUser: { label: "Codex", paths: "~/.codex/skills", agent: "codex" },
cursorWorkspace: { label: "Cursor", paths: ".cursor/skills", agent: "cursor" },
cursorUser: { label: "Cursor", paths: "~/.cursor/skills", agent: "cursor" },
};
/** Skill folders the CLI discovers itself: OpenIDEA only reads them, and its "off" holds only where the CLI supports it. */
export function isDiscoveredSource(source: AgentSkillSource): boolean {
return source !== "workspace" && source !== "user";
}
export interface SessionSkillItem {
name: string;
state: AgentSkillState;
/** The mode the settings resolve to for this session, before any override. */
defaultMode: AgentSkillMode;
/** Effective mode for this session after applying `overrides`. */
mode: AgentSkillMode;
/** True when `overrides` explicitly diverges from the resolved policy. */
overridden: boolean;
}
export interface ResolvedSessionSkills {
groups: Array<{ source: AgentSkillSource; items: SessionSkillItem[] }>;
activeCount: number;
totalCount: number;
overrideCount: number;
}
/** Resolves the session's skills: the discovered list with its modes, then the session's overrides. */
export function resolveSessionSkills(
skills: readonly AgentSkillState[],
overrides: Readonly<Record<string, AgentSkillMode>> = {},
): ResolvedSessionSkills {
const items = skills.map<SessionSkillItem>((state) => {
const explicit = overrides[state.skill.name];
return {
name: state.skill.name,
state,
defaultMode: state.mode,
mode: explicit ?? state.mode,
overridden: explicit !== undefined && explicit !== state.mode,
};
});
const groups: ResolvedSessionSkills["groups"] = [];
const seen = new Set<AgentSkillSource>();
for (const item of items) {
if (seen.has(item.state.skill.source)) continue;
seen.add(item.state.skill.source);
groups.push({
source: item.state.skill.source,
items: items.filter((i) => i.state.skill.source === item.state.skill.source),
});
}
const activeCount = items.filter((i) => i.mode !== "off").length;
const overrideCount = items.filter((i) => i.overridden).length;
return { groups, activeCount, totalCount: items.length, overrideCount };
}
/** Computes the minimal `skillOverrides` map after toggling `name`: off pins `off`, on returns to the policy. */
export function nextSkillOverrides(
current: Readonly<Record<string, AgentSkillMode>> | undefined,
item: Pick<SessionSkillItem, "name" | "defaultMode">,
nextEnabled: boolean,
): Record<string, AgentSkillMode> {
const next = { ...(current ?? {}) };
if (nextEnabled) {
delete next[item.name];
} else {
next[item.name] = "off";
}
return next;
}
/** Shared window-level cache of the skills every CLI exposes, with their resolved modes. */
interface SkillsCatalogState {
skills: AgentSkillState[];
loaded: boolean;
}
export const useSkillsCatalog = create<SkillsCatalogState>(() => ({
skills: [],
loaded: false,
}));
let listenerAttached = false;
export async function refreshSkillsCatalog(backend: SkillsBackend = defaultSkillsBackend): Promise<void> {
if (!isTauri()) return;
const skills = await backend.list().catch(() => null);
if (skills) useSkillsCatalog.setState({ skills, loaded: true });
}
export function useSkillsCatalogSync(backend: SkillsBackend = defaultSkillsBackend): void {
const root = useProject((s) => s.project?.root);
useEffect(() => {
if (!isTauri()) return;
void refreshSkillsCatalog(backend);
const onFocus = () => void refreshSkillsCatalog(backend);
window.addEventListener("focus", onFocus);
if (!listenerAttached && typeof onIdeEvent === "function") {
listenerAttached = true;
onIdeEvent("settingsChanged", (e) => {
if (!e.key || e.key.startsWith("agents.skills")) {
void refreshSkillsCatalog(backend);
}
});
}
return () => window.removeEventListener("focus", onFocus);
}, [root, backend]);
}
-21
Переглянути файл
@@ -16,7 +16,6 @@ import type {
AgentModelCatalog,
AgentPrompt,
AgentProvider,
AgentSkillMode,
AgentTask,
ExternalSession,
Isolation,
@@ -85,8 +84,6 @@ export interface Draft {
base: string | null;
/** Per-session MCP server enable/disable overrides (`server_name` -> `enabled`) for the next task. */
mcpOverrides?: Record<string, boolean>;
/** Per-session skill modes (`skill name` -> mode) for the next task. */
skillOverrides?: Record<string, AgentSkillMode>;
}
/** Composer key of the New Task page; sessions use their task id. */
@@ -1231,7 +1228,6 @@ export async function startTask(
isolation,
base: isolation === "worktree" ? draft.base : null,
mcpOverrides: draft.mcpOverrides ?? {},
skillOverrides: draft.skillOverrides ?? {},
// A `!` command runs in the new task before the agent hears anything.
idle: command !== null,
}),
@@ -1566,10 +1562,6 @@ export function setDraftMcpOverrides(mcpOverrides: Record<string, boolean>) {
updateDraft({ mcpOverrides });
}
export function setDraftSkillOverrides(skillOverrides: Record<string, AgentSkillMode>) {
updateDraft({ skillOverrides });
}
export async function setTaskMcpOverrides(task: string, overrides: Record<string, boolean>): Promise<void> {
const prev = useAgents.getState().tasks.get(task);
if (prev) {
@@ -1583,19 +1575,6 @@ export async function setTaskMcpOverrides(task: string, overrides: Record<string
}));
}
export async function setTaskSkillOverrides(task: string, overrides: Record<string, AgentSkillMode>): Promise<void> {
const prev = useAgents.getState().tasks.get(task);
if (prev) {
useAgents.setState((s) => ({
tasks: new Map(s.tasks).set(task, { ...prev, skillOverrides: overrides }),
}));
}
const updated = await call(commands.agentSetSkillOverrides(task, overrides));
useAgents.setState((s) => ({
tasks: new Map(s.tasks).set(task, updated),
}));
}
/** The composer the user is looking at: the Agents surface on show, else the one typed in last. */
function activeComposerKey(): string {
const s = useAgents.getState();
+22 -22
Переглянути файл
@@ -16,28 +16,22 @@
border-bottom: 1px solid var(--border);
}
.module {
min-width: min(136px, 100%);
max-width: min(260px, 100%);
min-width: 160px;
max-width: 260px;
}
.search {
flex: 1 1 140px;
min-width: min(140px, 100%);
min-width: 140px;
max-width: 360px;
}
.scope {
min-width: min(96px, 100%);
max-width: min(240px, 100%);
min-width: 110px;
}
.toolbarActions,
.viewActions {
display: flex;
align-items: center;
gap: var(--space-1);
flex: none;
}
.toolbarActions {
padding-inline-start: var(--space-1);
border-inline-start: 1px solid var(--border);
.sep {
width: 1px;
height: 16px;
margin: 0 2px;
background: var(--border);
}
.banner {
flex: none;
@@ -66,7 +60,13 @@
flex: 1;
min-width: 0;
}
.tree {
.panel {
display: flex;
flex-direction: column;
min-width: 0;
min-height: 0;
}
.panel > * {
flex: 1;
min-height: 0;
}
@@ -94,6 +94,7 @@
}
.version {
flex: none;
font-family: var(--font-mono);
font-size: var(--fs-small);
color: var(--fg-secondary);
}
@@ -119,24 +120,22 @@
min-height: 0;
height: 100%;
}
.paneHeader {
.usagesHeader {
flex: none;
display: flex;
align-items: center;
gap: var(--space-1-5);
min-height: calc(var(--h-field) + var(--space-1));
min-height: 32px;
padding: 0 10px;
border-bottom: 1px solid var(--border);
}
.paneTitle {
.usagesTitle {
flex: 1;
min-width: 0;
margin: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: var(--fs-ui);
font-weight: 500;
font-family: var(--font-mono);
color: var(--fg-strong);
}
.conflictNote {
@@ -168,6 +167,7 @@
}
.usageVersion {
flex: none;
font-family: var(--font-mono);
color: var(--fg);
}
.usageStatus {
+2 -3
Переглянути файл
@@ -114,8 +114,7 @@ describe("dependency analyzer", () => {
it("marks conflicts, shows their usages and excludes through the direct dependency", async () => {
ipc.exclude.mockResolvedValue({ path: "/p/pom.xml", range: {} });
render(<DependencyAnalyzer input={{ kind: ANALYZER_KIND, key: ANALYZER_KIND }} />);
fireEvent.click(screen.getByRole("button", { name: "Show conflicts only", pressed: false }));
expect(screen.getByRole("button", { name: "Show conflicts only", pressed: true })).toBeTruthy();
fireEvent.click(screen.getByRole("checkbox", { name: "Show conflicts only" }));
expect(screen.queryByText("com.google.inject:guice")).toBeNull();
fireEvent.mouseDown(screen.getByText("com.google.guava:guava").closest("[role=treeitem]")!, { button: 0 });
expect(screen.getByText("omitted for conflict with 32.1.3-jre")).toBeTruthy();
@@ -214,7 +213,7 @@ describe("dependency analyzer for Gradle", () => {
render(<DependencyAnalyzer input={{ kind: ANALYZER_KIND, key: ANALYZER_KIND }} />);
expect(ipc.gradle).toHaveBeenCalledWith(":app", "runtimeClasspath", false, expect.any(Number), "");
await screen.findByText("com.fasterxml.jackson.core:jackson-databind");
fireEvent.click(screen.getByRole("button", { name: "Show conflicts only", pressed: false }));
fireEvent.click(screen.getByRole("checkbox", { name: "Show conflicts only" }));
expect(screen.queryByText("org.springframework.boot:spring-boot-starter-json")).toBeNull();
fireEvent.mouseDown(screen.getByText("com.fasterxml.jackson.core:jackson-databind").closest("[role=treeitem]")!, {
button: 0,
+58 -93
Переглянути файл
@@ -4,7 +4,7 @@
* selected artifact every path that brings it in, with Exclude / Jump to Source (Maven)
* and Copy Coordinates. Gradle trees are read per configuration, on demand.
*/
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type MouseEvent } from "react";
import { useEffect, useMemo, useRef, useState, type MouseEvent } from "react";
import clsx from "clsx";
import {
call,
@@ -15,10 +15,11 @@ import {
type MavenDependency,
type MavenProject,
} from "@/platform/ipc";
import { useTx, useTxTemplate } from "@/platform/i18n";
import { useTx, useTxTemplate, tx } from "@/platform/i18n";
import { editorService, notifications, type EditorInput } from "@/workbench/contributions";
import {
Button,
Checkbox,
EmptyState,
Icon,
IconButton,
@@ -312,37 +313,28 @@ function UsagesPane({
moduleIcon: string;
pom: string | null;
}) {
const tx = useTx();
const symbol = artifact ? coordinates(artifact) : null;
if (!artifact) return <EmptyState title="Select a dependency to see its usages" />;
const usages = sortedUsages(artifact.usages);
const coords = coordinates({ ...artifact, version: artifact.version });
return (
<div className={styles.usages}>
<div className={styles.paneHeader}>
<h2 className={styles.paneTitle} title={symbol ?? undefined}>
{symbol ? tx`Usages of ${symbol}` : tx("Usages")}
</h2>
{symbol && (
<IconButton icon="copy" size="small" title="Copy Coordinates" onClick={() => void copyText(symbol)} />
)}
<div className={styles.usagesHeader}>
<span className={clsx(styles.usagesTitle, artifact.conflict && styles.conflict)}>{coords}</span>
<IconButton icon="copy" size="small" title="Copy Coordinates" onClick={() => void copyText(coords)} />
</div>
{artifact ? (
<>
{artifact.conflict && (
<div className={styles.conflictNote} role="note">
<Icon name="warning" size={16} />
<span>
<T>Versions requested</T>: {artifact.requested.join(", ")}
</span>
</div>
)}
<div className={styles.usageList} aria-label={tx("Usages")}>
{sortedUsages(artifact.usages).map((u, i) => (
<UsageBlock key={i} usage={u} moduleName={moduleName} moduleIcon={moduleIcon} pom={pom} />
))}
</div>
</>
) : (
<EmptyState title="Select a dependency to see its usages" />
{artifact.conflict && (
<div className={styles.conflictNote} role="note">
<Icon name="warning" size={16} />
<span>
<T>Versions requested</T>: {artifact.requested.join(", ")}
</span>
</div>
)}
<div className={styles.usageList} aria-label={tx("Usages")}>
{usages.map((u, i) => (
<UsageBlock key={i} usage={u} moduleName={moduleName} moduleIcon={moduleIcon} pom={pom} />
))}
</div>
</div>
);
}
@@ -355,18 +347,6 @@ export function DependencyAnalyzer(_props: { input: EditorInput }) {
const gradleSync = useBuild((s) => s.syncing.gradle);
const root = useBuild((s) => s.root);
const chosen = useAnalyzer((s) => s.module);
const hasProject = !!maven || !!gradle?.length;
const view = useRef<HTMLDivElement>(null);
const [stacked, setStacked] = useState(false);
useLayoutEffect(() => {
const frame = view.current;
if (!frame) return;
const measure = () => setStacked(frame.clientWidth < 580);
measure();
const observer = new ResizeObserver(measure);
observer.observe(frame);
return () => observer.disconnect();
}, [hasProject]);
const [query, setQuery] = useState("");
const [conflictsOnly, setConflictsOnly] = useState(false);
const [scope, setScope] = useState<string>(ALL_SCOPES);
@@ -480,41 +460,17 @@ export function DependencyAnalyzer(_props: { input: EditorInput }) {
showContextMenu({ x: e.clientX, y: e.clientY }, items);
};
if (!hasProject) return <EmptyState title="No Maven or Gradle projects" />;
if (!maven && !gradle?.length) return <EmptyState title="No Maven or Gradle projects" />;
const treeView = (
<div className={styles.body}>
<SplitGroup
orientation={stacked ? "vertical" : "horizontal"}
orientation="horizontal"
id="maven-dependency-analyzer-split"
storageKey={stacked ? "openidea.dependencyAnalyzer.split.vertical" : "openidea.dependencyAnalyzer.split"}
storageKey="openidea.dependencyAnalyzer.split"
>
<SplitPanel id="dependencies" minSize={stacked ? "30%" : 200}>
<div className={styles.paneHeader}>
<h2 className={styles.paneTitle}>
<T>Resolved Dependencies</T>
</h2>
<div className={styles.viewActions}>
<IconButton
icon="list"
size="small"
iconSize={16}
title="Show as List"
pressed={mode === "list"}
onClick={() => setMode("list")}
/>
<IconButton
icon="hierarchy"
size="small"
iconSize={16}
title="Show as Tree"
pressed={mode === "tree"}
onClick={() => setMode("tree")}
/>
</div>
</div>
<SplitPanel id="dependencies" minSize={200} className={styles.panel}>
<Tree<Node>
className={styles.tree}
aria-label="Dependencies"
roots={roots}
getKey={(n) => n.key}
@@ -545,7 +501,7 @@ export function DependencyAnalyzer(_props: { input: EditorInput }) {
/>
</SplitPanel>
<SplitHandle />
<SplitPanel id="usages" minSize={stacked ? "30%" : 240}>
<SplitPanel id="usages" minSize={240} className={styles.panel}>
<UsagesPane
artifact={selected}
moduleName={module?.displayName ?? gradleProject?.name ?? ""}
@@ -558,7 +514,7 @@ export function DependencyAnalyzer(_props: { input: EditorInput }) {
);
return (
<div ref={view} className={styles.view}>
<div className={styles.view}>
<div className={styles.toolbar} role="toolbar" aria-label={tx("Dependency Analyzer")}>
<Select
aria-label="Module"
@@ -578,6 +534,7 @@ export function DependencyAnalyzer(_props: { input: EditorInput }) {
aria-label="Search dependencies"
clearable
/>
<Checkbox checked={conflictsOnly} onChange={setConflictsOnly} label="Show conflicts only" />
{gradlePath != null ? (
<Select
aria-label="Configuration"
@@ -599,29 +556,37 @@ export function DependencyAnalyzer(_props: { input: EditorInput }) {
onChange={setScope}
/>
)}
<div className={styles.toolbarActions}>
<IconButton
icon="warning"
size="small"
iconSize={16}
title="Show conflicts only"
pressed={conflictsOnly}
onClick={() => setConflictsOnly((current) => !current)}
/>
{gradlePath != null ? (
configuration === null && gradleSync ? (
<IconButton icon="stop" size="small" iconSize={16} title="Stop" onClick={() => cancelSync("gradle")} />
) : report.loading ? (
<IconButton icon="stop" size="small" iconSize={16} title="Stop" onClick={report.cancel} />
) : (
<IconButton icon="refresh" size="small" iconSize={16} title="Refresh" onClick={refreshGradle} />
)
) : syncing ? (
<IconButton icon="stop" size="small" iconSize={16} action="maven.cancelReload" />
<span className={styles.sep} />
<IconButton
icon="list"
size="small"
iconSize={16}
title="Show as List"
pressed={mode === "list"}
onClick={() => setMode("list")}
/>
<IconButton
icon="hierarchy"
size="small"
iconSize={16}
title="Show as Tree"
pressed={mode === "tree"}
onClick={() => setMode("tree")}
/>
<span className={styles.sep} />
{gradlePath != null ? (
configuration === null && gradleSync ? (
<IconButton icon="stop" size="small" iconSize={16} title="Stop" onClick={() => cancelSync("gradle")} />
) : report.loading ? (
<IconButton icon="stop" size="small" iconSize={16} title="Stop" onClick={report.cancel} />
) : (
<IconButton icon="refresh" size="small" iconSize={16} action="maven.reload" />
)}
</div>
<IconButton icon="refresh" size="small" iconSize={16} title="Refresh" onClick={refreshGradle} />
)
) : syncing ? (
<IconButton icon="stop" size="small" iconSize={16} action="maven.cancelReload" />
) : (
<IconButton icon="refresh" size="small" iconSize={16} action="maven.reload" />
)}
</div>
{gradlePath != null ? (
<>
+4 -4
Переглянути файл
@@ -35,7 +35,7 @@ it("waits for pending typing before undoing the entire backend transaction", asy
release = resolve;
}),
);
emitLocalIdeEvent({ type: "workspaceEditApplied", id: 17, paths: [], moves: [], byAgent: false });
emitLocalIdeEvent({ type: "workspaceEditApplied", id: 17, paths: [], byAgent: false });
const action = notices[0]!.actions![0]!;
expect(action.label).toBe("Undo");
const pending = action.run();
@@ -47,13 +47,13 @@ it("waits for pending typing before undoing the entire backend transaction", asy
it("reports a refused undo instead of discarding newer work", async () => {
mocks.undo.mockRejectedValue(new Error("a.txt changed"));
emitLocalIdeEvent({ type: "workspaceEditApplied", id: 18, paths: [], moves: [], byAgent: false });
emitLocalIdeEvent({ type: "workspaceEditApplied", id: 18, paths: [], byAgent: false });
await notices[0]!.actions![0]!.run();
expect(notices[1]).toMatchObject({ level: "error", title: "Cannot undo refactoring", body: "a.txt changed" });
});
it("does not apply an old notification's id to a different project", async () => {
emitLocalIdeEvent({ type: "workspaceEditApplied", id: 19, paths: [], moves: [], byAgent: false });
emitLocalIdeEvent({ type: "workspaceEditApplied", id: 19, paths: [], byAgent: false });
const previous = useProject.getState().project;
useProject.setState({ project: { ...previous, root: "/different-project" } as NonNullable<typeof previous> });
try {
@@ -66,6 +66,6 @@ it("does not apply an old notification's id to a different project", async () =>
});
it("does not announce an agent's edit as a refactoring", () => {
emitLocalIdeEvent({ type: "workspaceEditApplied", id: 20, paths: [], moves: [], byAgent: true });
emitLocalIdeEvent({ type: "workspaceEditApplied", id: 20, paths: [], byAgent: true });
expect(notices).toEqual([]);
});
+2 -16
Переглянути файл
@@ -1,21 +1,7 @@
import { describe, expect, it } from "vitest";
import {
definitionInsertions,
matchesStep,
snippetStyle,
stepDefinitions,
stepSnippet,
type FeatureStep,
} from "./steps";
import { definitionInsertions, matchesStep, snippetStyle, stepDefinitions, stepSnippet, type FeatureStep } from "./steps";
const step = (text: string): FeatureStep => ({
from: 0,
to: 0,
keyword: "Given ",
type: "Given",
text,
matchText: text,
});
const step = (text: string): FeatureStep => ({ from: 0, to: 0, keyword: "Given ", type: "Given", text, matchText: text });
const apply = (text: string, insertions: { at: number; text: string }[]) =>
[...insertions].sort((a, b) => b.at - a.at).reduce((out, i) => out.slice(0, i.at) + i.text + out.slice(i.at), text);
+1 -4
Переглянути файл
@@ -141,10 +141,7 @@ export function pythonStepSnippet(
const decorator = keyword.toLowerCase();
const quoted = (s: string) => `'${s.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
if (framework === "pytest-bdd")
return {
text: [`@${decorator}(${quoted(text)})`, "def _():", " raise NotImplementedError", ""].join("\n"),
body: 2,
};
return { text: [`@${decorator}(${quoted(text)})`, "def _():", " raise NotImplementedError", ""].join("\n"), body: 2 };
// behave reads the pattern as a `parse` format: braces in the step are literal.
const format = text.replace(/[{}]/g, "$&$&");
return {
+1 -1
Переглянути файл
@@ -1,12 +1,12 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import type { FileMove, WorkspaceEdit } from "@/bindings";
import { movedPath } from "@/editor/fileMoves";
import { onFilesMoved } from "@/platform/fileOps";
import { provideNotificationService } from "@/workbench/contributions";
import {
lastFileRefactoring,
mergeEdits,
movedPath,
runFileRefactoring,
setRefactorBackendForTests,
touchesOtherFiles,
+52 -2
Переглянути файл
@@ -5,8 +5,10 @@
* files change, then the move itself — one step that Undo reverts.
*/
import type { FileMove, UndoOutcome, WorkspaceEdit } from "@/bindings";
import { saveAllQuietly, withEditorsFollowing } from "@/editor/fileMoves";
import { call, commands, isCancelled, isTauri, nextRequestId } from "@/platform/ipc";
import { openEditorPaths } from "@/editor/api";
import { notifyFilesMoved, trackFileMove } from "@/platform/fileOps";
import { call, commands, emitLocalIdeEvent, isCancelled, isTauri, nextRequestId } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { maybeEditorService, notifications } from "@/workbench/contributions";
import { projectFs } from "./fs";
import { isSameOrInside, nameOf, parentOf } from "./paths";
@@ -164,6 +166,54 @@ export function touchesOtherFiles(edit: WorkspaceEdit, moves: readonly FileMove[
);
}
// ---------------------------------------------------------------------------
// Editors follow the move
async function saveAllQuietly(editor: { saveAll(): Promise<void> }) {
try {
await editor.saveAll();
} catch {
/* unsaved files are reported by the editor */
}
}
/** `path` after `moves`. */
export function movedPath(path: string, moves: readonly FileMove[]): string {
let p = path;
for (const m of moves) if (isSameOrInside(p, m.from)) p = m.to + p.slice(m.from.length);
return p;
}
/** IDEA retargets editors of moved files: unsaved changes are saved first, tabs reopen at the new paths. */
async function withEditorsFollowing<T>(run: () => Promise<T>, done: (r: T) => FileMove[]): Promise<T> {
const projectRoot = () => useProject.getState().project?.root ?? null;
const root = projectRoot();
const editor = maybeEditorService();
const openBefore = editor ? openEditorPaths() : [];
if (editor) await saveAllQuietly(editor);
const active = editor?.activePath() ?? null;
const { result, applied } = await trackFileMove(root, async () => {
const result = await run();
const applied = done(result);
if (root === projectRoot()) await notifyFilesMoved(applied);
return { result, applied };
});
if (root !== projectRoot()) return result;
const open = openBefore.filter((p) => applied.some((m) => isSameOrInside(p, m.from)));
if (applied.length)
emitLocalIdeEvent({
type: "fsChanged",
created: applied.map((m) => m.to),
modified: [],
removed: applied.map((m) => m.from),
});
if (!editor || !open.length) return result;
const ordered = active && open.includes(active) ? [...open.filter((p) => p !== active), active] : open;
for (const p of ordered) await editor.openFile(movedPath(p, applied), { focus: false }).catch(() => {});
if (active && !open.includes(active)) await editor.openFile(active, { focus: false }).catch(() => {});
return result;
}
// ---------------------------------------------------------------------------
// Run / undo
-89
Переглянути файл
@@ -1,89 +0,0 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { RunConfig } from "@/platform/ipc";
import {
provideNotificationService,
provideToolWindowService,
type ToolWindowService,
} from "@/workbench/contributions";
import { resetRuns, rerunFailed, runSelectedTests, runtime, startRun, useRun } from "./store";
const classModules = vi.hoisted(() =>
vi.fn(async (cls: string) => ({ "com.a.AlphaTest": ["alpha"], "com.b.BetaTest": ["beta"] })[cls] ?? []),
);
vi.mock("@/platform/javaLaunch", async (importOriginal) => ({
...(await importOriginal<typeof import("@/platform/javaLaunch")>()),
classModules,
}));
vi.mock("./dialogs", () => ({
confirmRerun: vi.fn(async () => true),
confirmTerminate: vi.fn(async () => true),
promptValue: vi.fn(),
RunDialogsOverlay: () => null,
}));
const rootTests: RunConfig = {
id: "gradle:test",
name: "gradle test",
kind: "gradle",
command: "./gradlew",
args: ["test"],
cwd: null,
env: {},
detected: true,
isTest: true,
debugAdapter: null,
};
beforeEach(() => {
resetRuns();
provideToolWindowService({ show: vi.fn(), isVisible: () => true } as unknown as ToolWindowService);
provideNotificationService({ notify: () => undefined });
});
const failedRootRun = async () => {
const session = (await startRun(rootTests))!;
runtime(session.id)!.tests!.apply([
{ type: "result", path: ["com.a.AlphaTest", "one"], status: "failed" },
{ type: "result", path: ["com.b.BetaTest", "two"], status: "failed" },
]);
useRun.setState({
sessions: useRun.getState().sessions.map((s) => (s.id === session.id ? { ...s, status: "finished" } : s)),
});
return session;
};
const lastArgs = () => useRun.getState().sessions.at(-1)!.config.args;
describe("Gradle reruns after a run of the root test task", () => {
it("Rerun Failed Tests runs each test in its own subproject's test task", async () => {
const session = await failedRootRun();
expect(await rerunFailed(session.id)).toBe(true);
await vi.waitFor(() =>
expect(lastArgs()).toEqual([
":alpha:test",
"--tests",
"com.a.AlphaTest.one",
":beta:test",
"--tests",
"com.b.BetaTest.two",
"--continue",
]),
);
});
it("running a selection from the tree does the same", async () => {
const session = await failedRootRun();
const beta = runtime(session.id)!.tests!.node(["com.b.BetaTest", "two"]);
expect(await runSelectedTests(session.id, [beta.id], false)).toBe(true);
expect(lastArgs()).toEqual([":beta:test", "--tests", "com.b.BetaTest.two"]);
});
it("keeps today's command line when a class is not found", async () => {
classModules.mockResolvedValueOnce([]);
const session = await failedRootRun();
expect(await rerunFailed(session.id)).toBe(true);
await vi.waitFor(() =>
expect(lastArgs()).toEqual(["test", "--tests", "com.a.AlphaTest.one", "--tests", "com.b.BetaTest.two"]),
);
});
});
+3 -9
Переглянути файл
@@ -55,7 +55,6 @@ import { TeamcityOutput } from "./testing/teamcity";
import type { TestStdout } from "./testing/types";
import { recordTestStates } from "./testing/states";
import { failedTestPaths, leafTestPaths, rerunFailedConfigs, testsConfigs } from "./testing/rerun";
import { testsBySubproject } from "./testing/gradleSubprojects";
import { buildCMake, isCMakeBuild } from "./cmake";
import { compoundChildren } from "./configs";
import { remoteLabel, startWithRemedies } from "./remote";
@@ -1540,11 +1539,8 @@ export async function rerunFailed(sessionId: string): Promise<boolean> {
const session = getSession(sessionId);
if (!session || isLive(session)) return false;
const base = baseConfigOf(session);
const paths = failedTests(sessionId);
const selection = rerunFailedConfigs(base, paths);
const derived = await Promise.all(
(selection instanceof Promise ? await selection : selection).map((c) => testsBySubproject(c, paths)),
);
const selection = rerunFailedConfigs(base, failedTests(sessionId));
const derived = selection instanceof Promise ? await selection : selection;
if (getSession(sessionId) !== session || isLive(session)) return false;
if (!derived.length) return false;
derived.forEach((config, index) => void startRun(config, index === 0 ? sessionId : undefined, base));
@@ -1568,9 +1564,7 @@ export async function runSelectedTests(
const base = baseConfigOf(session);
const name = nodes.length === 1 ? nodes[0]!.name : `${paths.length} tests`;
const selection = testsConfigs(base, paths, name);
const derived = await Promise.all(
(selection instanceof Promise ? await selection : selection).map((c) => testsBySubproject(c, paths)),
);
const derived = selection instanceof Promise ? await selection : selection;
if (getSession(sessionId) !== session) return false;
if (!derived.length) return false;
for (const [index, next] of derived.entries()) {
-91
Переглянути файл
@@ -1,91 +0,0 @@
import { describe, expect, it } from "vitest";
import type { RunConfig } from "@/platform/ipc";
import { testsBySubproject } from "./gradleSubprojects";
const cfg = (args: string[], over: Partial<RunConfig> = {}): RunConfig => ({
id: "gradle:test",
name: "Failed: gradle test",
kind: "gradle",
command: "./gradlew",
args,
cwd: null,
env: {},
detected: true,
isTest: true,
debugAdapter: null,
...over,
});
const modules: Record<string, string[]> = {
"com.a.AlphaTest": ["alpha"],
"com.b.BetaTest": ["services/beta"],
"com.r.RootTest": [""],
"com.x.Twice": ["alpha", "services/beta"],
};
const find = async (cls: string) => modules[cls] ?? [];
describe("Gradle tests by subproject", () => {
it("runs each failed test with its own subproject's test task", async () => {
const derived = cfg(["test", "--tests", "com.a.AlphaTest.one", "--tests", "com.b.BetaTest$Inner.two"]);
const paths = [
["com.a.AlphaTest", "one()"],
["com.b.BetaTest$Inner", "two"],
];
expect((await testsBySubproject(derived, paths, find)).args).toEqual([
":alpha:test",
"--tests",
"com.a.AlphaTest.one",
":services:beta:test",
"--tests",
"com.b.BetaTest$Inner.two",
"--continue",
]);
});
it("keeps the other options and needs no --continue for one subproject", async () => {
const derived = cfg(["--offline", "test", "--tests", "com.b.BetaTest"]);
expect((await testsBySubproject(derived, [["com.b.BetaTest"]], find)).args).toEqual([
"--offline",
":services:beta:test",
"--tests",
"com.b.BetaTest",
]);
});
it("addresses the root project's own tests as :test next to a subproject's", async () => {
const derived = cfg(["test", "--tests", "com.r.RootTest.a", "--tests", "com.a.AlphaTest.one"]);
const paths = [
["com.r.RootTest", "a"],
["com.a.AlphaTest", "one"],
];
expect((await testsBySubproject(derived, paths, find)).args).toEqual([
":test",
"--tests",
"com.r.RootTest.a",
":alpha:test",
"--tests",
"com.a.AlphaTest.one",
"--continue",
]);
});
it("keeps the configuration when a class is not found in exactly one module", async () => {
const derived = cfg(["test", "--tests", "com.a.AlphaTest.one", "--tests", "com.z.Gone.x"]);
const paths = [
["com.a.AlphaTest", "one"],
["com.z.Gone", "x"],
];
expect(await testsBySubproject(derived, paths, find)).toBe(derived);
const twice = cfg(["test", "--tests", "com.x.Twice"]);
expect(await testsBySubproject(twice, [["com.x.Twice"]], find)).toBe(twice);
});
it("leaves runs alone that already name a task, run only root tests, or are not Gradle", async () => {
const scoped = cfg([":alpha:test", "--tests", "com.a.AlphaTest.one"]);
expect(await testsBySubproject(scoped, [["com.a.AlphaTest", "one"]], find)).toBe(scoped);
const root = cfg(["test", "--tests", "com.r.RootTest.a"]);
expect(await testsBySubproject(root, [["com.r.RootTest", "a"]], find)).toBe(root);
const maven = cfg(["test", "-Dtest=com.a.AlphaTest#one"], { kind: "maven", command: "./mvnw" });
expect(await testsBySubproject(maven, [["com.a.AlphaTest", "one"]], find)).toBe(maven);
});
});
-51
Переглянути файл
@@ -1,51 +0,0 @@
import type { RunConfig } from "@/platform/ipc";
import { classModules } from "@/platform/javaLaunch";
import { inGradleModule } from "../gradleModuleTests";
const isGradle = (config: Pick<RunConfig, "kind" | "command">) =>
config.kind === "gradle" || /(^|[/\\])gradlew?(\.bat)?$/.test(config.command);
/** `--tests` filter of a test tree path, as `rerun.ts` writes it. */
const filterOf = (path: string[]) =>
path.length >= 2 ? `${path[0]}.${path[path.length - 1]!.replace(/\(\)$/, "")}` : path[0]!;
/**
* `derived`, a run of the build's plain `test` task narrowed to the tests at `paths`, with each
* test's filter on its own subproject's test task (`:alpha:test --tests A :beta:test --tests B`;
* a task's `--tests` applies to that task only). The plain task filters every subproject's tests,
* and one without a match fails the build before the others run. IDEA reruns the original tasks
* and fails the same way. `derived` unchanged when a test class is not found in exactly one
* module, or every test is the root project's.
*/
export async function testsBySubproject(
derived: RunConfig,
paths: readonly string[][],
findModules: (className: string) => Promise<string[]> = classModules,
): Promise<RunConfig> {
if (!isGradle(derived) || !derived.args.includes("test") || !paths.length) return derived;
const groups = new Map<string, string[]>();
for (const path of paths) {
const modules = await findModules(path[0]!.split("$")[0]!);
if (modules.length !== 1) return derived;
const filters = groups.get(modules[0]!) ?? [];
filters.push(filterOf(path));
groups.set(modules[0]!, filters);
}
if (groups.size === 1 && groups.has("")) return derived;
let cwd = derived.cwd;
const tasks = [...groups].flatMap(([module, filters]) => {
const scoped = inGradleModule({ ...derived, args: ["test"] }, module);
cwd = scoped.cwd;
const task = scoped.args[0] === "test" ? ":test" : scoped.args[0]!;
return [task, ...[...new Set(filters)].flatMap((f) => ["--tests", f])];
});
const args: string[] = [];
for (let i = 0; i < derived.args.length; i++) {
const a = derived.args[i]!;
if (a === "--tests") i++;
else if (a === "test") args.push(...tasks);
else if (!a.startsWith("--tests=")) args.push(a);
}
if (groups.size > 1 && !args.includes("--continue")) args.push("--continue");
return { ...derived, cwd, args };
}
-9
Переглянути файл
@@ -165,15 +165,6 @@ describe("items and rows", () => {
expect([t!.col, t!.endCol]).toEqual([8, 13]);
});
it("textItems keeps each window of a long line as its own item", () => {
const items = textItems("/p/min.js", "min.js", [
{ line: 0, text: "x foo x", ranges: [[2, 5]], textOffset: 0 },
{ line: 0, text: "x foo x", ranges: [[2, 5]], textOffset: 2000 },
]);
expect(new Set(items.map((i) => i.key)).size).toBe(2);
expect(items.map((i) => i.col)).toEqual([2, 2002]);
});
it("buildRows orders sections, adds headers and more rows", () => {
const sections = new Map<SectionId, SectionState>([
[
-18
Переглянути файл
@@ -219,24 +219,6 @@ describe("result helpers", () => {
expect(rows[0]).toMatchObject({ text: "let foo = 1", ranges: [[4, 7]], col: 18, endCol: 21, matched: ["foo"] });
});
it("matchRows keeps each window of a long line as its own row", () => {
const rows = matchRows([
{
path: "/p/min.js",
relPath: "min.js",
matches: [
{ line: 0, text: "x foo x", ranges: [[2, 5]], textOffset: 0 },
{ line: 0, text: "x foo x", ranges: [[2, 5]], textOffset: 2000 },
],
},
]);
expect(new Set(rows.map((r) => r.key)).size).toBe(2);
expect(rows.flatMap((r) => r.starts)).toEqual([
{ line: 0, col: 2 },
{ line: 0, col: 2002 },
]);
});
it("previewReplacement supports Rust-style regex groups", () => {
const re = { pattern: "(\\w+)=(\\d+)", isRegex: true, caseSensitive: true };
expect(previewReplacement("a=1", re, "${2}:$1")).toBe("1:a");
-8
Переглянути файл
@@ -87,14 +87,6 @@ describe("buildFindTree", () => {
expect(roots.map((n) => n.key)).toEqual(["f:/p/a.ts", "f:/p/src/a.ts", "f:/p/src/b.ts"]);
});
it("keeps each window of a long line as its own node", () => {
const long = file("min.js");
long.matches.push({ ...long.matches[0]!, textOffset: 2000 });
const [f] = buildFindTree([long]);
const children = f?.kind === "file" ? f.children : [];
expect(new Set(children.map((n) => n.key)).size).toBe(2);
});
it("groups files by directory on request", () => {
const roots = buildFindTree(files, true);
expect(roots.map((n) => (n.kind === "dir" ? [n.label, n.count] : n.kind))).toEqual([
+1 -1
Переглянути файл
@@ -442,7 +442,7 @@ export function textItems(path: string, rel: string, matches: readonly LineMatch
const first = m.ranges[0] ?? [0, 0];
out.push({
kind: "text",
key: `t:${path}:${m.line}:${first[0] + m.textOffset}`,
key: `t:${path}:${m.line}:${first[0]}`,
path,
rel,
line: m.line,
+1 -1
Переглянути файл
@@ -95,7 +95,7 @@ export function buildFindTree(files: readonly FileMatches[], groupByDirectory =
const first = m.ranges[0] ?? [0, 0];
return {
kind: "match",
key: `m:${f.path}:${m.line}:${first[0] + m.textOffset}`,
key: `m:${f.path}:${m.line}`,
path: f.path,
line: m.line,
col: first[0] + m.textOffset,
+1 -2
Переглянути файл
@@ -197,8 +197,7 @@ export function matchRows(files: readonly FileMatches[]): MatchRow[] {
.filter(([s, e]) => e > s);
const first = m.ranges[0] ?? [0, 0];
rows.push({
// A long line comes in several windows: the column tells them apart.
key: `${f.path}:${m.line}:${first[0] + m.textOffset}`,
key: `${f.path}:${m.line}`,
path: f.path,
relPath: f.relPath,
line: m.line,
-1
Переглянути файл
@@ -19,7 +19,6 @@ describe("agent chat settings", () => {
newTaskApprovals: "bypass",
defaults: {},
mcpServers: {},
skills: {},
});
const stored = validateSettings({
agents: { showUsageLimits: false, showCost: true, showWorkTime: "no", fitWindowWidth: true },
-11
Переглянути файл
@@ -245,7 +245,6 @@ export const DEFAULT_SETTINGS: ValidSettings = {
newTaskApprovals: "bypass",
defaults: {},
mcpServers: {},
skills: {},
},
mcpServer: {
enabled: false,
@@ -315,15 +314,6 @@ function agentMcpServers(v: unknown): Required<AgentSettings>["mcpServers"] {
return out;
}
function agentSkillPolicies(v: unknown): Required<AgentSettings>["skills"] {
const out: Required<AgentSettings>["skills"] = {};
for (const [name, raw] of Object.entries(obj(v))) {
if (!name.trim()) continue;
out[name] = { mode: oneOf(obj(raw).mode, ["auto", "slashOnly", "off"] as const, "auto") };
}
return out;
}
const oneOf = <T extends string>(v: unknown, allowed: readonly T[], d: T): T =>
typeof v === "string" && (allowed as readonly string[]).includes(v) ? (v as T) : d;
const num = (v: unknown, d: number, { min, max }: { min: number; max: number }, int = false) => {
@@ -458,7 +448,6 @@ export function validateSettings(raw: Settings | unknown): ValidSettings {
newTaskApprovals: oneOf(agents.newTaskApprovals, ["bypass", "ask"] as const, d.agents.newTaskApprovals),
defaults: agentDefaults(agents.defaults),
mcpServers: agentMcpServers(agents.mcpServers),
skills: agentSkillPolicies(agents.skills),
},
mcpServer: {
enabled: bool(obj(root.mcpServer).enabled, d.mcpServer.enabled),
+1 -2
Переглянути файл
@@ -123,12 +123,11 @@
.radio {
display: inline-flex;
flex: none;
max-inline-size: 100%;
white-space: nowrap;
align-items: center;
gap: var(--space-1-5);
}
.radio input {
flex: none;
margin: 0;
accent-color: var(--accent);
}
-28
Переглянути файл
@@ -138,34 +138,6 @@
.table tbody tr.selectedRow {
background: var(--bg-tree-selected);
}
.saveActions {
display: flex;
flex-direction: column;
gap: var(--space-3);
font-size: var(--fs-ui);
}
.saveActionsTable th {
background: var(--bg-control);
}
.saveActionsTable td {
height: auto;
padding-block: var(--space-1);
vertical-align: top;
white-space: normal;
overflow-wrap: anywhere;
}
.saveActivationColumn {
width: 168px;
}
@container settings-content (width < 560px) {
.saveActivationColumn {
width: 120px;
}
}
.saveActivation {
padding-block-start: var(--space-0-5);
color: var(--fg-muted);
}
.mappingsTable {
height: 100%;
min-height: 0;
-6
Переглянути файл
@@ -34,12 +34,6 @@
align-items: center;
gap: var(--space-1-5);
}
.inlineChoices {
flex-wrap: wrap;
min-height: var(--h-field);
max-width: 100%;
gap: var(--space-1) var(--space-4);
}
.inlineLabel::after {
content: ":";
}
+12 -45
Переглянути файл
@@ -8,7 +8,7 @@
import { useEffect, useId, useState } from "react";
import clsx from "clsx";
import { commands, isTauri } from "@/platform/ipc";
import { Checkbox, Icon, Radio, type IconName } from "@/ui";
import { Checkbox, Icon, type IconName } from "@/ui";
import { SearchLabel, Select } from "../../components/Form";
import { useLabelMatch, useSearchQuery, useSetting } from "../../components/context";
import { labelMatches } from "../../model/pages";
@@ -377,46 +377,6 @@ const BREADCRUMBS = editorPage({
],
});
const COMPLETION_MATCH_CASE_LABEL = "Match case:";
const COMPLETION_CASE_OPTIONS = [
{ value: "first", label: "First letter only" },
{ value: "all", label: "All letters" },
] as const;
function CompletionMatchCase() {
const [matchCase, setMatchCase] = useSetting<boolean>(`${P}.completion.matchCase`);
const [caseSensitivity, setCaseSensitivity] = useSetting<string>(`${P}.completion.caseSensitivity`);
const selected = caseSensitivity === "all" ? "all" : "first";
const name = useId();
const matched = useLabelMatch(COMPLETION_MATCH_CASE_LABEL);
return (
<div className={clsx(styles.check, matched && styles.matched)} data-search-match={matched || undefined}>
<Checkbox
checked={!!matchCase}
onChange={setMatchCase}
label={<SearchLabel text={COMPLETION_MATCH_CASE_LABEL} />}
/>
<span
className={clsx(styles.inline, styles.inlineChoices)}
role="radiogroup"
aria-label={tx(COMPLETION_MATCH_CASE_LABEL)}
>
{COMPLETION_CASE_OPTIONS.map((option) => (
<Radio
key={option.value}
name={name}
checked={option.value === selected}
onChange={() => setCaseSensitivity(option.value)}
disabled={!matchCase}
label={<SearchLabel text={option.label} />}
/>
))}
</span>
</div>
);
}
const COMPLETION = editorPage({
id: "editor.general.codeCompletion",
title: "Code Completion",
@@ -426,10 +386,17 @@ const COMPLETION = editorPage({
{
items: [
{
t: "custom",
label: COMPLETION_MATCH_CASE_LABEL,
keywords: COMPLETION_CASE_OPTIONS.map((option) => option.label),
component: CompletionMatchCase,
t: "check",
key: `${P}.completion.matchCase`,
label: "Match case:",
inline: {
kind: "select",
key: `${P}.completion.caseSensitivity`,
options: [
{ value: "first", label: "First letter only" },
{ value: "all", label: "All letters" },
],
},
},
{
t: "check",
Loaded 100 of 134 files, more files were not shown because too many files have changed in this diff. Show more