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

...
Автор SHA1 Повідомлення Дата
l0ng-ai 0103f2af94 fix(editor): write failed saves to the log with their stack
A failed save showed only its message in the "Could not save" notification,
and a failed autosave of a closed tab went to the console. Both now go to the
log file, so a report's log shows where the save failed.
2026-11-21 02:49:01 +08:00
Emir 51bab9a25b feat(i18n): add Turkish localization (#4881)
Turkish joins the UI languages (Settings > Appearance > Language), with the key catalog and the source-text catalog; tr / tr-TR system locales resolve to it.

Co-authored-by: laot7490 <[email protected]>

Co-authored-by: laot7490 <[email protected]>
2026-11-21 02:01:59 +08:00
Vadim LazukтаInf1mum 302c4068cf feat(agents): skills hub for every CLI, per-workspace modes, and per-session skills picker (#4879)
Fixes #3897 (phase 1)

Settings > Agents > Skills lists every skill found in the workspace (.agents/skills, .openidea/skills and each CLI's folder) and the user's folders (~/.agents/skills, ~/.claude/skills, ~/.copilot, ~/.codex, ~/.cursor), with symlinked copies collapsed and SKILL.md validated. Each skill can be auto, slash only or off, globally or per workspace ([agents.skills.<name>] in settings.toml). SKILL.md files are never edited. An untrusted workspace can only turn skills off. The composer gets a per-session Skills picker and /skills, and / completion offers active skills for every agent.

Sessions get their skills through a per-task folder that is rebuilt on each start: Claude Code via --add-dir and --settings skillOverrides, Copilot via skillDirectories/disabledSkills, Codex via skills/extraRoots/set and skills.config. Other ACP agents only get their / menu filtered.

Co-authored-by: Inf1mum <[email protected]>

Co-authored-by: Inf1mum <[email protected]>
2026-11-21 01:57:18 +08:00
l0ng-ai ff11932a65 fix(vcs): keep git status from rewriting the index (#4880)
Refs #4792

The dirty-scope status refresh (and the full one when gitoxide can't read the tree) ran git status, which writes refreshed stat data back to .git/index. The watcher can't tell that write from an external one, so it scheduled another refresh that could run git again. git status now runs with GIT_OPTIONAL_LOCKS=0 and leaves the index alone; our own gitoxide write-back is unchanged.
2026-11-21 01:45:09 +08:00
42 змінених файлів з 12612 додано та 56 видалено

No files matched your search

+178 -14
Переглянути файл
@@ -23,7 +23,7 @@ mod provider;
pub mod registry;
pub mod security;
mod shell;
mod skills;
pub mod skills;
mod timeline;
mod worktree;
@@ -131,6 +131,19 @@ pub type McpServersFn = dyn Fn() -> Vec<McpServer> + Send + Sync;
/// Returns the executable of the running built-in MCP server, if any.
pub type McpExecutableFn = dyn Fn() -> Option<PathBuf> + Send + Sync;
/// The `[agents.skills.<name>]` policies a session resolves against: the user's (global
/// `settings.toml`), the workspace's (`.openidea/settings.toml`), and whether the workspace
/// is trusted (an untrusted one can only turn skills off).
#[derive(Clone, Debug, Default)]
pub struct SkillsPolicy {
pub user: BTreeMap<String, AgentSkillPolicy>,
pub workspace: BTreeMap<String, AgentSkillPolicy>,
pub workspace_trusted: bool,
}
/// Returns the skill policies for this project.
pub type SkillsPolicyFn = dyn Fn() -> SkillsPolicy + Send + Sync;
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
struct CopilotBinaryKey {
command: String,
@@ -156,6 +169,7 @@ 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,
}
@@ -528,6 +542,8 @@ struct Task {
idle_epoch: AtomicU64,
/// Turned on when per-session MCP overrides changed while a turn was busy; dropped once idle.
mcp_reload_pending: AtomicBool,
/// Turned on when per-session skill overrides changed while a turn was busy; dropped once idle.
skills_reload_pending: AtomicBool,
/// Settings already sent this session (`(option, value)`), so a refusal is not retried.
config_sent: Mutex<HashSet<(String, String)>>,
dirty: Mutex<BTreeSet<(Session, usize)>>,
@@ -575,6 +591,7 @@ impl AgentManager {
idle_release_ms: AtomicU64::new(IDLE_RELEASE.as_millis() as u64),
mcp_servers_hook: RwLock::new(None),
mcp_executable_hook: RwLock::new(None),
skills_policy_hook: RwLock::new(None),
attention_seq: AtomicU64::new(0),
});
shared.paths.catalogs.subscribe(&shared);
@@ -724,10 +741,15 @@ impl AgentManager {
*self.shared.mcp_executable_hook.write() = Some(Arc::from(hook));
}
/// Provides the user and workspace skill policies and the workspace's trust.
pub fn set_skills_policy_hook(&self, hook: Box<SkillsPolicyFn>) {
*self.shared.skills_policy_hook.write() = Some(Arc::from(hook));
}
/// The slash commands to complete for `provider`, in `task`'s directory or (without one)
/// in the project: what the agent offered last time there, unadvertised builtins,
/// and, for Claude Code, skills and custom commands on disk it has not listed (for Hermes,
/// its profile's skills).
/// for Claude Code the skills and custom commands on disk it has not listed (for
/// Hermes, its profile's skills), and the skills hub's active skills for every agent.
pub async fn commands(&self, provider: &str, task: Option<&str>) -> IdeResult<Vec<AgentCommand>> {
let (provider, offered, cwd) = match task {
Some(id) => {
@@ -770,11 +792,44 @@ impl AgentManager {
.await?;
return Ok(skills::merge(offered, found));
}
if provider != "claude" && provider != "claude-acp" {
return Ok(offered);
if provider == "claude" || provider == "claude-acp" {
let claude_cwd = cwd.clone();
let found = blocking(move || Ok(skills::discover(&claude_cwd, home.as_deref()))).await?;
offered = skills::merge(offered, found);
}
let found = blocking(move || Ok(skills::discover(&cwd, home.as_deref()))).await?;
Ok(skills::merge(offered, found))
// The hub's active skills complete on every agent; its `off` ones drop out here,
// which is all the enforcement an ACP agent gets.
let holder = self.task_for_commands(&provider, task);
let states = match holder {
Some(holder) => holder.skill_states().await,
None => {
let (policy, root) = {
let shared = &self.shared;
let policy = shared.skills_policy_hook.read().as_ref().map(|hook| hook()).unwrap_or_default();
(policy, shared.paths.project_root.clone())
};
let home = self.shared.paths.home_dir.clone();
blocking(move || {
Ok(skills::resolve(
skills::discover_skills(&root, home.as_deref()),
None,
&policy.workspace,
&policy.user,
policy.workspace_trusted,
))
})
.await
.unwrap_or_default()
}
};
Ok(skills::menu_commands(offered, &states))
}
/// The task to resolve skills for, when the commands are for one and its provider matches.
fn task_for_commands(&self, provider: &str, task: Option<&str>) -> Option<Arc<Task>> {
let task = self.task(task?).ok()?;
let matches = task.state.lock().task.provider == provider;
matches.then_some(task)
}
fn task(&self, id: &str) -> IdeResult<Arc<Task>> {
@@ -858,6 +913,7 @@ impl AgentManager {
retry: None,
background: Box::default(),
mcp_overrides: BTreeMap::new(),
skill_overrides: BTreeMap::new(),
stats: Box::default(),
};
let file = TaskFile {
@@ -976,6 +1032,7 @@ impl AgentManager {
retry: None,
background: Box::default(),
mcp_overrides: req.mcp_overrides,
skill_overrides: req.skill_overrides,
stats: Box::default(),
};
let file = TaskFile {
@@ -1319,13 +1376,14 @@ impl AgentManager {
(s.task.cwd.0.clone(), s.task.provider.clone(), s.task.mcp_overrides.clone())
};
let mcp_servers = source.shared.mcp_servers_for_session(&provider_id, &live.init, &mcp_overrides);
let skills_delivery = source.stage_skills(stage_key(live.driver), &cwd).await;
let cwd_s = dunce::canonicalize(&cwd).unwrap_or(cwd).to_string_lossy().into_owned();
let reply: Value = live
.peer
.request(
"session/fork",
{
let mut params = session_params(&cwd_s, &mcp_servers);
let mut params = session_params(&cwd_s, &mcp_servers, skills_delivery.as_ref());
params["sessionId"] = json!(live.session);
params
},
@@ -1726,6 +1784,7 @@ impl AgentManager {
*task.deleted.lock() = true;
let _ = std::fs::remove_file(self.shared.paths.store_dir.join(format!("{id}.json")));
let _ = std::fs::remove_dir_all(task.turn_dir());
skills::remove_farm(&self.shared.paths.store_dir, id);
let saved = task.state.lock().saved.clone();
if let Some(saved) = saved
&& !self.tasks.read().values().any(|t| t.state.lock().saved.as_ref() == Some(&saved))
@@ -1987,6 +2046,38 @@ impl AgentManager {
Ok(out)
}
/// Sets the session's skill modes; like MCP overrides, a change reaches the agent when
/// its idle session is recycled and the next turn starts fresh.
pub fn set_skill_overrides(&self, id: &str, overrides: BTreeMap<String, AgentSkillMode>) -> IdeResult<AgentTask> {
let task = self.task(id)?;
let cleaned: BTreeMap<String, AgentSkillMode> = overrides
.into_iter()
.filter_map(|(k, v)| (!k.trim().is_empty()).then(|| (k.trim().to_owned(), v)))
.collect();
let (changed, busy, has_bg, out) = {
let mut s = task.state.lock();
if s.task.status == AgentStatus::Archived {
return Err(IdeError::invalid("the task is archived"));
}
let changed = s.task.skill_overrides != cleaned;
if changed {
s.task.skill_overrides = cleaned;
s.task.updated_ms = now_ms();
}
(changed, s.busy, !s.background_tasks.is_empty(), s.task.clone())
};
if changed {
task.persist();
task.emit_task();
if busy || has_bg || !task.permissions.lock().is_empty() {
task.skills_reload_pending.store(true, Ordering::Release);
} else {
task.recycle_resumable_session();
}
}
Ok(out)
}
/// Recycles idle resumable live sessions (or schedules reload after the running turn) when
/// global, workspace, or built-in IDE MCP server settings change.
pub fn notify_mcp_servers_changed(&self) {
@@ -2019,6 +2110,55 @@ impl AgentManager {
}
impl Task {
/// The skills offered in this project: every discovery resolved against the policies
/// and the task's overrides.
async fn skill_states(&self) -> Vec<AgentSkillState> {
let (policy, overrides, home, root) = {
let shared = &self.shared;
let policy = shared.skills_policy_hook.read().as_ref().map(|hook| hook()).unwrap_or_default();
let overrides = self.state.lock().task.skill_overrides.clone();
(policy, overrides, shared.paths.home_dir.clone(), shared.paths.project_root.clone())
};
blocking(move || {
Ok(skills::resolve(
skills::discover_skills(&root, home.as_deref()),
Some(&overrides),
&policy.workspace,
&policy.user,
policy.workspace_trusted,
))
})
.await
.unwrap_or_default()
}
/// Stages the session's skills into the task's farm and reports what its CLI takes.
/// Nothing staged for an ACP agent (its `/` menu is filtered instead), and a failed
/// stage (locked files, full disk) runs the session without the farm.
async fn stage_skills(&self, provider: &str, cwd: &Path) -> Option<skills::Delivery> {
let states = self.skill_states().await;
let (farm, home, out_cwd) = {
(
skills::farm_dir(&self.shared.paths.store_dir, &self.id),
self.shared.paths.home_dir.clone(),
cwd.to_path_buf(),
)
};
let provider = provider.to_owned();
match blocking(move || {
skills::stage(&farm, &provider, &states, &out_cwd, home.as_deref())
.map_err(|e| IdeError::internal(e.to_string()))
})
.await
{
Ok(delivery) => Some(delivery),
Err(e) => {
tracing::warn!("agent task {}: staging its skills failed: {e}", self.id);
None
}
}
}
fn restore(file: TaskFile, shared: Arc<Shared>) -> Arc<Self> {
let mut task = file.task;
config::add_client_options(&task.provider, &mut task.config);
@@ -2075,6 +2215,7 @@ impl Task {
turns: AtomicU64::new(0),
idle_epoch: AtomicU64::new(0),
mcp_reload_pending: AtomicBool::new(false),
skills_reload_pending: AtomicBool::new(false),
config_sent: Mutex::new(HashSet::new()),
dirty: Mutex::new(BTreeSet::new()),
streamed: Mutex::new(HashMap::new()),
@@ -2366,7 +2507,8 @@ impl Task {
if stop != "cancelled" {
self.emit_attention(AgentAttentionReason::Finished);
}
if self.mcp_reload_pending.swap(false, Ordering::AcqRel)
if (self.mcp_reload_pending.swap(false, Ordering::AcqRel)
|| self.skills_reload_pending.swap(false, Ordering::AcqRel))
&& self.state.lock().background_tasks.is_empty()
{
self.recycle_resumable_session();
@@ -2884,6 +3026,7 @@ impl Task {
let (capabilities, embedded) = capabilities_of(&init);
let mcp_overrides = self.state.lock().task.mcp_overrides.clone();
let mcp_servers = self.shared.mcp_servers_for_session(provider_id, &init, &mcp_overrides);
let skills_delivery = self.stage_skills(stage_key(spec.driver), cwd).await;
// Agents that compare canonical paths fail in a symlinked directory (macOS `/tmp`).
let cwd_s = dunce::canonicalize(cwd).unwrap_or_else(|_| cwd.to_path_buf()).to_string_lossy().into_owned();
@@ -2898,7 +3041,7 @@ impl Task {
}
if let (Some(id), true, false) = (saved, can_load, start_fresh) {
self.replaying.store(true, Ordering::Release);
let mut params = session_params(&cwd_s, &mcp_servers);
let mut params = session_params(&cwd_s, &mcp_servers, skills_delivery.as_ref());
params["sessionId"] = json!(&id);
let loaded = self.request_with_auth(&peer, &init, &mut tried_auth, "session/load", params).await;
tokio::time::sleep(REPLAY_GRACE).await;
@@ -2938,7 +3081,7 @@ impl Task {
let (session_id, result) = match session {
Some(s) => s,
None => {
let params = session_params(&cwd_s, &mcp_servers);
let params = session_params(&cwd_s, &mcp_servers, skills_delivery.as_ref());
let v = self.request_with_auth(&peer, &init, &mut tried_auth, "session/new", params).await.map_err(
|e| match self.sign_in_error(&e, Some(&sign_in_message)) {
Some(msg) => SessionOpenError { message: msg, allow_acp_fallback: false },
@@ -3914,13 +4057,34 @@ struct McpForSession {
off: Vec<String>,
}
/// The driver a session's staged skills are staged for (`skills::stage` matches on it):
/// the native CLIs take the farm, everything else (an ACP agent) gets the `/` menu filter.
fn stage_key(driver: provider::Driver) -> &'static str {
match driver {
provider::Driver::Claude => "claude",
provider::Driver::Codex => "codex",
provider::Driver::Copilot => "copilot",
provider::Driver::Acp => "acp",
}
}
/// The session parameters `session/new`, `session/load` and `session/fork` share: the MCP
/// servers, and the ones off for this session, so an agent that also loads its own
/// configuration (Claude Code) can keep a same-named server of it off too.
fn session_params(cwd: &str, mcp: &McpForSession) -> Value {
/// configuration (Claude Code) can keep a same-named server of it off too — plus the
/// session's staged skills for the drivers that take them.
fn session_params(cwd: &str, mcp: &McpForSession, skills: Option<&skills::Delivery>) -> Value {
let mut params = json!({ "cwd": cwd, "mcpServers": mcp.servers });
let mut meta = json!({});
if !mcp.off.is_empty() {
params["_meta"] = json!({ "openidea": { "mcpServersOff": mcp.off } });
meta["mcpServersOff"] = json!(mcp.off);
}
if let Some(skills) = skills
&& let Ok(v) = serde_json::to_value(skills)
{
meta["skills"] = v;
}
if !meta.is_null() && meta.as_object().is_some_and(|m| !m.is_empty()) {
params["_meta"] = json!({ "openidea": meta });
}
params
}
+84
Переглянути файл
@@ -110,6 +110,9 @@ pub struct AgentTask {
/// Per-session MCP server enable/disable overrides (`server_name` -> `enabled`), including `"openidea"`.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub mcp_overrides: BTreeMap<String, bool>,
/// Per-session skill modes (`skill name` -> mode), on top of the settings' policies.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub skill_overrides: BTreeMap<String, AgentSkillMode>,
/// Token counts of the last turn and context compressions, when the agent reports them.
// Boxed so that `AgentEvent::Task` stays within clippy's `large_enum_variant` bound on Windows.
#[serde(default)]
@@ -687,6 +690,9 @@ pub struct NewAgentTask {
/// Per-session MCP server enable/disable overrides (`server_name` -> `enabled`).
#[serde(default)]
pub mcp_overrides: BTreeMap<String, bool>,
/// Per-session skill modes (`skill name` -> mode).
#[serde(default)]
pub skill_overrides: BTreeMap<String, AgentSkillMode>,
/// Creates the task without sending `prompt` (it only names the task): the composer's
/// `!` command runs in it first.
#[serde(default)]
@@ -879,6 +885,84 @@ fn default_true() -> bool {
true
}
pub use ide_core::settings::{AgentSkillMode, AgentSkillPolicy};
/// Which CLI's own folders a skill was discovered in (Settings › Agents › Skills groups by it).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentSkillSource {
/// The project's `.agents/skills` and `.openidea/skills`.
#[default]
Workspace,
/// The user's `~/.agents/skills` (what `npx skills add` fills).
User,
/// The project's `.claude/skills`.
ClaudeWorkspace,
/// `~/.claude/skills`.
ClaudeUser,
/// The project's `.github/skills` (Copilot's repository skills).
GithubWorkspace,
/// `~/.copilot/skills` and `~/.copilot/installed-plugins/*`.
CopilotUser,
/// The project's `.codex/skills`.
CodexWorkspace,
/// `~/.codex/skills`.
CodexUser,
/// The project's `.cursor/skills`.
CursorWorkspace,
/// `~/.cursor/skills`.
CursorUser,
}
impl AgentSkillSource {
/// Whether skills of this source are only read, never delivered by OpenIDEA: the CLI
/// discovers them itself, so "off" holds only where the CLI supports a native disable.
pub fn discovered(&self) -> bool {
!matches!(self, Self::Workspace | Self::User)
}
}
/// One discovered skill: a folder with a `SKILL.md`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentSkill {
/// The frontmatter `name`, else the folder's name.
pub name: String,
pub description: String,
/// Canonical folder holding `SKILL.md` (symlinks resolved, so duplicates collapse).
pub path: IpcPath,
pub source: AgentSkillSource,
/// The `SKILL.md` passes validation (`name` matches its folder, `description` present).
pub valid: bool,
/// What validation found (`name` mismatch, missing or over-long description…).
pub warnings: Vec<String>,
}
/// A skill as Settings › Agents › Skills shows it: discovery plus the effective mode and
/// which layer decided it.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentSkillState {
pub skill: AgentSkill,
pub mode: AgentSkillMode,
/// What set `mode`: a session override, the workspace, the user's settings, workspace
/// trust, or nothing (the default `auto`).
pub origin: AgentSkillOrigin,
}
/// Which layer decided a skill's [`AgentSkillState::mode`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentSkillOrigin {
#[default]
None,
Session,
Workspace,
User,
/// An untrusted workspace's skills and policies may only turn skills off.
Trust,
}
/// An external MCP configuration file discovered on disk (user CLI config or workspace file).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
+15
Переглянути файл
@@ -172,6 +172,10 @@ struct Session {
mcp_config: Option<tempfile::TempPath>,
/// MCP servers switched off for this session (`--disallowedTools`), its own config's too.
mcp_off: Vec<String>,
/// The staged skills folder passed as `--add-dir` (its `.claude/skills` holds the copies).
skills_add_dir: Option<PathBuf>,
/// The staged skills' `--settings` JSON (`skillOverrides` for the native ones too).
skills_settings: Option<String>,
shim: Weak<Shim>,
st: Mutex<State>,
/// Serializes (re)starting the process.
@@ -356,10 +360,13 @@ impl Shim {
None
}
});
let skills = params.pointer("/_meta/openidea/skills");
let session = Arc::new(Session {
id: id.to_owned(),
mcp_config,
mcp_off,
skills_add_dir: skills.and_then(|s| s.get("claudeAddDir")).and_then(Value::as_str).map(PathBuf::from),
skills_settings: skills.and_then(|s| s.get("claudeSettings")).and_then(Value::as_str).map(str::to_owned),
shim: Arc::downgrade(self),
st: Mutex::new(State {
proc: None,
@@ -673,6 +680,14 @@ impl Session {
if !self.mcp_off.is_empty() {
args.extend(["--disallowedTools".to_owned(), self.mcp_off.join(",")]);
}
// The staged skills: `.claude/skills` of the added directory is discovered like the
// project's own, and the settings hold the modes of the skills it sees natively too.
if let Some(dir) = &self.skills_add_dir {
args.extend(["--add-dir".to_owned(), dir.to_string_lossy().into_owned()]);
}
if let Some(settings) = &self.skills_settings {
args.extend(["--settings".to_owned(), settings.clone()]);
}
args.extend(start.args());
let launch =
Launch { program: shim.config.program.clone(), args, cwd: self.cwd.clone(), env: shim.config.env.clone() };
+56 -9
Переглянути файл
@@ -334,6 +334,31 @@ fn str_param<'a>(params: &'a Value, key: &str) -> Result<&'a str, ResponseError>
params.get(key).and_then(Value::as_str).ok_or_else(|| invalid(format!("missing {key}")))
}
/// Fills a `thread/start`/`thread/resume`/`thread/fork` request's `config` with the session's
/// MCP servers and its staged skills: the off ones, by path (`skills.config` entries with
/// `enabled = false`, which the CLI honors for the copies it discovers natively too).
fn apply_thread_config(params: &Value, request: &mut Value) {
let mut config = translate::mcp_config(params).unwrap_or_else(|| json!({}));
let off: Vec<Value> = params
.pointer("/_meta/openidea/skills/codexOff")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(|entry| {
let path = entry.get(1)?.as_str()?;
Some(json!({ "path": path, "enabled": false }))
})
.collect();
if !off.is_empty()
&& let Some(map) = config.as_object_mut()
{
map.insert("skills".into(), json!({ "config": off }));
}
if !config.as_object().is_some_and(|m| m.is_empty()) {
request["config"] = config;
}
}
impl CodexShim {
fn codex(&self) -> &Peer {
self.codex.get().expect("attached before any message")
@@ -414,6 +439,31 @@ impl CodexShim {
}
}
/// Hands the session's staged skills to the app-server: the farm's `codex` tree joins
/// its discovery roots. Best-effort: a CLI version without `skills/extraRoots/set`
/// (the method arrived later than some pinned installs) runs without the farm, as
/// before.
async fn apply_skill_roots(&self, session: &str, params: &Value) {
let roots = params
.pointer("/_meta/openidea/skills/codexExtraRoots")
.and_then(Value::as_array)
.map(|a| a.iter().filter_map(Value::as_str).collect::<Vec<_>>())
.unwrap_or_default();
if roots.is_empty() {
return;
}
let set = tokio::time::timeout(
Duration::from_secs(5),
self.call("skills/extraRoots/set", json!({ "extraRoots": roots })),
)
.await;
match set {
Ok(Ok(_)) => {}
Ok(Err(e)) => tracing::info!("codex session {session}: could not set the extra skill roots: {}", e.message),
Err(e) => tracing::info!("codex session {session}: could not set the extra skill roots: {e}"),
}
}
/// Registers a thread codex opened for a session of its own; returns its `configOptions`.
fn open_thread(&self, result: &Value, models: &[ModelInfo], settings: Option<Settings>) -> (String, Value) {
let thread = result.get("thread").unwrap_or(&Value::Null);
@@ -434,14 +484,13 @@ impl CodexShim {
let models = self.models().await?;
self.prepare_project_trust(params).await;
let mut request = json!({ "cwd": params.get("cwd") });
if let Some(config) = translate::mcp_config(params) {
request["config"] = config;
}
apply_thread_config(params, &mut request);
let result = self.call("thread/start", request).await?;
let (id, options) = self.open_thread(&result, &models, None);
if id.is_empty() {
return Err(error(codes::INTERNAL_ERROR, "codex started no thread"));
}
self.apply_skill_roots(&id, params).await;
self.publish_skills(&id).await;
Ok(json!({ "sessionId": id, "configOptions": options }))
}
@@ -452,9 +501,7 @@ impl CodexShim {
let models = self.models().await?;
self.prepare_project_trust(params).await;
let mut request = json!({ "threadId": id, "cwd": params.get("cwd") });
if let Some(config) = translate::mcp_config(params) {
request["config"] = config;
}
apply_thread_config(params, &mut request);
let result = self.call("thread/resume", request).await?;
let (_, options) = self.open_thread(&result, &models, None);
let cwd = self.state.lock().threads.get(id).and_then(|t| t.cwd.clone());
@@ -462,6 +509,7 @@ impl CodexShim {
for update in translate::history(thread, cwd.as_deref()) {
self.emit(id, update);
}
self.apply_skill_roots(id, params).await;
self.publish_skills(id).await;
Ok(json!({ "configOptions": options }))
}
@@ -472,9 +520,7 @@ impl CodexShim {
self.prepare_project_trust(params).await;
let settings = self.state.lock().threads.get(source).and_then(|t| t.settings.clone());
let mut request = json!({ "threadId": source, "cwd": params.get("cwd") });
if let Some(config) = translate::mcp_config(params) {
request["config"] = config;
}
apply_thread_config(params, &mut request);
if let Some(s) = &settings {
request["model"] = json!(s.model_slug(&models));
request["approvalPolicy"] = json!(s.mode.approval_policy());
@@ -482,6 +528,7 @@ impl CodexShim {
}
let result = self.call("thread/fork", request).await?;
let (id, options) = self.open_thread(&result, &models, settings);
self.apply_skill_roots(&id, params).await;
self.publish_skills(&id).await;
Ok(json!({ "sessionId": id, "configOptions": options }))
}
+20
Переглянути файл
@@ -372,6 +372,24 @@ fn error(code: i64, message: impl Into<String>) -> ResponseError {
ResponseError { code, message: message.into(), data: None }
}
/// Adds the session's staged skills to a `session.create`/`session.resume` request:
/// `skillDirectories` (the farm's `copilot` tree) and `disabledSkills` (the off and
/// slash-only ones; Copilot invokes skills with the model only, so a slash-only skill has
/// no other switch here).
fn apply_skills(params: &Value, req: &mut Value) {
let skills = params.pointer("/_meta/openidea/skills");
if let Some(dirs) = skills.and_then(|s| s.get("copilotSkillDirectories")).and_then(Value::as_array)
&& !dirs.is_empty()
{
req["skillDirectories"] = json!(dirs.iter().filter_map(Value::as_str).collect::<Vec<_>>());
}
if let Some(disabled) = skills.and_then(|s| s.get("copilotDisabledSkills")).and_then(Value::as_array)
&& !disabled.is_empty()
{
req["disabledSkills"] = json!(disabled.iter().filter_map(Value::as_str).collect::<Vec<_>>());
}
}
fn invalid(message: impl Into<String>) -> ResponseError {
error(codes::INVALID_PARAMS, message)
}
@@ -496,6 +514,7 @@ impl CopilotShim {
if let Some(disabled) = translate::wire_disabled_mcp_servers(params) {
req["disabledMcpServers"] = disabled;
}
apply_skills(params, &mut req);
let created = self.call("session.create", req).await?;
let session_id = created
@@ -546,6 +565,7 @@ impl CopilotShim {
if let Some(disabled) = translate::wire_disabled_mcp_servers(params) {
req["disabledMcpServers"] = disabled;
}
apply_skills(params, &mut req);
let resumed = self.call("session.resume", req).await?;
if let Ok(current) = self.call("session.model.getCurrent", json!({ "sessionId": session_id })).await {
+604 -7
Переглянути файл
@@ -1,11 +1,17 @@
//! Claude Code's slash commands on disk, for completion before (or without) a session:
//! skills (`.claude/skills/<dir>/SKILL.md`) and custom commands (`.claude/commands/**/*.md`)
//! of the working directory and every directory above it, then the user's `~/.claude`; and
//! the skills of a Hermes profile (`<profile>/skills`).
//! Slash commands and skills on disk. Claude Code's own discovery (`.claude/skills` and
//! `.claude/commands` of the working directory tree and `~/.claude`, and a Hermes profile's
//! `skills`) for completion before (or without) a session, plus the multi-level skills hub
//! of #3897: every CLI's skill folders discovered once, deduplicated by canonical path,
//! resolved against the `[agents.skills.<name>]` policies of the global and workspace
//! settings, and staged into a per-session folder the CLIs each receive their own way.
use crate::{AgentCommand, AgentCommandSource};
use std::collections::HashSet;
use std::path::Path;
use crate::{
AgentCommand, AgentCommandSource, AgentSkill, AgentSkillMode, AgentSkillOrigin, AgentSkillPolicy, AgentSkillSource,
AgentSkillState,
};
use ide_core::output_encoding::strip_ansi;
use std::collections::{BTreeMap, HashSet};
use std::path::{Path, PathBuf};
const MAX_DESCRIPTION: usize = 200;
/// Command directories nest this deep at most (`a/b/c.md` → `a:b:c`).
@@ -200,6 +206,370 @@ fn truncate(s: &str) -> String {
}
}
// ─── The skills hub (#3897): discovery, policy, delivery ────────────────────────────
/// A skill's `name` must be this and lowercase letters, digits and hyphens only.
fn valid_name(name: &str) -> bool {
(1..=64).contains(&name.len()) && name.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
}
/// A `SKILL.md`'s description is at most this many characters.
const MAX_SKILL_DESCRIPTION: usize = 1024;
/// The workspace folders skills are discovered in, by the source they report.
const WORKSPACE_ROOTS: &[(&str, AgentSkillSource)] = &[
(".agents/skills", AgentSkillSource::Workspace),
(".openidea/skills", AgentSkillSource::Workspace),
(".claude/skills", AgentSkillSource::ClaudeWorkspace),
(".github/skills", AgentSkillSource::GithubWorkspace),
(".codex/skills", AgentSkillSource::CodexWorkspace),
(".cursor/skills", AgentSkillSource::CursorWorkspace),
];
/// The home folders skills are discovered in, by the source they report.
const HOME_ROOTS: &[(&str, AgentSkillSource)] = &[
(".agents/skills", AgentSkillSource::User),
(".claude/skills", AgentSkillSource::ClaudeUser),
(".copilot/skills", AgentSkillSource::CopilotUser),
(".codex/skills", AgentSkillSource::CodexUser),
(".cursor/skills", AgentSkillSource::CursorUser),
];
/// Every skill found under `workspace` (a project, scanned even for a worktree task, whose
/// checkout lacks untracked skills) and `home`, in source precedence order, symlinked
/// duplicates collapsed by canonical path: the first of a path wins, and so does the first
/// of a name (the higher source), so a session never sees one skill twice.
pub fn discover_skills(workspace: &Path, home: Option<&Path>) -> Vec<AgentSkill> {
let mut out: Vec<AgentSkill> = Vec::new();
let mut seen_paths: HashSet<PathBuf> = HashSet::new();
let mut seen_names: HashSet<String> = HashSet::new();
let mut roots: Vec<(PathBuf, AgentSkillSource)> = Vec::new();
roots.extend(WORKSPACE_ROOTS.iter().map(|(rel, source)| (workspace.join(rel), *source)));
let mut plugin_roots = Vec::new();
if let Some(home) = home {
roots.extend(HOME_ROOTS.iter().map(|(rel, source)| (home.join(rel), *source)));
// `copilot install` unpacks plugins under `installed-plugins/<plugin>/`, whose skills
// sit in a `skills` folder (or directly in the plugin folder).
let plugins = home.join(".copilot/installed-plugins");
if let Ok(plugins) = plugins.read_dir() {
for plugin in plugins.flatten() {
if plugin.path().is_dir() {
plugin_roots.push((plugin.path().join("skills"), AgentSkillSource::CopilotUser));
plugin_roots.push((plugin.path(), AgentSkillSource::CopilotUser));
}
}
}
}
roots.extend(plugin_roots);
for (root, source) in roots {
for skill in skills_of(&root, source) {
let path = dunce::canonicalize(&skill.path.0).unwrap_or_else(|_| skill.path.0.clone());
if !seen_paths.insert(path.clone()) || !seen_names.insert(skill.name.clone()) {
continue;
}
out.push(AgentSkill { path: path.into(), ..skill });
}
}
out
}
/// The skills of one root: `<name>/SKILL.md` folders, validated.
fn skills_of(root: &Path, source: AgentSkillSource) -> Vec<AgentSkill> {
let mut out: Vec<AgentSkill> = Vec::new();
let Ok(entries) = std::fs::read_dir(root) else { return out };
for entry in entries.flatten() {
let dir = entry.path();
let Some(folder) = dir.file_name().and_then(|n| n.to_str()).map(str::to_owned) else { continue };
if !dir.is_dir() || folder.starts_with('.') {
continue;
}
let Ok(text) = std::fs::read_to_string(dir.join("SKILL.md")) else { continue };
let meta = Frontmatter::parse(&text);
let name = meta.get("name").filter(|n| !n.is_empty()).map(str::to_owned).unwrap_or_else(|| folder.clone());
let mut warnings = Vec::new();
if !valid_name(&name) {
warnings.push(format!("`name: {name}` is not 1-64 lowercase letters, digits or hyphens"));
}
if name != folder {
warnings.push(format!("`name: {name}` does not match the folder `{folder}`"));
}
let description = meta.get("description").unwrap_or_default();
let description = strip_ansi(description).trim().to_owned();
if description.is_empty() {
warnings.push("no `description`: the model never sees when to use it".into());
} else if description.chars().count() > MAX_SKILL_DESCRIPTION {
warnings.push(format!("`description` is over {MAX_SKILL_DESCRIPTION} characters"));
}
out.push(AgentSkill {
name,
description: truncate(&description),
path: dir.into(),
source,
valid: warnings.is_empty(),
warnings,
});
}
out.sort_by(|a, b| a.name.cmp(&b.name));
out
}
/// A skill's mode, as one policy layer of the settings has it.
type Policies = BTreeMap<String, AgentSkillPolicy>;
/// Resolves every skill's mode: a session override, then the workspace's and the user's
/// `[agents.skills.<name>]` policy, then the default `auto` — with an untrusted workspace
/// able to turn skills off only: its own skills stay off (whatever the session chose), and
/// its policies hold only when they turn a skill off.
pub fn resolve(
skills: Vec<AgentSkill>,
session: Option<&BTreeMap<String, AgentSkillMode>>,
workspace: &Policies,
user: &Policies,
workspace_trusted: bool,
) -> Vec<AgentSkillState> {
let mut out = Vec::new();
for skill in skills {
let workspace_skill = matches!(
skill.source,
AgentSkillSource::Workspace
| AgentSkillSource::ClaudeWorkspace
| AgentSkillSource::GithubWorkspace
| AgentSkillSource::CodexWorkspace
| AgentSkillSource::CursorWorkspace
);
let (mode, origin) = if workspace_skill && !workspace_trusted {
// Workspace trust gates the workspace's own skills, whatever else says.
(AgentSkillMode::Off, AgentSkillOrigin::Trust)
} else if let Some(chosen) = session.and_then(|s| s.get(&skill.name)) {
(*chosen, AgentSkillOrigin::Session)
} else if let Some(policy) =
workspace.get(&skill.name).filter(|p| workspace_trusted || p.mode == AgentSkillMode::Off)
{
(policy.mode, AgentSkillOrigin::Workspace)
} else if let Some(policy) = user.get(&skill.name) {
(policy.mode, AgentSkillOrigin::User)
} else {
(AgentSkillMode::Auto, AgentSkillOrigin::None)
};
out.push(AgentSkillState { skill, mode, origin });
}
out
}
/// What one CLI session receives for its active skills. Sent to the shims in
/// `session/new`'s `_meta.openidea.skills`, so each driver applies its own fields.
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub struct Delivery {
/// Claude Code: the farm passed as `--add-dir` (its `.claude/skills` holds the staged copies).
#[serde(skip_serializing_if = "Option::is_none")]
pub claude_add_dir: Option<PathBuf>,
/// Claude Code: the `--settings` JSON with `skillOverrides` (the native skills too).
#[serde(skip_serializing_if = "Option::is_none")]
pub claude_settings: Option<String>,
/// Copilot: `skillDirectories` (the farm's `copilot` tree).
#[serde(skip_serializing_if = "Vec::is_empty")]
pub copilot_skill_directories: Vec<String>,
/// Copilot: `disabledSkills`, spelled as the skills are.
#[serde(skip_serializing_if = "Vec::is_empty")]
pub copilot_disabled_skills: Vec<String>,
/// Codex: `skills/extraRoots/set` roots (the farm's `codex` tree).
#[serde(skip_serializing_if = "Vec::is_empty")]
pub codex_extra_roots: Vec<String>,
/// Codex: `skills.config` entries turning skills off by path.
#[serde(skip_serializing_if = "Vec::is_empty")]
pub codex_off: Vec<(String, String)>,
}
/// Stages the skills a session of `provider` runs with into `farm` — linking (copying on
/// Windows, where directory symlinks need Developer Mode) every active skill folder into
/// the CLI's tree — and reports what to hand the CLI. Skills the CLI discovers natively
/// (its own folders of the working directory and the home) are not staged again: it already
/// sees them, and seeing both would list one skill twice. Skills `off` are never staged;
/// the CLI's native disable (where it has one) receives their names or paths. An ACP
/// agent gets nothing here: its `/` menu is filtered instead.
pub fn stage(
farm: &Path,
provider: &str,
states: &[AgentSkillState],
cwd: &Path,
home: Option<&Path>,
) -> std::io::Result<Delivery> {
let mut out = Delivery::default();
let cwd = dunce::canonicalize(cwd).unwrap_or_else(|_| cwd.to_path_buf());
// Only the native drivers take the farm, each its own tree; `provider` is their key
// (`claude`, `copilot`, `codex`), anything else (an ACP agent) gets the `/` menu filter.
let (claude_tree, copilot_tree, codex_tree) = match provider {
"claude" => (Some(farm.join(".claude/skills")), None, None),
"copilot" => (None, Some(farm.join("copilot")), None),
"codex" => (None, None, Some(farm.join("codex"))),
_ => return Ok(out),
};
// Restage from scratch: a skill turned off or deleted since the last session must not
// linger in the tree. Removing a tree removes its links, never the skills they point at.
for tree in [&claude_tree, &copilot_tree, &codex_tree].into_iter().flatten() {
match std::fs::remove_dir_all(tree) {
Err(e) if e.kind() != std::io::ErrorKind::NotFound => return Err(e),
_ => {}
}
}
for state in states {
let name = state.skill.name.as_str();
let path = state.skill.path.0.as_path();
match state.mode {
AgentSkillMode::Off => {
out.codex_off.push((name.to_owned(), state.skill.path.to_string_lossy().into_owned()));
}
// Claude Code runs a slash-only skill on `/name`, so it has to see the folder;
// Copilot and Codex have no such mode and get it disabled or left out.
AgentSkillMode::SlashOnly => {
if let Some(tree) = claude_tree.as_ref().filter(|_| !native_claude(&state.skill, &cwd, home)) {
link_skill(&tree.join(name), path)?;
}
}
AgentSkillMode::Auto => {
if let Some(tree) = claude_tree.as_ref().filter(|_| !native_claude(&state.skill, &cwd, home)) {
link_skill(&tree.join(name), path)?;
}
if let Some(tree) = copilot_tree.as_ref().filter(|_| !native_copilot(&state.skill, &cwd, home)) {
link_skill(&tree.join(name), path)?;
}
if let Some(tree) = codex_tree.as_ref().filter(|_| !native_codex(&state.skill, &cwd, home)) {
link_skill(&tree.join(name), path)?;
}
}
}
}
if claude_tree.as_ref().is_some_and(|t| t.exists()) {
out.claude_add_dir = Some(farm.to_path_buf());
}
if let Some(tree) = copilot_tree.as_ref().filter(|t| t.exists()) {
out.copilot_skill_directories.push(tree.to_string_lossy().into_owned());
}
if let Some(tree) = codex_tree.as_ref().filter(|t| t.exists()) {
out.codex_extra_roots.push(tree.to_string_lossy().into_owned());
}
// Claude Code's `skillOverrides` and Copilot's `disabledSkills` take the names of the
// off and slash-only skills — the native copies included.
let off: Vec<&str> =
states.iter().filter(|s| s.mode == AgentSkillMode::Off).map(|s| s.skill.name.as_str()).collect();
let slash: Vec<&str> =
states.iter().filter(|s| s.mode == AgentSkillMode::SlashOnly).map(|s| s.skill.name.as_str()).collect();
if !off.is_empty() || !slash.is_empty() {
let mut overrides = serde_json::Map::new();
for (name, mode) in off.iter().map(|n| (*n, "off")).chain(slash.iter().map(|n| (*n, "user-invocable-only"))) {
overrides.insert(name.to_owned(), serde_json::Value::String(mode.to_owned()));
}
out.claude_settings = Some(
serde_json::to_string(&serde_json::json!({ "skillOverrides": overrides })).expect("settings serialize"),
);
out.copilot_disabled_skills = off.iter().chain(slash.iter()).map(|n| (*n).to_owned()).collect();
out.copilot_disabled_skills.sort();
}
Ok(out)
}
/// Claude Code sees this skill without the farm: its own `.claude/skills` of the working
/// directory (a worktree lacks the untracked originals) or the home.
fn native_claude(skill: &AgentSkill, cwd: &Path, home: Option<&Path>) -> bool {
match skill.source {
AgentSkillSource::ClaudeWorkspace => is_under(skill.path.0.as_path(), cwd),
AgentSkillSource::ClaudeUser => home.is_some_and(|h| is_under(skill.path.0.as_path(), &h.join(".claude"))),
_ => false,
}
}
/// Copilot reads the repository's `.github/skills` and the home's `.copilot` itself.
fn native_copilot(skill: &AgentSkill, cwd: &Path, home: Option<&Path>) -> bool {
match skill.source {
AgentSkillSource::GithubWorkspace => is_under(skill.path.0.as_path(), cwd),
AgentSkillSource::CopilotUser => home.is_some_and(|h| is_under(skill.path.0.as_path(), &h.join(".copilot"))),
_ => false,
}
}
/// Codex reads its own folders itself.
fn native_codex(skill: &AgentSkill, cwd: &Path, home: Option<&Path>) -> bool {
match skill.source {
AgentSkillSource::CodexWorkspace => is_under(skill.path.0.as_path(), cwd),
AgentSkillSource::CodexUser => home.is_some_and(|h| is_under(skill.path.0.as_path(), &h.join(".codex"))),
_ => false,
}
}
fn is_under(path: &Path, root: &Path) -> bool {
path.starts_with(root)
}
/// Puts `name` into the farm tree: a directory symlink where they work, a copy otherwise
/// (Windows needs Developer Mode for directory symlinks).
fn link_skill(link: &Path, target: &Path) -> std::io::Result<()> {
let _ = std::fs::remove_file(link);
if let Some(parent) = link.parent() {
std::fs::create_dir_all(parent)?;
}
#[cfg(unix)]
{
std::os::unix::fs::symlink(target, link)
}
#[cfg(windows)]
{
copy_dir_all(target, link)
}
}
#[cfg(windows)]
fn copy_dir_all(from: &Path, to: &Path) -> std::io::Result<()> {
std::fs::create_dir_all(to)?;
for entry in std::fs::read_dir(from)?.flatten() {
let path = entry.path();
let dest = to.join(entry.file_name());
if path.is_dir() {
copy_dir_all(&path, &dest)?;
} else {
std::fs::copy(&path, &dest)?;
}
}
Ok(())
}
/// Removes a task's farm (task deleted or archived); missing is fine.
pub fn remove_farm(store_dir: &Path, task: &str) {
let farm = farm_dir(store_dir, task);
match std::fs::remove_dir_all(&farm) {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => tracing::warn!("removing the session skills folder {}: {e}", farm.display()),
}
}
/// Where a task's staged skills live.
pub fn farm_dir(store_dir: &Path, task: &str) -> PathBuf {
store_dir.join("session-skills").join(sanitized(task))
}
/// A task id is a uuid, but never trust it with a path segment.
fn sanitized(id: &str) -> String {
id.chars().filter(|c| c.is_ascii_alphanumeric() || *c == '-').collect()
}
/// The `/` menu's skills: the active ones as commands (the agent's own listing wins on a
/// name clash). `Off` ones drop out everywhere; an ACP agent gets no other enforcement, so
/// `slashOnly` ones stay listed — there is nothing to hold them back with.
pub fn menu_commands(offered: Vec<AgentCommand>, states: &[AgentSkillState]) -> Vec<AgentCommand> {
let extra = states
.iter()
.filter(|s| s.mode != AgentSkillMode::Off)
.map(|s| AgentCommand {
name: s.skill.name.clone(),
description: s.skill.description.clone(),
hint: None,
source: AgentCommandSource::Skill,
})
.collect();
merge(offered, extra)
}
#[cfg(test)]
mod tests {
use super::*;
@@ -333,4 +703,231 @@ mod tests {
assert_eq!(f.get("name"), Some("quoted"));
assert_eq!(truncate(&"é".repeat(MAX_DESCRIPTION + 5)).chars().count(), MAX_DESCRIPTION + 1);
}
fn skill(name: &str, source: AgentSkillSource, root: &Path) -> AgentSkill {
AgentSkill {
name: name.into(),
description: format!("{name} does things"),
path: root.join(name).into(),
source,
valid: true,
warnings: Vec::new(),
}
}
fn policy(mode: AgentSkillMode) -> Option<AgentSkillPolicy> {
Some(AgentSkillPolicy { mode })
}
#[test]
fn hub_discovery_scans_every_root_and_collapses_symlinks() {
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path().join("home");
let repo = tmp.path().join("work/app");
std::fs::create_dir_all(&repo).unwrap();
write(&repo.join(".agents/skills/dep/SKILL.md"), "---\nname: dep\ndescription: From the standard root\n---\n");
write(&repo.join(".openidea/skills/local/SKILL.md"), "---\nname: local\ndescription: OpenIDEA's own\n---\n");
write(&repo.join(".claude/skills/claudey/SKILL.md"), "---\nname: claudey\ndescription: Claude's\n---\n");
write(&repo.join(".github/skills/gh/SKILL.md"), "---\nname: gh\ndescription: Copilot's repo one\n---\n");
write(
&home.join(".agents/skills/shared/SKILL.md"),
"---\nname: shared\ndescription: From npx skills add\n---\n",
);
write(&home.join(".codex/skills/codexy/SKILL.md"), "---\nname: codexy\ndescription: Codex's\n---\n");
write(&home.join(".cursor/skills/cursory/SKILL.md"), "---\nname: cursory\ndescription: Cursor's\n---\n");
// A symlink to `dep` in the home (the same canonical folder): collapsed.
#[cfg(unix)]
{
std::fs::create_dir_all(home.join(".claude/skills")).unwrap();
std::os::unix::fs::symlink(repo.join(".agents/skills/dep"), home.join(".claude/skills/dep")).unwrap();
}
// Hidden folders and files are not skills.
write(&repo.join(".agents/skills/.stash/SKILL.md"), "---\nname: hidden\ndescription: x\n---\n");
write(&repo.join(".agents/skills/loose.txt"), "not a folder");
// Same name from a lower-precedence source: the workspace one wins.
write(&home.join(".cursor/skills/local/SKILL.md"), "---\nname: local\ndescription: from cursor\n---\n");
let found = discover_skills(&repo, Some(&home));
assert_eq!(
found.iter().map(|s| (s.name.as_str(), s.source)).collect::<Vec<_>>(),
[
("dep", AgentSkillSource::Workspace),
("local", AgentSkillSource::Workspace),
("claudey", AgentSkillSource::ClaudeWorkspace),
("gh", AgentSkillSource::GithubWorkspace),
("shared", AgentSkillSource::User),
("codexy", AgentSkillSource::CodexUser),
("cursory", AgentSkillSource::CursorUser),
],
"symlinks collapse and the first of a name wins"
);
assert!(found.iter().all(|s| s.valid), "{:?}", found.iter().flat_map(|s| &s.warnings).collect::<Vec<_>>());
}
#[test]
fn hub_discovery_validates_and_reports() {
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path().join("app");
std::fs::create_dir_all(&repo).unwrap();
write(&repo.join(".agents/skills/bad-name/SKILL.md"), "---\nname: Bad_Name\ndescription: x\n---\n");
write(&repo.join(".agents/skills/no-desc/SKILL.md"), "---\nname: no-desc\n---\n");
write(
&repo.join(".agents/skills/verbose/SKILL.md"),
&format!("---\nname: verbose\ndescription: {}\n---\n", "x".repeat(MAX_SKILL_DESCRIPTION + 1)),
);
let found = discover_skills(&repo, None);
let by = |n: &str| found.iter().find(|s| s.name == n).unwrap();
assert!(!by("Bad_Name").valid && !by("Bad_Name").warnings.is_empty());
assert!(!by("no-desc").valid && by("no-desc").warnings.len() == 1);
assert!(!by("verbose").valid);
}
#[test]
fn hub_resolution_precedence_and_trust() {
let root = PathBuf::from("/r");
let ws = skill("tdd", AgentSkillSource::Workspace, &root);
let user = skill("lint", AgentSkillSource::User, &root);
let claude = skill("claudey", AgentSkillSource::ClaudeWorkspace, &root);
let session = BTreeMap::from([("tdd".to_owned(), AgentSkillMode::Off)]);
let workspace = BTreeMap::from([
("tdd".to_owned(), policy(AgentSkillMode::SlashOnly).unwrap()),
("lint".to_owned(), policy(AgentSkillMode::Off).unwrap()),
]);
let user_policies = BTreeMap::from([
("lint".to_owned(), policy(AgentSkillMode::SlashOnly).unwrap()),
("claudey".to_owned(), policy(AgentSkillMode::Auto).unwrap()),
]);
// Session > workspace policy > user policy.
let resolved = resolve(vec![ws.clone(), user.clone()], Some(&session), &workspace, &user_policies, true);
assert_eq!((resolved[0].mode, resolved[0].origin), (AgentSkillMode::Off, AgentSkillOrigin::Session));
assert_eq!((resolved[1].mode, resolved[1].origin), (AgentSkillMode::Off, AgentSkillOrigin::Workspace));
// Without a workspace policy the user's applies.
let resolved = resolve(vec![user.clone()], None, &BTreeMap::new(), &user_policies, true);
assert_eq!((resolved[0].mode, resolved[0].origin), (AgentSkillMode::SlashOnly, AgentSkillOrigin::User));
// Untrusted: the workspace's own skills stay off whatever the session chose, its
// policies hold only when they turn a skill off, and user skills keep resolving.
let resolved = resolve(vec![ws, user, claude], Some(&session), &workspace, &user_policies, false);
assert_eq!((resolved[0].mode, resolved[0].origin), (AgentSkillMode::Off, AgentSkillOrigin::Trust));
assert_eq!((resolved[1].mode, resolved[1].origin), (AgentSkillMode::Off, AgentSkillOrigin::Workspace));
assert_eq!((resolved[2].mode, resolved[2].origin), (AgentSkillMode::Off, AgentSkillOrigin::Trust));
}
fn listed(dir: &Path) -> Vec<String> {
let mut names: Vec<String> =
std::fs::read_dir(dir).unwrap().flatten().map(|e| e.file_name().to_string_lossy().into_owned()).collect();
names.sort();
names
}
#[test]
fn hub_staging_hands_each_cli_its_own_tree() {
let tmp = tempfile::tempdir().unwrap();
// Discovery reports canonical paths (macOS's temp folder is a symlink).
let root = dunce::canonicalize(tmp.path()).unwrap();
let home = root.join("home");
let repo = root.join("app");
std::fs::create_dir_all(&repo).unwrap();
// The staged folders must exist: Windows copies them (symlinks need Developer Mode).
for path in [
repo.join(".agents/skills/tdd"),
repo.join(".agents/skills/off"),
repo.join(".github/skills/gh"),
home.join(".agents/skills/lint"),
home.join(".agents/skills/muted"),
home.join(".codex/skills/codexy"),
] {
std::fs::create_dir_all(path).unwrap();
}
let states = resolve(
vec![
skill("tdd", AgentSkillSource::Workspace, &repo.join(".agents/skills")),
skill("gh", AgentSkillSource::GithubWorkspace, &repo.join(".github/skills")),
skill("lint", AgentSkillSource::User, &home.join(".agents/skills")),
skill("codexy", AgentSkillSource::CodexUser, &home.join(".codex/skills")),
skill("muted", AgentSkillSource::User, &home.join(".agents/skills")),
skill("off", AgentSkillSource::Workspace, &repo.join(".agents/skills")),
],
None,
&BTreeMap::from([("muted".to_owned(), policy(AgentSkillMode::SlashOnly).unwrap())]),
&BTreeMap::from([("off".to_owned(), policy(AgentSkillMode::Off).unwrap())]),
true,
);
// Local (non-worktree) session: the project's GitHub skills are Copilot's own.
let farm = farm_dir(&root.join("store"), "task-1");
let delivery = stage(&farm, "claude", &states, &repo, Some(&home)).unwrap();
assert_eq!(delivery.claude_add_dir.as_deref(), Some(farm.as_path()));
let claude_tree = farm.join(".claude/skills");
let staged = listed(&claude_tree);
assert_eq!(
staged,
["codexy", "gh", "lint", "muted", "tdd"],
"everything but the off one: none is native to Claude here, and slash-only needs the folder"
);
let delivery = stage(&farm, "copilot", &states, &repo, Some(&home)).unwrap();
assert_eq!(delivery.copilot_skill_directories, [farm.join("copilot").to_string_lossy().into_owned()]);
assert_eq!(delivery.copilot_disabled_skills, ["muted", "off"]);
let copilot_staged = listed(&farm.join("copilot"));
assert_eq!(copilot_staged, ["codexy", "lint", "tdd"], "`gh` is native to a local Copilot session");
assert_eq!(
delivery.codex_off,
[("off".to_owned(), repo.join(".agents/skills").join("off").to_string_lossy().into_owned())]
);
// A worktree task: the repo's skills are untracked, so nothing is native any more.
let worktree = root.join("wt");
std::fs::create_dir_all(&worktree).unwrap();
let _ = stage(&farm, "copilot", &states, &worktree, Some(&home)).unwrap();
let copilot_staged = listed(&farm.join("copilot"));
assert!(copilot_staged.contains(&"gh".to_string()));
// Slash-only reaches Claude as `user-invocable-only`, off as `off`.
let delivery = stage(&farm, "claude", &states, &repo, Some(&home)).unwrap();
let settings: serde_json::Value = serde_json::from_str(delivery.claude_settings.as_deref().unwrap()).unwrap();
assert_eq!(settings["skillOverrides"]["muted"], "user-invocable-only");
assert_eq!(settings["skillOverrides"]["off"], "off");
// Restaging after a session turned `lint` off drops its link and leaves the skill.
let session = BTreeMap::from([("lint".to_owned(), AgentSkillMode::Off)]);
let restated = resolve(
states.iter().map(|s| s.skill.clone()).collect(),
Some(&session),
&BTreeMap::from([("muted".to_owned(), policy(AgentSkillMode::SlashOnly).unwrap())]),
&BTreeMap::from([("off".to_owned(), policy(AgentSkillMode::Off).unwrap())]),
true,
);
stage(&farm, "claude", &restated, &repo, Some(&home)).unwrap();
assert_eq!(listed(&claude_tree), ["codexy", "gh", "muted", "tdd"]);
assert!(home.join(".agents/skills/lint").is_dir());
assert!(farm.join("copilot").is_dir(), "restaging Claude's tree leaves Copilot's alone");
// An ACP agent gets no farm.
let delivery = stage(&farm, "cursor-acp", &states, &repo, Some(&home)).unwrap();
assert_eq!(delivery, Delivery::default());
// The farm goes away with the task.
remove_farm(&root.join("store"), "task-1");
assert!(!farm.exists());
}
#[test]
fn hub_menu_filters_off_and_keeps_the_agents_own() {
let root = PathBuf::from("/r");
let states = resolve(
vec![skill("tdd", AgentSkillSource::Workspace, &root), skill("lint", AgentSkillSource::User, &root)],
Some(&BTreeMap::from([("lint".to_owned(), AgentSkillMode::Off)])),
&BTreeMap::new(),
&BTreeMap::new(),
true,
);
let menu = menu_commands(vec![cmd("tdd", "from the agent itself")], &states);
assert_eq!(names(&menu), ["tdd"]);
assert_eq!(menu[0].description, "from the agent itself");
assert_eq!(menu[0].source, AgentCommandSource::Skill);
}
}
+5 -2
Переглянути файл
@@ -4532,6 +4532,7 @@ async fn per_session_mcp_overrides_filter_session_and_reload_when_idle() {
base: None,
mcp_overrides: BTreeMap::from([("slack".into(), false)]),
idle: false,
skill_overrides: BTreeMap::new(),
})
.await
.unwrap();
@@ -4660,6 +4661,7 @@ async fn copilot_falls_back_to_acp_when_headless_probe_session_or_prompt_fails()
base: None,
mcp_overrides: BTreeMap::new(),
idle: false,
skill_overrides: BTreeMap::new(),
})
.await
.unwrap();
@@ -4685,6 +4687,7 @@ async fn copilot_falls_back_to_acp_when_headless_probe_session_or_prompt_fails()
base: None,
mcp_overrides: BTreeMap::new(),
idle: false,
skill_overrides: BTreeMap::new(),
})
.await
.unwrap();
@@ -4763,10 +4766,10 @@ done
#[test]
fn session_params_name_the_servers_off() {
let mcp = McpForSession { servers: vec![json!({ "name": "docs" })], off: vec!["github".into()] };
let params = session_params("/p", &mcp);
let params = session_params("/p", &mcp, None);
assert_eq!(params["cwd"], "/p");
assert_eq!(params["mcpServers"][0]["name"], "docs");
assert_eq!(params["_meta"]["openidea"]["mcpServersOff"], json!(["github"]));
let none = McpForSession { servers: Vec::new(), off: Vec::new() };
assert!(session_params("/p", &none).get("_meta").is_none());
assert!(session_params("/p", &none, None).get("_meta").is_none());
}
+34
Переглянути файл
@@ -130,6 +130,11 @@ pub struct AgentSettings {
#[serde(deserialize_with = "or_default")]
#[specta(type = BTreeMap<String, AgentMcpServer>)]
pub mcp_servers: BTreeMap<String, AgentMcpServer>,
/// How agent skills may run, keyed by skill name (`[agents.skills.<name>]`); `SKILL.md`
/// files on disk are never modified.
#[serde(deserialize_with = "or_default")]
#[specta(type = BTreeMap<String, AgentSkillPolicy>)]
pub skills: BTreeMap<String, AgentSkillPolicy>,
}
impl Default for AgentSettings {
@@ -150,6 +155,7 @@ impl Default for AgentSettings {
new_task_approvals: NewTaskApprovals::Bypass,
defaults: BTreeMap::new(),
mcp_servers: BTreeMap::new(),
skills: BTreeMap::new(),
}
}
}
@@ -205,6 +211,34 @@ impl Default for AgentMcpServer {
}
}
/// How an agent skill may run (`[agents.skills.<name>] mode = …`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentSkillMode {
/// The model decides when to use it.
#[default]
Auto,
/// Only when the user invokes it with `/name`.
SlashOnly,
/// Never.
Off,
}
/// A skill's policy in Settings › Agents › Skills, stored without touching its `SKILL.md`.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct AgentSkillPolicy {
#[serde(deserialize_with = "or_default")]
#[specta(type = AgentSkillMode)]
pub mode: AgentSkillMode,
}
impl Default for AgentSkillPolicy {
fn default() -> Self {
Self { mode: AgentSkillMode::Auto }
}
}
/// A hand-edited value these settings don't know reads as the default, rather than
/// failing the whole settings file.
fn or_default<'de, D, T>(d: D) -> Result<T, D::Error>
+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: trust::TrustStore,
pub trust: std::sync::Arc<trust::TrustStore>,
pub(crate) mcp_approvals: Arc<trust::McpServerApprovals>,
pub config_dir: PathBuf,
/// Persistent user state, including credentials and recovery history.
@@ -169,7 +169,7 @@ impl Host {
mcp_agent_runs: Default::default(),
mcp_background: Default::default(),
agent_catalogs: Arc::default(),
trust: trust::TrustStore::load(&config_dir, &data_dir),
trust: std::sync::Arc::new(trust::TrustStore::load(&config_dir, &data_dir)),
mcp_approvals: Arc::new(trust::McpServerApprovals::load(&data_dir)),
proxy_password: ide_ssh::secrets::SecretFile::new(data_dir.join("proxy-password.json")),
proxy_session_password: Mutex::default(),
+148 -2
Переглянути файл
@@ -7,8 +7,9 @@ use ide_agent::registry::{AgentRegistry, RegistryPaths};
use ide_agent::{
AcpImportOutcome, AgentAcceptOutcome, AgentChange, AgentChanges, AgentChangesView, AgentCliOffer,
AgentCliUpdateResult, AgentCommand, AgentContextUsage, AgentEntry, AgentEvent, AgentModelCatalog, AgentProbe,
AgentPrompt, AgentProvider, AgentQueued, AgentTask, CustomAgentInput, ExternalSession, McpExternalSource,
McpImportSelection, McpProbeResult, McpScope, McpServer, McpServerInput, McpTransport, NewAgentTask,
AgentPrompt, AgentProvider, AgentQueued, AgentSkillMode, AgentSkillPolicy, AgentSkillState, AgentTask,
CustomAgentInput, ExternalSession, McpExternalSource, McpImportSelection, McpProbeResult, McpScope, McpServer,
McpServerInput, McpTransport, NewAgentTask, SkillsPolicy,
};
use ide_command::command;
use ide_core::error::ErrorKind;
@@ -1028,6 +1029,148 @@ pub fn agent_set_mcp_overrides(
host.project(window)?.agents.set_mcp_overrides(&task, overrides)
}
/// Updates per-session skill modes on `task`.
#[command(trust = always)]
pub fn agent_set_skill_overrides(
host: &Host,
window: &str,
task: String,
overrides: std::collections::BTreeMap<String, AgentSkillMode>,
) -> IdeResult<AgentTask> {
host.project(window)?.agents.set_skill_overrides(&task, overrides)
}
/// Every skill discovered in the project and the user's folders, with the mode a session
/// of this project runs it with (without any session's own overrides).
#[command(trust = always)]
pub async fn agent_skills_list(host: &Host, window: &str) -> IdeResult<Vec<AgentSkillState>> {
let project = host.project(window)?;
let root = project.root.clone();
let (policy, home) = (skills_policy(&project), dirs::home_dir());
tokio::task::spawn_blocking(move || {
Ok(ide_agent::skills::resolve(
ide_agent::skills::discover_skills(&root, home.as_deref()),
None,
&policy.workspace,
&policy.user,
policy.workspace_trusted,
))
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?
}
/// Sets how `name` may run in `scope`, in the settings file of that scope, and returns the
/// updated list. `SKILL.md` files are never touched; the default `auto` removes the entry.
#[command(trust = always)]
pub fn agent_skills_set_mode(
host: &Host,
window: &str,
name: String,
scope: McpScope,
mode: AgentSkillMode,
) -> IdeResult<Vec<AgentSkillState>> {
let name = name.trim().to_owned();
if name.is_empty() {
return Err(IdeError::invalid("a skill needs a name"));
}
let project = host.project(window).ok().filter(|p| !p.light);
let (mut user, mut workspace) = skills_maps(host, project.as_ref());
match scope {
McpScope::User => {
let changed = if mode == AgentSkillMode::Auto {
user.remove(&name).is_some()
} else {
user.insert(name, AgentSkillPolicy { mode }).map(|p| p.mode) != Some(mode)
};
if changed {
persist_skills_map(host, None, scope, &user)?;
}
}
McpScope::Workspace => {
let map =
workspace.as_mut().ok_or_else(|| IdeError::invalid("Open a project to configure workspace skills"))?;
let changed = if mode == AgentSkillMode::Auto {
map.remove(&name).is_some()
} else {
map.insert(name, AgentSkillPolicy { mode }).map(|p| p.mode) != Some(mode)
};
if changed {
let map = map.clone();
persist_skills_map(host, project.as_ref(), scope, &map)?;
}
}
}
match project {
Some(project) => {
let root = project.root.clone();
let policy = skills_policy(&project);
let home = dirs::home_dir();
Ok(ide_agent::skills::resolve(
ide_agent::skills::discover_skills(&root, home.as_deref()),
None,
&policy.workspace,
&policy.user,
policy.workspace_trusted,
))
}
None => Ok(Vec::new()),
}
}
/// The user's and the workspace's skill policies (`[agents.skills.<name>]`).
fn skills_maps(
host: &Host,
project: Option<&std::sync::Arc<crate::Project>>,
) -> (std::collections::BTreeMap<String, AgentSkillPolicy>, Option<std::collections::BTreeMap<String, AgentSkillPolicy>>)
{
let user = host.global_settings.effective().agents.skills.clone();
let workspace =
project.map(|p| p.settings.layer(ide_workspace::settings::SettingsScope::Project).agents.skills.clone());
(user, workspace)
}
/// Saves `map` into its scope's settings and tells the windows.
fn persist_skills_map(
host: &Host,
project: Option<&std::sync::Arc<crate::Project>>,
scope: McpScope,
map: &std::collections::BTreeMap<String, AgentSkillPolicy>,
) -> IdeResult<()> {
let value = if map.is_empty() {
serde_json::Value::Null
} else {
serde_json::to_value(map).map_err(|e| IdeError::invalid(e.to_string()))?
};
let event = IdeEvent::SettingsChanged { key: "agents.skills".into() };
match scope {
McpScope::User => {
host.global_settings.set(ide_workspace::settings::SettingsScope::Global, "agents.skills", value)?;
for p in host.projects() {
p.settings.reload();
p.agents.notify_mcp_servers_changed();
p.sink.emit(event.clone());
}
}
McpScope::Workspace => {
let p = project.ok_or_else(|| IdeError::invalid("Open a project to configure workspace skills"))?;
p.settings.set(ide_workspace::settings::SettingsScope::Project, "agents.skills", value)?;
p.agents.notify_mcp_servers_changed();
p.sink.emit(event);
}
}
Ok(())
}
/// The skill policies a session of `project` resolves against.
fn skills_policy(project: &crate::Project) -> SkillsPolicy {
SkillsPolicy {
user: project.settings.layer(ide_workspace::settings::SettingsScope::Global).agents.skills.clone(),
workspace: project.settings.layer(ide_workspace::settings::SettingsScope::Project).agents.skills.clone(),
workspace_trusted: project.trusted.load(std::sync::atomic::Ordering::Acquire),
}
}
fn validate_project_root(root: &std::path::Path, requested: Option<&std::path::Path>) -> IdeResult<std::path::PathBuf> {
let Some(requested) = requested else {
return Ok(root.to_path_buf());
@@ -1183,6 +1326,9 @@ ide_command::domain!(
agent_set_config,
agent_set_env,
agent_set_mcp_overrides,
agent_set_skill_overrides,
agent_skills_list,
agent_skills_set_mode,
agent_stop_background,
agent_subscribe,
agent_unarchive,
+6
Переглянути файл
@@ -335,6 +335,12 @@ pub fn set_settings(
project.agents.notify_mcp_servers_changed();
}
}
// A skill policy change re-resolves the modes; an idle session restarts to pick them up.
if key == "agents" || key == "agents.skills" || key.starts_with("agents.skills.") {
for project in affected() {
project.agents.notify_mcp_servers_changed();
}
}
// A new interpreter / toolchain / server executable restarts the language servers it affects.
// So do inspections that are compiler options (`ide-sdk` `configure_java_compiler`).
let code_style = key == "editor"
+13
Переглянути файл
@@ -738,6 +738,19 @@ impl Host {
let approvals = self.mcp_approvals.clone();
let secrets = self.agent_secrets.clone();
let root = root.to_path_buf();
// The skill policies sessions resolve against: both settings layers and the
// workspace's trust as it stands when a session starts.
let skill_settings = settings.clone();
let skill_root = root.clone();
let trust = self.trust.clone();
agents.set_skills_policy_hook(Box::new(move || {
let layer = |scope| skill_settings.layer(scope).agents.skills.clone();
ide_agent::SkillsPolicy {
user: layer(ide_workspace::settings::SettingsScope::Global),
workspace: layer(ide_workspace::settings::SettingsScope::Project),
workspace_trusted: trust.trusted(&skill_root).unwrap_or(false),
}
}));
agents.set_mcp_servers_hook(Box::new(move || {
crate::ops::agent::session_mcp_servers(&settings, &approvals, &secrets, &root)
}));
+31 -2
Переглянути файл
@@ -235,6 +235,12 @@ fn gix_status(r: &Repo, ignored: &IgnoredNames) -> IdeResult<Entries> {
Ok((map, conflicts))
}
/// Keeps `git status` from rewriting the index with refreshed stat data. Such a write is not
/// one of ours to the watcher, so it would schedule another refresh, which runs git again (#4792).
fn read_only() -> [(&'static str, &'static std::ffi::OsStr); 1] {
[("GIT_OPTIONAL_LOCKS", std::ffi::OsStr::new("0"))]
}
/// `git status --porcelain=v2`: what git lists, unreadable directories skipped.
/// In Restricted Mode git compares content without the repository's clean/process
/// filters and doesn't ask submodules for their own status (which runs their config).
@@ -245,7 +251,7 @@ fn cli_status(r: &Repo, ignored: &IgnoredNames) -> IdeResult<Entries> {
if !crate::execution_allowed() {
args.push("--ignore-submodules=dirty");
}
let out = crate::cli::run(r.root(), &args, None)?;
let out = crate::cli::run_env(r.root(), &args, None, &read_only())?;
Ok(parse_porcelain_v2(&String::from_utf8_lossy(&out.stdout), ignored))
}
@@ -260,7 +266,7 @@ fn cli_status_paths(r: &Repo, ignored: &IgnoredNames, paths: &[String]) -> IdeRe
}
args.push("--");
args.extend(paths.iter().map(String::as_str));
let out = crate::cli::run(r.root(), &args, None)?;
let out = crate::cli::run_env(r.root(), &args, None, &read_only())?;
Ok(parse_porcelain_v2(&String::from_utf8_lossy(&out.stdout), ignored))
}
@@ -397,6 +403,29 @@ mod tests {
assert!(staged.stdout.is_empty(), "{}", String::from_utf8_lossy(&staged.stdout));
}
/// #4792: the dirty-scope `git status` must not rewrite the index after refreshing stale
/// stat data, or the watcher sees a foreign index write and refreshes again.
#[test]
fn git_status_of_paths_leaves_the_index_alone() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
git(dir, &["init", "-q"]);
git(dir, &["config", "user.name", "Test User"]);
git(dir, &["config", "user.email", "[email protected]"]);
git(dir, &["config", "commit.gpgsign", "false"]);
std::fs::write(dir.join("a.txt"), "a\n").unwrap();
commit_all(dir, "base");
// Same content, new stat data: plain `git status` would refresh and write the index.
std::thread::sleep(std::time::Duration::from_millis(1100));
std::fs::write(dir.join("a.txt"), "a\n").unwrap();
let index = dir.join(".git/index");
let before = std::fs::read(&index).unwrap();
let repo = Repo::discover(dir).unwrap().expect("repository found");
assert!(status_paths(&repo, &["a.txt".to_owned()]).unwrap().is_empty());
assert_eq!(std::fs::read(&index).unwrap(), before, "git status rewrote the index");
}
/// git's porcelain answer (used when gitoxide can't read the tree) matches gitoxide's.
#[test]
fn git_and_gitoxide_report_the_same_status() {
+8
Переглянути файл
@@ -139,6 +139,14 @@ Tasks are saved per project and survive restarts. When the agent supports resumi
- **Agent Configs**: discovers servers already configured in `~/.copilot/mcp-config.json` (and installed Copilot CLI plugins), `~/.claude.json`, `~/.codex/config.toml`, `~/.cursor/mcp.json`, `~/.gemini/settings.json`, `~/.jetbrains/mcp/mcp.json`, `.mcp.json`, and `.vscode/mcp.json` so you can import them into Global or Project settings with one click. You can also add or edit servers via structured fields or raw `mcpServers` JSON (**Add from JSON**), and run **Test Connection** to inspect the tools a server advertises.
- **Per-session (`MCP` / `/mcp`)**: in both **New Agent Task** and active task conversations, open **MCP** in the composer toolbar (or run `/mcp`) to enable or disable individual servers—including the built-in `openidea` server—for that task only, or click **Reset** to return to the inherited defaults.
### Agent skills
**Settings › Agents › Skills** lists every skill (`SKILL.md` folders) in one place, grouped by the folder it was found in: the project's `.agents/skills` and `.openidea/skills`, your `~/.agents/skills` (what `npx skills add` fills), and each CLI's own folders (`.claude/skills`, `.github/skills`, `.codex/skills`, `.cursor/skills`, `~/.claude/skills`, `~/.copilot/skills` and its installed plugins, `~/.codex/skills`, `~/.cursor/skills`). Symlinked copies of the same skill appear once, and expanding a row shows its canonical path and the `SKILL.md` validation result.
Each skill runs in one of three modes, set globally or per workspace without ever editing the skill's files: **Auto** (the model decides), **Slash only** (just `/name`), or **Off**. A workspace can turn a global skill off without prose rules in `AGENTS.md`; a skill the settings keep off shows as **Enable in Settings** in the session picker.
In the composer, `/skills` (or the **Add Context** menu) opens the per-session picker next to the MCP one: turn individual skills off for this task only, or **Reset** to the inherited modes. The `/` menu offers the active skills of every agent, and Claude Code, Copilot and Codex all receive the same set. Agents that only speak ACP keep their own `/` menu, so turning a skill off there stops OpenIDEA from offering it but is otherwise best-effort.
While the agent works, the line under the conversation says what it is doing: thinking, reading, editing, running a command, writing its reply.
## Add a custom agent
+8
Переглянути файл
@@ -139,6 +139,14 @@ agent 运行过一个任务后,新任务会以它自动批准所有操作的
- **智能体配置**:自动发现 `~/.copilot/mcp-config.json`(及已安装的 Copilot CLI 插件)、`~/.claude.json`、`~/.codex/config.toml`、`~/.cursor/mcp.json`、`~/.gemini/settings.json`、`~/.jetbrains/mcp/mcp.json`、`.mcp.json` 和 `.vscode/mcp.json` 中已配置的服务器,可一键导入到全局或项目设置。添加或编辑服务器时既可使用表单,也可直接粘贴 `mcpServers` JSON(**从 JSON 添加**),并可通过 **测试连接** 查看服务器声明的工具列表。
- **按会话覆盖(`MCP` / `/mcp`)**:在 **新建 Agent 任务** 和进行中的任务对话中,单击输入框工具栏的 **MCP**(或输入 `/mcp`),即可仅针对当前任务开启或关闭任意服务器(包括内置的 `openidea` 服务器),或点击 **重置** 恢复继承的默认状态。
### 智能体技能
**设置 › 智能体 › 技能** 把所有技能(`SKILL.md` 文件夹)汇总在一个列表里,并按发现它们的文件夹分组:项目的 `.agents/skills` 与 `.openidea/skills`、你的 `~/.agents/skills`(即 `npx skills add` 填充的目录),以及各 CLI 自己的文件夹(`.claude/skills`、`.github/skills`、`.codex/skills`、`.cursor/skills`、`~/.claude/skills`、`~/.copilot/skills` 及其已安装插件、`~/.codex/skills`、`~/.cursor/skills`)。同一技能的符号链接副本只显示一次,展开一行可以看到其规范路径与 `SKILL.md` 的校验结果。
每个技能有三种运行模式,可全局或按工作区设置,且从不改动技能自身的文件:**自动**(由模型决定)、**仅斜杠**(只通过 `/名称` 调用)或 **关闭**。工作区可以关闭一个全局技能,而无需在 `AGENTS.md` 里写文字规则;被设置关闭的技能在会话选择器中会显示为 **在设置中启用**。
在输入框中,`/skills`(或 **添加上下文** 菜单)会打开与 MCP 并排的会话技能选择器:仅为当前任务关闭单个技能,或点击 **重置** 恢复继承的模式。`/` 菜单会列出所有智能体的活动技能,Claude Code、Copilot 与 Codex 收到的是同一套技能。只讲 ACP 协议的智能体保留自己的 `/` 菜单,因此在那里关闭技能只会让 OpenIDEA 不再提供它,其余尽力而为。
agent 工作时,对话下方的状态行显示它正在做什么:思考、读取、编辑、运行命令、输出回复。
## 添加自定义 agent
+3
Переглянути файл
@@ -46,7 +46,10 @@ 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
+106
Переглянути файл
@@ -143,11 +143,23 @@ 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 })),
/**
@@ -2688,6 +2700,11 @@ 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. */
@@ -2728,6 +2745,89 @@ 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. */
@@ -2802,6 +2902,8 @@ 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,
};
@@ -2852,6 +2954,8 @@ 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,
};
@@ -9019,6 +9123,8 @@ 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,7 +571,10 @@ 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);
+3 -1
Переглянути файл
@@ -927,7 +927,7 @@ export class DocumentManager {
try {
await model.save("auto");
} catch (e) {
console.warn(`autosave of ${model.path} failed`, e);
logError(`autosave of ${model.path} failed`, e);
}
}
// As in IDEA, a file whose changes are not saved (autosave off, or a failed save) stays
@@ -985,6 +985,8 @@ 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);
}),
),
+44 -11
Переглянути файл
@@ -130,6 +130,8 @@ 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. */
@@ -514,17 +516,26 @@ 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 =
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,
]
completion.query.length > 0 && openPickerCommands.length > 0
? [...openPickerCommands, ...props.commands]
: props.commands;
const out: Item[] = [];
let source: "command" | "skill" | undefined;
@@ -537,7 +548,18 @@ export function Composer(props: ComposerProps) {
out.push({ kind: "command", command });
}
return out;
}, [completion, files, shellFound, shellQuery, recentCommands, props.history, props.commands, props.onOpenMcp, tx]);
}, [
completion,
files,
shellFound,
shellQuery,
recentCommands,
props.history,
props.commands,
props.onOpenMcp,
props.onOpenSkills,
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;
@@ -629,6 +651,11 @@ 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);
@@ -980,6 +1007,12 @@ 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();
+22 -1
Переглянути файл
@@ -15,6 +15,7 @@ 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";
@@ -27,6 +28,7 @@ import {
refreshProviders,
refreshModels,
setDraftMcpOverrides,
setDraftSkillOverrides,
setDraftOption,
startTask,
updateDraft,
@@ -66,6 +68,7 @@ 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();
@@ -163,6 +166,7 @@ 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(" ");
@@ -208,8 +212,16 @@ 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 }] : undefined}
addMenu={
provider
? [
{ id: "mcp", label: "MCP Servers…", icon: "plugin", run: openMcp },
{ id: "skills", label: "Skills…", icon: "bulb", run: openSkills },
]
: undefined
}
toolbar={
<>
<span className={styles.agentPicker} {...tooltipAttrs(agentTitle, undefined, true)}>
@@ -270,6 +282,15 @@ export function HomeEditor({ docked = false, input }: { docked?: boolean; input?
hideTrigger
/>
)}
{provider && (
<SkillsPicker
provider={provider.id}
overrides={draft.skillOverrides}
onChange={setDraftSkillOverrides}
openRequest={skillsOpenRequest}
hideTrigger
/>
)}
</>
}
actions={
+334
Переглянути файл
@@ -0,0 +1,334 @@
.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
Переглянути файл
@@ -0,0 +1,139 @@
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
Переглянути файл
@@ -0,0 +1,420 @@
/**
* 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
Переглянути файл
@@ -0,0 +1,225 @@
.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
Переглянути файл
@@ -0,0 +1,141 @@
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
Переглянути файл
@@ -0,0 +1,314 @@
/**
* 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,6 +21,7 @@ export const AGENT_SETTINGS_DEFAULTS: ResolvedAgentSettings = {
newTaskApprovals: "bypass",
defaults: {},
mcpServers: {},
skills: {},
};
export function resolveAgentSettings(s: AgentSettings | null | undefined): ResolvedAgentSettings {
+12
Переглянути файл
@@ -182,6 +182,18 @@ 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,6 +13,8 @@ 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,6 +10,7 @@ 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";
@@ -27,6 +28,7 @@ import {
sendQueuedNow,
setTaskConfig,
setTaskMcpOverrides,
setTaskSkillOverrides,
stopBackgroundTask,
useAgentCommands,
useAgents,
@@ -197,6 +199,7 @@ 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);
@@ -263,6 +266,7 @@ 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 (
@@ -307,9 +311,11 @@ 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={
<>
@@ -352,6 +358,23 @@ 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={
+10 -2
Переглянути файл
@@ -1,8 +1,8 @@
import { lazyComponent } from "@/ui";
import { registerSettingsPages } from "@/workbench/contributions";
import { AGENTS_GROUP, MCP_PAGE, POLICY_PAGE, REGISTRY_PAGE } from "./model";
import { AGENTS_GROUP, MCP_PAGE, POLICY_PAGE, REGISTRY_PAGE, SKILLS_PAGE } from "./model";
/** Settings › Agents › Coding Agents and Settings › Agents › External MCP Servers (also used by the Settings window). */
/** Settings › Agents › Coding Agents, External MCP Servers, Skills, and Command Permissions (also used by the Settings window). */
export function activateSettingsPages(): () => void {
return registerSettingsPages([
{
@@ -22,6 +22,14 @@ 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
Переглянути файл
@@ -0,0 +1,140 @@
/**
* 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,6 +16,7 @@ import type {
AgentModelCatalog,
AgentPrompt,
AgentProvider,
AgentSkillMode,
AgentTask,
ExternalSession,
Isolation,
@@ -84,6 +85,8 @@ 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. */
@@ -1228,6 +1231,7 @@ 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,
}),
@@ -1562,6 +1566,10 @@ 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) {
@@ -1575,6 +1583,19 @@ 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();
+1
Переглянути файл
@@ -19,6 +19,7 @@ describe("agent chat settings", () => {
newTaskApprovals: "bypass",
defaults: {},
mcpServers: {},
skills: {},
});
const stored = validateSettings({
agents: { showUsageLimits: false, showCost: true, showWorkTime: "no", fitWindowWidth: true },
+11
Переглянути файл
@@ -245,6 +245,7 @@ export const DEFAULT_SETTINGS: ValidSettings = {
newTaskApprovals: "bypass",
defaults: {},
mcpServers: {},
skills: {},
},
mcpServer: {
enabled: false,
@@ -314,6 +315,15 @@ 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) => {
@@ -448,6 +458,7 @@ 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),
+12
Переглянути файл
@@ -88,6 +88,7 @@ describe("t / locales", () => {
expect(resolveLocale("fr")).toBe("fr");
expect(resolveLocale("fr-CA")).toBe("fr");
expect(resolveLocale("pl_PL")).toBe("pl");
expect(resolveLocale("tr-TR")).toBe("tr");
expect(resolveLocale("pl-PL")).toBe("pl");
expect(resolveLocale("es-MX")).toBe("es");
expect(resolveLocale("es_MX")).toBe("es");
@@ -220,6 +221,13 @@ describe("t / locales", () => {
expect(t("app.keymap.count", { count: 5 })).toBe("5 skrótów");
});
it("loads the Turkish catalogs", async () => {
await setLocale("tr-TR");
expect(useI18n.getState().locale).toBe("tr");
expect(t("common.cancel")).toBe("İptal");
expect(t("app.keymap.count", { count: 1 })).toBe("1 kısayol");
});
it("loads the Spanish catalogs", async () => {
await setLocale("es-MX");
expect(useI18n.getState().locale).toBe("es");
@@ -278,6 +286,10 @@ describe("catalogs", () => {
"Go",
"Rust",
"Kotlin",
"Claude Code",
"GitHub Copilot",
"Codex",
"Cursor",
"PHP",
"SQL",
"COPY",
+1
Переглянути файл
@@ -46,6 +46,7 @@ export const LOCALES = {
pl: { name: "Polski (Polish)", tag: "pl" },
pt: { name: "Português (Portuguese)", tag: "pt-BR" },
es: { name: "Español (Spanish)", tag: "es-MX" },
tr: { name: "Türkçe (Turkish)", tag: "tr-TR" },
} as const;
export type Locale = keyof typeof LOCALES;
export const SUPPORTED_LOCALES = Object.keys(LOCALES) as Locale[];
+41 -1
Переглянути файл
@@ -2836,5 +2836,45 @@
"{all} is not available in a remote project.": "{all} is not available in a remote project.",
"Cannot start '{name}'": "Cannot start '{name}'",
"Module working directory": "Module working directory",
"User home directory": "User home directory"
"User home directory": "User home directory",
"Session Skills": "Session Skills",
"Skills…": "Skills…",
"Filter skills…": "Filter skills…",
"Filter skills": "Filter skills",
"/Slash": "/Slash",
"Auto": "Auto",
"No skills found.": "No skills found.",
"No matching skills.": "No matching skills.",
"This agent keeps its own / menu: off only stops OpenIDEA offering the skill.": "This agent keeps its own / menu: off only stops OpenIDEA offering the skill.",
"Skills ({active}/{total} active)": "Skills ({active}/{total} active)",
"Skills ({active}/{total} active · {overrides} session overrides)": "Skills ({active}/{total} active · {overrides} session overrides)",
"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.": "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.",
"Skill sources": "Skill sources",
"All Sources": "All Sources",
"User": "User",
"Agent Folders": "Agent Folders",
"Search skills": "Search skills",
"Global": "Global",
"Slash only": "Slash only",
"Off": "Off",
"Untrusted workspace": "Untrusted workspace",
"CLI-discovered": "CLI-discovered",
"Invalid SKILL.md": "Invalid SKILL.md",
"Active": "Active",
"Path": "Path",
"Validation": "Validation",
"SKILL.md is valid": "SKILL.md is valid",
"SKILL.md failed validation": "SKILL.md failed validation",
"Open SKILL.md": "Open SKILL.md",
"Copy path": "Copy path",
"Copy the path of {name}": "Copy the path of {name}",
"Scope for {name}": "Scope for {name}",
"Mode for {name}": "Mode for {name}",
"Claude Code": "Claude Code",
"GitHub Copilot": "GitHub Copilot",
"Codex": "Codex",
"Cursor": "Cursor",
"Configure skills for this session": "Configure skills for this session",
"No skills found in .agents/skills, .openidea/skills, ~/.agents/skills, or the CLI folders of Claude Code, GitHub Copilot, Codex, and Cursor.": "No skills found in .agents/skills, .openidea/skills, ~/.agents/skills, or the CLI folders of Claude Code, GitHub Copilot, Codex, and Cursor.",
"This CLI discovers the folder itself: off hides the skill from OpenIDEA's / menu and applies only where the CLI supports disabling.": "This CLI discovers the folder itself: off hides the skill from OpenIDEA's / menu and applies only where the CLI supports disabling."
}
File diff suppressed because it is too large. Load diff
+36 -2
Переглянути файл
@@ -564,7 +564,6 @@
"Nested function definition": "嵌套函数定义",
"Text (unicode)": "文本(Unicode)",
"Escape sequence": "转义序列",
"Valid": "有效",
"Operation sign": "运算符",
"Function definition": "函数定义",
"Class definition": "类定义",
@@ -9190,5 +9189,40 @@
"{all} is not available in a remote project.": "{all} 在远程项目中不可用。",
"Cannot start '{name}'": "无法启动“{name}”",
"Module working directory": "模块工作目录",
"User home directory": "用户主目录"
"User home directory": "用户主目录",
"Session Skills": "会话技能",
"Skills…": "技能…",
"Filter skills…": "筛选技能…",
"Filter skills": "筛选技能",
"/Slash": "/斜杠",
"No skills found.": "未找到技能。",
"No matching skills.": "没有匹配的技能。",
"This agent keeps its own / menu: off only stops OpenIDEA offering the skill.": "该代理保留自己的 / 菜单:关闭只会让 OpenIDEA 不再提供该技能。",
"Skills ({active}/{total} active)": "技能({active}/{total} 个启用)",
"Skills ({active}/{total} active · {overrides} session overrides)": "技能({active}/{total} 个启用 · {overrides} 个会话覆盖)",
"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.": "技能是编码代理加载的 SKILL.md 文件夹:先看工作区与你的用户文件夹,再看各个 CLI 自己发现的部分。这里设置的模式从不改动技能的文件,仓库也可以让全局技能安静下来,而无需在 AGENTS.md 里写规则。",
"Skill sources": "技能来源",
"All Sources": "所有来源",
"Agent Folders": "代理文件夹",
"Search skills": "搜索技能",
"Slash only": "仅斜杠",
"Untrusted workspace": "不受信任的工作区",
"CLI-discovered": "CLI 自发现",
"Invalid SKILL.md": "无效的 SKILL.md",
"Active": "启用",
"Validation": "校验",
"SKILL.md is valid": "SKILL.md 校验通过",
"SKILL.md failed validation": "SKILL.md 校验未通过",
"Open SKILL.md": "打开 SKILL.md",
"Copy path": "复制路径",
"Copy the path of {name}": "复制 {name} 的路径",
"Scope for {name}": "{name} 的作用域",
"Mode for {name}": "{name} 的模式",
"Claude Code": "Claude Code",
"GitHub Copilot": "GitHub Copilot",
"Codex": "Codex",
"Cursor": "Cursor",
"Configure skills for this session": "为此会话配置技能",
"No skills found in .agents/skills, .openidea/skills, ~/.agents/skills, or the CLI folders of Claude Code, GitHub Copilot, Codex, and Cursor.": "未在 .agents/skills、.openidea/skills、~/.agents/skills 或 Claude Code、GitHub Copilot、Codex 与 Cursor 的 CLI 文件夹中找到技能。",
"This CLI discovers the folder itself: off hides the skill from OpenIDEA's / menu and applies only where the CLI supports disabling.": "该 CLI 会自己发现这个文件夹:关闭只会让 OpenIDEA 的 / 菜单不再提供该技能,并且只在 CLI 支持禁用时生效。"
}
+533
Переглянути файл
@@ -0,0 +1,533 @@
{
"app.about.build": "Derleme",
"app.about.configDir": "Yapılandırma",
"app.about.copyInfo": "Bilgileri Kopyala",
"app.about.copyright": "Telif Hakkı © 2026 OpenIDEA katkıda bulunanları",
"app.about.disclaimer": "JetBrains ile bağlantılı değildir.",
"app.about.license": "Apache Lisansı 2.0 kapsamında lisanslanmıştır",
"app.about.platform": "Platform",
"app.about.reportIssue": "Sorun Bildir",
"app.about.runtime": "Çalışma Zamanı",
"app.about.showConfig": "Yapılandırma Klasörünü Aç",
"app.about.tagline": "IntelliJ IDEA'dan ilham alan açık kaynaklı bir IDE",
"app.about.thirdParty": "IntelliJ Platformu simgelerini içerir (Apache-2.0).",
"app.about.title": "OpenIDEA Hakkında",
"app.about.version": "Sürüm",
"app.action.about": "OpenIDEA Hakkında",
"app.action.checkForUpdates": "Güncellemeleri Denetle…",
"app.action.copy": "Kopyala",
"app.action.cut": "Kes",
"app.action.keymapReference": "Klavye Kısayolları Başvurusu",
"app.action.lightEditOpenProject": "Bulunduğu Klasörü Proje Olarak Aç",
"app.action.newFile": "Yeni Adsız Dosya",
"app.action.newWindow": "Yeni Pencere",
"app.action.nextWindow": "Sonraki Proje Penceresi",
"app.action.openFile": "Dosya Aç…",
"app.action.openInNewWindow": "Yeni Pencerede Aç…",
"app.action.openRecentProject": "Son Kullanılan Projeyi Aç",
"app.action.paste": "Yapıştır",
"app.action.previousWindow": "Önceki Proje Penceresi",
"app.action.quit": "{os, select, macos {OpenIDEA'dan Çık} other {Çıkış}}",
"app.action.redo": "Yinele",
"app.action.selectAll": "Tümünü Seç",
"app.action.showLog": "{os, select, macos {Günlüğü Finder'da Göster} windows {Günlüğü Dosya Gezgini'nde Göster} other {Günlüğü Dosyalar'da Göster}}",
"app.action.toggleFullScreen": "Tam Ekranı Aç/Kapat",
"app.action.undo": "Geri Al",
"app.category.edit": "Düzenle",
"app.category.file": "Dosya",
"app.category.help": "Yardım",
"app.category.view": "Görünüm",
"app.category.window": "Pencere",
"app.exit.body": "OpenIDEA'dan çıkmak istediğinizden emin misiniz?",
"app.exit.confirm": "Çıkış",
"app.exit.dontAsk": "Bir Daha Sorma",
"app.exit.title": "Çıkışı Onayla",
"app.keymap.count": "{count, plural, one {# kısayol} other {# kısayol}}",
"app.keymap.empty": "Eşleşen kısayol bulunamadı",
"app.keymap.filter": "Eyleme veya kısayola göre filtrele",
"app.keymap.other": "Diğer",
"app.keymap.preset": "Klavye Düzeni: {preset}",
"app.keymap.title": "Klavye Kısayolları Başvurusu",
"app.lightEdit.openProject": "Proje Olarak Aç",
"app.lightEdit.openProjectTooltip": "{folder} klasörünü proje olarak aç",
"app.lightEdit.pickFolderTooltip": "Proje olarak açılacak klasörü seç",
"app.log.failed": "Günlük gösterilemiyor",
"app.project.opening": "{name} açılıyor…",
"app.terminateProcesses.bodyMany": "Şu {count} işlemi sonlandırmak istiyor musunuz: {names}?",
"app.terminateProcesses.bodyOne": "'{name}' işlemini sonlandırmak istiyor musunuz?",
"app.terminateProcesses.dontAsk": "Bir Daha Sorma",
"app.terminateProcesses.terminate": "Sonlandır",
"app.terminateProcesses.titleMany": "Çalışan İşlemler Var",
"app.terminateProcesses.titleOne": "'{name}' İşlemi Çalışıyor",
"app.title.default": "OpenIDEA",
"app.unsaved.body": "{project} projesinde {count, plural, one {# dosyada} other {# dosyada}} kaydedilmemiş değişiklik var. Kapatmadan önce kaydedilsin mi?",
"app.unsaved.discard": "Kaydetme",
"app.unsaved.fileBody": "{name} dosyasında kaydedilmemiş değişiklikler var. Kapatmadan önce kaydedilsin mi?",
"app.unsaved.save": "Tümünü Kaydet",
"app.unsaved.saveFailed": "Tüm dosyalar kaydedilemedi",
"app.unsaved.saveFile": "Kaydet",
"app.unsaved.title": "Kaydedilmemiş Değişiklikler",
"app.update.available": "OpenIDEA {version} kullanılabilir",
"app.update.cancel": "İptal",
"app.update.cancelled": "Güncelleme iptal edildi",
"app.update.checking": "Güncellemeler denetleniyor…",
"app.update.disabled": "Otomatik güncellemeler yapılandırılmamış",
"app.update.disabledBody": "Güncelleme denetimini etkinleştirmek için bir güncelleme uç noktası (OPENIDEA_UPDATE_ENDPOINT veya plugins.updater.endpoints) belirleyin.",
"app.update.downloading": "OpenIDEA {version} indiriliyor",
"app.update.failed": "Güncelleme denetimi başarısız oldu",
"app.update.install": "Yükle ve Yeniden Başlat",
"app.update.installFailed": "Güncelleme yüklenemedi",
"app.update.installed": "OpenIDEA {version} yüklendi",
"app.update.installedBody": "OpenIDEA yeniden başlatıldıktan sonra kullanılacaktır.",
"app.update.installingMessage": "Yükleniyor…",
"app.update.installUncancellable": "Güncelleme yükleniyor; bu aşama iptal edilemez",
"app.update.none": "OpenIDEA {version} güncel",
"app.update.progress": "{total} MB üzerinden {done} MB",
"app.update.progressUnknown": "{done} MB",
"app.update.restart": "Yeniden Başlat",
"app.update.retry": "Yeniden Dene",
"app.update.retryWith": "{source} ile Yeniden Dene",
"app.whatsNew.loading": "Sürüm notları getiriliyor…",
"app.whatsNew.noNotes": "Bu sürüm için sürüm notu bulunmuyor.",
"app.whatsNew.openReleases": "Sürüm Sayfasını Aç",
"app.whatsNew.showAfterUpdate": "Her güncellemeden sonra bu sayfayı göster",
"app.whatsNew.title": "Yenilikler",
"app.whatsNew.version": "OpenIDEA {version}",
"app.window.desktopOnly": "Birden fazla pencere için masaüstü uygulaması gereklidir",
"app.window.openFailed": "{name} açılamıyor",
"app.window.pickFileTitle": "Dosya Aç",
"app.window.pickTitle": "Yeni Pencerede Aç",
"app.window.askTitle": "Proje Aç",
"app.window.askBody": "Projeler yeni bir pencerede açılabilir, mevcut projenin yerine geçebilir veya açık projelere eklenebilir.\n\"{name}\" projesini nasıl açmak istersiniz?",
"app.window.askThis": "Bu Pencere",
"app.action.attachProject": "Proje Ekle…",
"app.window.detachTitle": "Projeyi Ayır",
"app.window.detachBody": "{name} projesini ayırmak istiyor musunuz?",
"app.window.detach": "Ayır",
"app.window.askAttach": "Ekle",
"app.window.askNew": "Yeni Pencere",
"app.window.askRemember": "Bir Daha Sorma",
"common.cancel": "İptal",
"common.close": "Kapat",
"common.copied": "Kopyalandı",
"common.copy": "Kopyala",
"editor.closeBusy.message": "'{name}' işlemini sonlandırmak istiyor musunuz?",
"editor.closeBusy.terminate": "Sonlandır",
"editor.closeBusy.title": "'{name}' İşlemi Çalışıyor",
"menu.activeEditor": "Etkin Düzenleyici",
"menu.editor.toggleSoftWrap": "Satırları Otomatik Kaydır",
"menu.editor.toggleRenderedDocs": "Belgelendirme Yorumlarını Biçimlendir",
"menu.app": "OpenIDEA",
"menu.app.about": "OpenIDEA Hakkında",
"menu.app.checkForUpdates": "Güncellemeleri Denetle…",
"menu.app.installCli": "'openidea' Komutunu Yükle",
"menu.app.quit": "{os, select, macos {OpenIDEA'dan Çık} other {Çıkış}}",
"menu.app.uninstallCli": "'openidea' Komutunu Kaldır",
"menu.app.whatsNew": "Yenilikler",
"menu.appearance": "Görünüm",
"menu.code": "Kod",
"menu.code.commentBlock": "Blok Yorumu Ekle",
"menu.code.commentLine": "Satır Yorumu Ekle",
"menu.code.completion": "Temel",
"menu.code.deleteLine": "Satırı Sil",
"menu.code.duplicateLine": "Satırı veya Seçimi Çoğalt",
"menu.code.extendSelection": "Seçimi Genişlet",
"menu.code.foldAll": "Tümünü Daralt",
"menu.code.foldToggle": "Genişlet/Daralt",
"menu.code.generate": "Oluştur…",
"menu.code.pasteAsPlainText": "Düz Metin Olarak Yapıştır",
"menu.editor.copyReference": "Başvuruyu Kopyala",
"menu.code.cyclicExpandWord": "Sözcüğü Döngüsel Genişlet",
"menu.code.cyclicExpandWordBackward": "Sözcüğü Döngüsel Genişlet (Geriye)",
"menu.code.expressionTypeInfo": "İfade Türü Bilgisi",
"menu.code.overrideMethods": "Metotları Geçersiz Kıl…",
"menu.code.implementMethods": "Metotları Uygula…",
"menu.code.insertLiveTemplate": "Canlı Şablon Ekle…",
"menu.code.moveLineDown": "Satırı Aşağı Taşı",
"menu.code.moveLineUp": "Satırı Yukarı Taşı",
"menu.code.optimizeImports": "İçe Aktarmaları İyileştir",
"menu.code.parameterInfo": "Parametre Bilgisi",
"menu.code.quickDocumentation": "Hızlı Belgelendirme",
"menu.code.reformat": "Kodu Yeniden Biçimlendir",
"menu.code.showIntentions": "Bağlam Eylemlerini Göster",
"menu.code.shrinkSelection": "Seçimi Daralt",
"menu.code.surroundWith": "Şununla Çevrele…",
"menu.code.unwrap": "Sarmalamayı Kaldır…",
"menu.code.unfoldAll": "Tümünü Genişlet",
"menu.debug.evaluate": "İfadeyi Değerlendir…",
"menu.debug.pause": "Programı Duraklat",
"menu.debug.resume": "Programı Sürdür",
"menu.debug.runToCursor": "İmlece Kadar Çalıştır",
"menu.debug.stepInto": "İçine Adımla",
"menu.debug.stepOut": "Dışına Adımla",
"menu.debug.stepOver": "Üzerinden Adımla",
"menu.debug.toggleBreakpoint": "Satır Kesme Noktasını Aç/Kapat",
"menu.debug.viewBreakpoints": "Kesme Noktalarını Görüntüle…",
"menu.debug.attachToProcess": "İşleme Bağlan…",
"menu.debug.forceStepOver": "Zorla Üzerinden Adımla",
"menu.debug.forceStepInto": "Zorla İçine Adımla",
"menu.debug.smartStepInto": "Akıllı İçine Adımla",
"menu.debug.forceRunToCursor": "Zorla İmlece Kadar Çalıştır",
"menu.debug.showExecutionPoint": "Yürütme Noktasını Göster",
"menu.debug.resetFrame": "Yığın Çerçevesini Sıfırla",
"menu.debug.toggleTemporaryBreakpoint": "Geçici Satır Kesme Noktasını Aç/Kapat",
"menu.debug.toggleMethodBreakpoint": "Metot Kesme Noktasını Aç/Kapat",
"menu.debug.toggleFieldWatchpoint": "Alan İzleme Noktasını Aç/Kapat",
"menu.edit": "Düzenle",
"menu.edit.copy": "Kopyala",
"menu.edit.cut": "Kes",
"menu.edit.paste": "Yapıştır",
"menu.code.pasteFromHistory": "Geçmişten Yapıştır…",
"menu.edit.redo": "Yinele",
"menu.edit.selectAll": "Tümünü Seç",
"menu.edit.undo": "Geri Al",
"menu.editor.copyPath": "Yolu Kopyala",
"menu.code.sortLines": "Satırları Sırala",
"menu.code.reverseLines": "Satırların Sırasını Tersine Çevir",
"menu.editor.toggleColumnSelection": "Sütun Seçim Modu",
"menu.editor.splitDown": "Aşağı Böl",
"menu.editor.splitRight": "Sağa Böl",
"menu.editor.toggleZen": "{distractionFree, select, on {Dikkat Dağıtmayan Moddan Çık} other {Dikkat Dağıtmayan Moda Geç}}",
"menu.editor.unsplit": "Bölmeyi Kaldır",
"menu.file": "Dosya",
"menu.fileProperties": "Dosya Özellikleri",
"menu.newProjectsSetup": "Yeni Proje Ayarları",
"menu.file.newProjectsSettings": "Yeni Projeler için Ayarlar…",
"menu.file.toggleReadOnly": "Dosyayı Salt Okunur / Yazılabilir Yap",
"menu.file.closeProject": "Projeyi Kapat",
"menu.remote.reopenInContainer": "Kapsayıcıda Yeniden Aç",
"menu.remote.reloadEnvironment": "Ortamı Yeniden Yükle",
"menu.file.new": "Dosya…",
"menu.file.newScratchFile": "Geçici Dosya",
"menu.new": "Yeni",
"menu.workspace.create": "Çalışma Alanı…",
"menu.vcs.cloneProject": "Sürüm Kontrolünden Proje…",
"menu.workspace.open": "Çalışma Alanı Aç…",
"menu.workspace.manage": "Çalışma Alanını Yönet…",
"menu.file.newUntitled": "Adsız Dosya",
"menu.file.openInNewWindow": "Yeni Pencerede Aç…",
"menu.file.openFile": "Dosya Aç…",
"menu.remote.connect": "Uzaktan Geliştirme…",
"menu.remote.disconnect": "Uzak Ana Bilgisayar Bağlantısını Kes",
"menu.navigationBar": "Gezinme Çubuğu",
"menu.run.updateApplication": "Uygulamayı Güncelle",
"menu.ssh.startSession": "SSH Oturumu Başlat…",
"menu.ssh.configurations": "SSH Yapılandırmaları…",
"menu.deployment": "Dağıtım",
"menu.deployment.uploadToDefault": "Varsayılan Sunucuya Yükle",
"menu.deployment.uploadTo": "Şuraya Yükle…",
"menu.deployment.downloadFromDefault": "Varsayılan Sunucudan İndir",
"menu.deployment.downloadFrom": "Şuradan İndir…",
"menu.deployment.syncWith": "Dağıtılan Sürümle Eşitle…",
"menu.deployment.deleteFromServer": "Sunucudan Sil",
"menu.deployment.toggleAutoUpload": "Otomatik Yükleme",
"menu.deployment.browseRemoteHost": "Uzak Ana Bilgisayara Göz At",
"menu.deployment.openInBrowser": "Tarayıcıda Aç",
"menu.deployment.configure": "Yapılandırma…",
"menu.window.mergeAllWindows": "Tüm Proje Pencerelerini Birleştir",
"menu.window.detachTab": "Sekmeyi Yeni Pencereye Taşı",
"menu.window.nextTab": "Sonraki Proje Sekmesi",
"menu.window.previousTab": "Önceki Proje Sekmesi",
"menu.project.attach": "Proje Ekle…",
"menu.file.openProject": "Aç…",
"menu.file.save": "Tümünü Kaydet",
"menu.file.projectStructure": "Proje Yapısı…",
"menu.file.settings": "Ayarlar…",
"menu.find": "Bul",
"menu.find.inFile": "Bul…",
"menu.find.inPath": "Dosyalarda Bul…",
"menu.find.replaceInFile": "Değiştir…",
"menu.find.replaceInPath": "Dosyalarda Değiştir…",
"menu.find.showUsages": "Kullanımları Göster",
"menu.find.usages": "Kullanımları Bul",
"menu.completion": "Kod Tamamlama",
"menu.folding": "Kod Katlama",
"menu.code.foldSelection": "Seçimi Katla / Bölgeyi Kaldır",
"menu.git": "Git",
"menu.help": "Yardım",
"menu.mainMenu": "Ana Menü",
"window.caption.minimize": "Simge Durumuna Küçült",
"window.caption.maximize": "Ekranı Kapla",
"window.caption.restore": "Önceki Boyuta Döndür",
"window.caption.close": "Kapat",
"menu.help.keymapReference": "Klavye Kısayolları Başvurusu",
"menu.help.showLog": "{os, select, macos {Günlüğü Finder'da Göster} windows {Günlüğü Dosya Gezgini'nde Göster} other {Günlüğü Dosyalar'da Göster}}",
"menu.native.bringAllToFront": "Tümünü Öne Getir",
"menu.native.copy": "Kopyala",
"menu.native.cut": "Kes",
"menu.native.hide": "OpenIDEA'yı Gizle",
"menu.native.hideOthers": "Diğerlerini Gizle",
"menu.native.minimize": "Simge Durumuna Küçült",
"menu.native.paste": "Yapıştır",
"menu.native.redo": "Yinele",
"menu.native.selectAll": "Tümünü Seç",
"menu.native.services": "Servisler",
"menu.native.showAll": "Tümünü Göster",
"menu.native.undo": "Geri Al",
"menu.native.zoom": "Yakınlaştır",
"menu.navigate": "Gezin",
"menu.navigate.back": "Geri",
"menu.navigate.lastEditLocation": "Son Düzenleme Konumu",
"menu.navigate.nextEditLocation": "Sonraki Düzenleme Konumu",
"menu.navigate.callHierarchy": "Çağrı Hiyerarşisi",
"menu.navigate.declaration": "Bildirim veya Kullanımlar",
"menu.navigate.fileStructure": "Dosya Yapısı",
"menu.navigate.findAction": "Eylem Bul…",
"menu.navigate.forward": "İleri",
"menu.navigate.gotoClass": "Sınıf…",
"menu.navigate.gotoFile": "Dosya…",
"menu.navigate.gotoLine": "Satır/Sütun…",
"menu.navigate.gotoSymbol": "Sembol…",
"menu.navigate.implementation": "Uygulamalar",
"menu.navigate.nextError": "Sonraki Vurgulanan Hata",
"menu.navigate.prevError": "Önceki Vurgulanan Hata",
"menu.navigate.recentFiles": "Son Kullanılan Dosyalar",
"menu.navigate.recentLocations": "Son Konumlar",
"menu.navigate.searchEverywhere": "Her Yerde Ara",
"menu.navigate.selectIn": "Şurada Seç…",
"menu.navigate.showBookmarks": "Yer İmlerini Göster",
"menu.navigate.toggleBookmark": "Yer İmini Aç/Kapat",
"menu.navigate.typeDeclaration": "Tür Bildirimi",
"menu.navigate.typeHierarchy": "Tür Hiyerarşisi",
"menu.navigate.superMethod": "Üst Metot",
"menu.navigate.gotoTest": "Test",
"menu.navigate.relatedSymbol": "İlgili Sembol…",
"menu.navigate.nextMethod": "Sonraki Metot",
"menu.navigate.previousMethod": "Önceki Metot",
"menu.openRecent": "Son Kullanılanları Aç",
"menu.recent.none": "Son Kullanılan Proje Yok",
"menu.refactor": "Yeniden Düzenle",
"menu.refactor.changeSignature": "İmzayı Değiştir…",
"menu.refactor.extractConstant": "Sabit Tanımla…",
"menu.refactor.extractField": "Alan Tanımla…",
"menu.refactor.extractInterface": "Arayüz Çıkar…",
"menu.refactor.extractMethod": "Metot Çıkar…",
"menu.refactor.extractParameter": "Parametre Tanımla…",
"menu.refactor.extractVariable": "Değişken Tanımla…",
"menu.refactor.inline": "Yerine Aç…",
"menu.refactor.move": "Taşı…",
"menu.refactor.pullMembersUp": "Üyeleri Üst Sınıfa Taşı…",
"menu.refactor.pushMembersDown": "Üyeleri Alt Sınıfa Taşı…",
"menu.refactor.rename": "Yeniden Adlandır…",
"menu.refactor.safeDelete": "Güvenli Sil…",
"menu.refactor.thisMenu": "Bunu Yeniden Düzenle…",
"menu.run": "Çalıştır",
"menu.run.chooseConfig": "Çalıştır…",
"menu.run.debug": "Hata Ayıkla",
"menu.run.debugContext": "Bağlam Yapılandırmasında Hata Ayıkla",
"menu.run.coverage": "Kapsam Analiziyle Çalıştır",
"menu.run.profile": "Performans Profili Oluştur",
"menu.coverage.hide": "Kapsam Analizini Gizle",
"menu.debuggingActions": "Hata Ayıklama Eylemleri",
"menu.debug.reloadChangedClasses": "Değiştirilen Sınıfları Yeniden Yükle",
"menu.toolwindow.coverage": "Kapsam Analizi",
"menu.toolwindow.profiler": "Performans Profilleyici",
"menu.run.editConfigs": "Yapılandırmaları Düzenle…",
"menu.run.run": "Çalıştır",
"menu.run.runContext": "Bağlam Yapılandırmasını Çalıştır",
"menu.run.stop": "Durdur",
"menu.toolWindows": "Araç Pencereleri",
"menu.toolwindow.bookmarks": "Yer İmleri",
"menu.toolwindow.commit": "Commit",
"menu.toolwindow.debug": "Hata Ayıkla",
"menu.toolwindow.find": "Bul",
"menu.toolwindow.git": "Git",
"menu.toolwindow.hideAll": "{toolWindows, select, hidden {Araç Pencerelerini Geri Yükle} other {Tüm Araç Pencerelerini Gizle}}",
"menu.toolwindow.problems": "Sorunlar",
"menu.toolwindow.project": "Proje",
"menu.toolwindow.run": "Çalıştır",
"menu.toolwindow.structure": "Yapı",
"menu.toolwindow.terminal": "Terminal",
"terminal.close.title": "'{name}' İşlemi Çalışıyor",
"terminal.close.message": "'{name}' işlemini sonlandırmak istiyor musunuz?",
"terminal.close.terminate": "Sonlandır",
"menu.vcs.annotate": "Git Blame ile Satır Geçmişini Göster",
"menu.vcs.branches": "Dallar…",
"menu.vcs.commit": "Commit Oluştur…",
"menu.vcs.fetch": "Uzak Depodan Getir",
"menu.vcs.localHistory": "Yerel Geçmiş",
"menu.vcs.newBranch": "Yeni Dal…",
"menu.vcs.push": "Uzak Depoya Gönder…",
"menu.vcs.rollback": "Geri Al…",
"menu.vcs.showDiff": "Farkları Göster",
"menu.vcs.showLog": "Git Günlüğünü Göster",
"menu.vcs.stash": "Değişiklikleri Geçici Olarak Sakla…",
"menu.vcs.unstash": "Saklanan Değişiklikleri Geri Yükle…",
"menu.vcs.update": "Projeyi Güncelle…",
"menu.vcs.pull": "Değişiklikleri Çek…",
"menu.vcs.merge": "Birleştir…",
"menu.vcs.rebase": "Rebase Uygula…",
"menu.vcs.newWorktree": "Yeni Worktree…",
"menu.vcs.worktrees": "Worktree'ler…",
"menu.vcs.manageRemotes": "Uzak Depoları Yönet…",
"menu.vcs.clone": "Klonla…",
"menu.vcs.operations": "Sürüm Kontrolü İşlemleri Menüsü…",
"menu.view": "Görünüm",
"menu.view.notifications": "Bildirimler",
"menu.view.toggleTheme": "Açık/Koyu Temayı Değiştir",
"menu.welcome.recentProjects": "Projeleri Yönet…",
"menu.window": "Pencere",
"menu.tools": "Araçlar",
"menu.http.newRequest": "Yeni HTTP İsteği",
"menu.http.showToolWindow": "HTTP İstemcisi",
"menu.db.showToolWindow": "Veritabanı",
"menu.db.newDataSource": "Yeni Veri Kaynağı…",
"menu.db.openConsole": "Sorgu Konsolunu Aç",
"menu.vim.toggle": "Vim",
"menu.window.new": "Yeni Pencere",
"menu.window.next": "Sonraki Proje Penceresi",
"menu.window.previous": "Önceki Proje Penceresi",
"menu.window.toggleFullScreen": "Tam Ekranı Aç/Kapat",
"os.linux": "Linux",
"os.macos": "macOS",
"os.web": "Tarayıcı",
"os.windows": "Windows",
"menu.gitPatch": "Yama",
"menu.vcs.newTag": "Yeni Etiket…",
"menu.vcs.resetHead": "HEAD'i Sıfırla…",
"menu.vcs.shelve": "Değişiklikleri Rafa Kaldır…",
"menu.vcs.showShelf": "Rafı Göster",
"menu.vcs.createPatch": "Yama Oluştur…",
"menu.vcs.applyPatch": "Yama Uygula…",
"menu.vcs.applyPatchFromClipboard": "Panodan Yama Uygula…",
"menu.vcs.resolveConflicts": "Çakışmaları Çöz…",
"menu.vcs.rebase.continue": "Rebase İşlemine Devam Et",
"menu.vcs.rebase.abort": "Rebase İşlemini İptal Et",
"menu.vcs.rebase.skip": "Commit'i Atla",
"menu.vcs.merge.abort": "Birleştirmeyi İptal Et",
"menu.vcs.cherryPick.continue": "Cherry-Pick İşlemine Devam Et",
"menu.vcs.cherryPick.abort": "Cherry-Pick İşlemini İptal Et",
"menu.vcs.revert.continue": "Geri Alma İşlemine Devam Et",
"menu.vcs.revert.abort": "Geri Alma İşlemini İptal Et",
"menu.gitUncommittedChanges": "Commit Edilmemiş Değişiklikler",
"menu.gitCurrentFile": "Geçerli Dosya",
"menu.vcs.addToVcs": "Sürüm Kontrolüne Ekle",
"menu.vcs.compareWithBranch": "Dal veya Revizyonla Karşılaştır…",
"menu.vcs.showHistory": "Geçmişi Göster",
"menu.vcs.showHistoryForSelection": "Seçimin Geçmişini Göster",
"menu.build": "Derleme",
"menu.build.buildProject": "Projeyi Derle",
"menu.build.buildModule": "Modülü Derle",
"menu.build.rebuildProject": "Projeyi Yeniden Derle",
"menu.build.buildArtifacts": "Çıktıları Derle",
"menu.toolwindow.build": "Derleme",
"menu.find.structural": "Yapısal Ara…",
"menu.find.replaceStructural": "Yapısal Değiştir…",
"menu.analyze.inspectCode": "Kodu İncele…",
"menu.analyzeCode": "Kod Analizi",
"menu.analyze.locateDuplicates": "Yinelenen Kodları Bul…",
"menu.analyze.stackTrace": "Yığın İzini veya İş Parçacığı Dökümünü Analiz Et…",
"menu.toolwindow.services": "Servisler",
"menu.gitHub": "GitHub",
"menu.github.pullRequests": "Pull Request'leri Görüntüle",
"menu.github.createPullRequest": "Pull Request Oluştur…",
"menu.github.checkoutPullRequest": "Pull Request'e Geç…",
"menu.github.openInBrowser": "GitHub'da Aç",
"menu.file.newProject": "Proje…",
"menu.file.renameProject": "Projeyi Yeniden Adlandır…",
"menu.file.reloadAllFromDisk": "Tümünü Diskten Yeniden Yükle",
"menu.file.invalidateCaches": "Önbellekleri Geçersiz Kıl…",
"menu.manageIdeSettings": "IDE Ayarlarını Yönet",
"menu.file.exportSettings": "Ayarları Dışa Aktar…",
"menu.file.importSettings": "Ayarları İçe Aktar…",
"menu.file.importJetBrainsSettings": "JetBrains IDE'den Ayarları İçe Aktar…",
"menu.file.togglePowerSave": "Güç Tasarrufu Modu",
"menu.macros": "Makrolar",
"menu.macro.startRecording": "Makro Kaydını Başlat",
"menu.macro.stopRecording": "Makro Kaydını Durdur",
"menu.macro.playBack": "Son Makroyu Oynat",
"menu.macro.playSaved": "Kayıtlı Makroları Oynat…",
"menu.macro.edit": "Makroları Düzenle…",
"menu.bookmarks": "Yer İmleri",
"menu.navigate.toggleBookmarkWithMnemonic": "Kısayol Harfiyle Yer İmini Aç/Kapat",
"menu.navigate.nextBookmark": "Sonraki Yer İmi",
"menu.navigate.prevBookmark": "Önceki Yer İmi",
"menu.view.toggleCompactMode": "Kompakt Mod",
"menu.view.togglePresentationAssistant": "Sunum Yardımcısı",
"menu.view.zoomIn": "IDE'yi Yakınlaştır",
"menu.view.zoomOut": "IDE'yi Uzaklaştır",
"menu.view.resetZoom": "IDE Yakınlaştırmasını Sıfırla",
"menu.toolbar.customize": "Ana Araç Çubuğunu Özelleştir…",
"menu.view.toggleToolbar": "Araç Çubuğu",
"menu.view.toggleToolWindowBars": "Araç Penceresi Çubukları",
"menu.view.toggleStatusBar": "Durum Çubuğu",
"menu.view.navigationBar": "Gezinme Çubuğu",
"menu.view.navigationBarTop": "Üst",
"menu.view.navigationBarStatusBar": "Durum Çubuğu",
"menu.view.navigationBarHidden": "Gösterme",
"menu.statusBarWidgets": "Durum Çubuğu Bileşenleri",
"menu.code.quickDefinition": "Hızlı Tanım",
"menu.code.quickTypeDefinition": "Hızlı Tür Tanımı",
"menu.localHistory.recentChanges": "Son Değişiklikler",
"menu.diff.compareWithClipboard": "Panoyla Karşılaştır",
"menu.view.quickSwitchScheme": "Hızlı Şema Değiştir…",
"menu.editor.resetFontSize": "Yazı Tipi Boyutunu Sıfırla",
"menu.editor.resetFontSizeAll": "Tüm Düzenleyicilerde Yazı Tipi Boyutunu Sıfırla",
"menu.code.cleanup": "Kod Temizliği…",
"menu.runAnything.show": "Her Şeyi Çalıştır…",
"menu.localHistory.putLabel": "Etiket Ekle…",
"menu.toolWindowLayouts": "Araç Penceresi Düzenleri",
"menu.layout.saveCurrent": "Geçerli Düzendeki Değişiklikleri Kaydet",
"menu.layout.restoreCurrent": "Geçerli Düzeni Geri Yükle",
"menu.layout.save": "Geçerli Düzeni Farklı Kaydet…",
"menu.layout.restoreDefault": "Varsayılan Düzeni Geri Yükle",
"menu.layout.rename": "Düzeni Yeniden Adlandır…",
"menu.layout.delete": "Düzeni Sil…",
"menu.activeToolWindow": "Etkin Araç Penceresi",
"menu.toolwindow.hideActive": "Etkin Araç Penceresini Gizle",
"menu.toolwindow.maximize": "Araç Penceresini Ekranı Kaplayacak Şekilde Büyüt",
"menu.toolwindow.closeContent": "Etkin Sekmeyi Kapat",
"menu.toolwindow.jumpToLast": "Son Araç Penceresine Git",
"menu.toolwindow.focusEditor": "Düzenleyiciye Odaklan",
"menu.editorTabs": "Düzenleyici Sekmeleri",
"menu.editor.nextTab": "Sonraki Sekmeyi Seç",
"menu.editor.prevTab": "Önceki Sekmeyi Seç",
"menu.editor.pinTab": "Sekmeyi Sabitle",
"menu.editor.closeTab": "Sekmeyi Kapat",
"menu.editor.closeOtherTabs": "Diğer Sekmeleri Kapat",
"menu.editor.closeAllTabs": "Tüm Sekmeleri Kapat",
"menu.editor.reopenClosedTab": "Kapatılan Sekmeyi Yeniden Aç",
"menu.editor.moveToOppositeGroup": "Karşı Gruba Taşı",
"menu.editor.openInOppositeGroup": "Karşı Grupta Aç",
"menu.editor.changeSplitOrientation": "Bölme Yönünü Değiştir",
"menu.editor.unsplitAll": "Tüm Bölmeleri Kaldır",
"menu.navigate.showFilePath": "Dosya Yolu",
"menu.navigate.customRegion": "Özel Katlama…",
"menu.code.showErrorDescription": "Hata Açıklaması",
"menu.code.surroundWithLiveTemplate": "Canlı Şablonla Çevrele…",
"menu.code.autoIndentLines": "Satırları Otomatik Girintile",
"menu.code.moveStatementUp": "İfadeyi Yukarı Taşı",
"menu.code.moveStatementDown": "İfadeyi Aşağı Taşı",
"menu.code.moveElementLeft": "Öğeyi Sola Taşı",
"menu.code.moveElementRight": "Öğeyi Sağa Taşı",
"menu.code.collapseBlock": "Kod Bloğunu Katla",
"menu.analyze.inspectFile": "Geçerli Dosyayı İncele",
"menu.project.copyElement": "Kopyala…",
"menu.run.chooseDebugConfig": "Hata Ayıkla…",
"menu.debug.quickEvaluate": "İfadeyi Hızlı Değerlendir",
"menu.resizeToolWindow": "Yeniden Boyutlandır",
"menu.toolwindow.resizeLeft": "Sola Doğru Genişlet",
"menu.toolwindow.resizeRight": "Sağa Doğru Genişlet",
"menu.toolwindow.resizeUp": "Yukarı Doğru Genişlet",
"menu.toolwindow.resizeDown": "Aşağı Doğru Genişlet",
"menu.editor.nextSplitter": "Sonraki Bölmeye Git",
"menu.editor.prevSplitter": "Önceki Bölmeye Git",
"menu.expandToLevel": "Düzeye Kadar Genişlet",
"menu.expandAllToLevel": "Tümünü Düzeye Kadar Genişlet",
"menu.code.expandToLevel1": "1",
"menu.code.expandAllToLevel1": "1",
"menu.code.expandToLevel2": "2",
"menu.code.expandAllToLevel2": "2",
"menu.code.expandToLevel3": "3",
"menu.code.expandAllToLevel3": "3",
"menu.code.expandToLevel4": "4",
"menu.code.expandAllToLevel4": "4",
"menu.code.expandToLevel5": "5",
"menu.code.expandAllToLevel5": "5",
"menu.editor.contextInfo": "Bağlam Bilgisi",
"run.services.configurationCount": "{count} yapılandırma",
"search.bookmarks.count": "{count, plural, one {# yer imi} other {# yer imi}}",
"search.find.matches": "{matches, plural, one {# eşleşme} other {# eşleşme}}; {files, plural, one {# dosyada} other {# dosyada}}",
"search.find.matchesIncomplete": "{matches, plural, one {#+ eşleşme} other {#+ eşleşme}}; {files, plural, one {#+ dosyada} other {#+ dosyada}}",
"settings.zoom.hint": "{zoomIn} veya {zoomOut} ile değiştirin. {reset} ile %100'e sıfırlayın"
}