Compare commits

...
Author SHA1 Message Date
l0ng-ai 4f755d55de test(e2e): wait for the Run window to take focus before toggling it
The tool-window shortcut hides a window only once it is active, and
activation focuses it on the next frame. Under load the test pressed ⌘4 or
Shift+Escape before that, so the window stayed open.
2026-11-21 04:26:44 +08:00
l0ng-ai 97f78908a1 fix(terminal): don't take focus that moved elsewhere while the view loaded (#4899)
A focus request made before xterm opened was applied whenever it opened, so a terminal still loading took the caret back from a view the user had clicked meanwhile. The deferred focus now applies only while focus is where it was when requested, on the page, or inside the terminal's own tool window.
2026-11-21 04:23:06 +08:00
faysouandfaysou e7aec17d46 Match backtick runs in protected inline Markdown math (#4895)
Protected inline math ($`...`$) now matches the opening backtick run to the first closing run of the same length, as Markdown code spans do: ($``x` + y``$) renders as math, while ($`x` `y`$) keeps two code spans and literal dollars.

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

Co-authored-by: faysou <[email protected]>
2026-11-21 03:56:06 +08:00
l0ng-ai cb24f252c5 fix(vcs): keep focus on the commit message when the Commit window opens (#4896)
Activating a tool window focuses its first field or tree on the next frame unless its content marks a data-autofocus target. The Commit window's message wasn't marked, so after Cmd+K focused the message, activation could move focus to the Changes tree depending on timing. The message is now the window's preferred focus, also when the window is activated from its stripe button.
2026-11-21 03:55:28 +08:00
faysouandfaysou 8557b8d21e feat(vcs): make default Commit inclusion configurable (#4864)
Settings > Version Control > Commit gets Include changes in the commit by default. It is on by default, which keeps the current behaviour (the active changelist's changes start checked). Turned off, the Commit view starts with every file unchecked, partially staged files included. Explicit selections still apply, and staging-area mode still follows the Git index.

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

Co-authored-by: faysou <[email protected]>
2026-11-21 03:32:16 +08:00
l0ng-ai 99a8f8feaa fix(completion): put the caret inside a Kotlin call that takes arguments (#4888)
Refs #3447

kotlin-lsp inserts a picked item itself, parentheses included, and the caret was moved after the whole edit (read()| for read(name: String)), so typed arguments went after the call. When the item's signature lists parameters and the server's edit ends with (), the caret now goes between the parentheses, as it does for items inserted on the client.
2026-11-21 02:50:55 +08:00
l0ng-ai 4b76566af4 fix(editor): write failed saves to the log with their stack (#4887)
Refs #3447

A failed save only showed its message in the Could not save notification, and a failed autosave of a closed tab went to the console. Both are now written to the log file with their stack, so a report's log shows where the save failed.
2026-11-21 02:49:14 +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 LazukandInf1mum 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
Ernstjan FreriksandEjaYF 745038b4e2 fix(markdown): zoom preview images with ⌘/Ctrl+wheel like Mermaid diagrams (#4729)
Images in the Markdown preview get the pan/zoom Mermaid diagrams already have: Cmd/Ctrl+wheel zooms the image at the cursor, drag pans once zoomed, double-click resets; the image keeps its place and size in the page and font zoom still scales it.

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

Co-authored-by: EjaYF <[email protected]>
2026-11-21 01:41:13 +08:00
Vladislav Kuzmin 3c3b26b419 fix(settings): wrap radio labels in narrow System Settings (#4841)
In a narrow Settings window, System Settings clipped the Open project in radio labels because they could not wrap; the labels now wrap within the group.

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

Co-authored-by: principalwater <[email protected]>
2026-11-21 01:39:48 +08:00
ntbang0901 1189a71205 fix(search): match Words like IntelliJ when the text starts or ends with punctuation (#4873)
With Words on, Find and Replace in Files missed matches whose text starts or ends with punctuation (doWork( in doWork(arg), [] in string[]) because ripgrep's word rule wants non-word characters on both sides. The whole-word check now follows the editor's rule: an identifier-character edge must not touch another identifier character (escapes like \n excepted), any other edge only needs a different neighbour, and a rejected match is retried from its next character; it sits in the shared match iteration so search, Replace, match_ranges and replace_in_text agree. $ counts as an identifier character.

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

Co-authored-by: ntbang0901 <[email protected]>
2026-11-21 01:38:57 +08:00
ntbang0901 f27dea2d8a fix(search): Replace All past the match limit keeps to the search context (#4872)
Replace All after the search hit its match limit ignored the Search Context (e.g. In Comments also rewrote code and string literals): past the limit the scope is searched again to find files, and the replace step had no comment/string filter. The filter now lives in SearchContext::keeps, used by both the search engine and replace_files_in_context, with comments and string literals from the same literals_of in ide-host.

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

Co-authored-by: ntbang0901 <[email protected]>
2026-11-21 01:37:09 +08:00
ntbang0901 7b5ff4e4b5 fix(search): list and replace every match of a very long line (#4871)
Find in Files dropped every match outside the window kept around the first match of a line longer than 500 UTF-16 units, so long lines showed one match and Replace All replaced only that one. Such a line now yields one LineMatch per window, so each match is listed, counted, navigable and replaceable with its own context; result rows are keyed by line and column, and the MCP text search matches each long line once.

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

Co-authored-by: ntbang0901 <[email protected]>
2026-11-21 01:33:56 +08:00
ntbang0901 e94dc1baae fix(refactor): keep editors on files a refactoring renames or moves (#4868)
Renaming or moving a class through a refactoring closed the editor of the old file and never opened the new one: workspace edits applied through Documents::apply_workspace_edit_as reported only the affected paths, so the editor saw just the watcher's removal. WorkspaceEditApplied now carries the edit's file moves, and WorkspaceHistory makes open editors follow them on apply, Undo and Redo using the Project view's helper (moved to src/editor/fileMoves.ts), which now waits for the old tab to close before reopening and settles the record before reopening on Undo/Redo.

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

Co-authored-by: ntbang0901 <[email protected]>
2026-11-21 01:30:12 +08:00
l0ng-ai 3228da223e fix(build): align the Dependency Analyzer panes (#4856)
Dependency Analyzer keeps module selection, search, scope or configuration, and conflict filtering in the main toolbar; the pane headers align the resolved dependency list with the selected dependency's usages, with list and tree controls beside the list, and narrow editors stack both panes.
2026-11-21 01:28:47 +08:00
ntbang0901 332334fb4f fix(outline): show type aliases a language server reports as variables (#4869)
TypeScript type aliases showed as variables in the Structure view and breadcrumbs, and Rust type aliases / associated types had no usages lens, because LSP has no kind for type aliases and servers report Variable or TypeParameter. doc_outline now takes the syntax tree's type kind (merge_kinds) where the server reported one of those placeholder kinds for a declaration the syntax outline types at the same name and position.

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

Co-authored-by: ntbang0901 <[email protected]>
2026-11-21 01:26:41 +08:00
ntbang0901 047ec9d6bc fix(navigation): name a target's container only from a type whose body holds it (#4870)
Navigation choosers and gutter marker names took a target's container from the nearest type declaration above it without checking that its body was still open, so targets after a closed type got that type's name. enclosingType now uses a declaration only when its body holds the target: brace bodies count braces up to the target column (ignoring string literals), others use indentation; Go methods still use their receiver.

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

Co-authored-by: ntbang0901 <[email protected]>
2026-11-21 01:25:20 +08:00
ntbang0901 912c710096 fix(agents): open binary session artifacts through the checked backend command (#4866)
Clicking a binary artifact (Word, Excel...) in an agent session's Artifacts popup always opened it as text: SessionAssets called the opener plugin's openPath, which the app capability does not grant. It now goes through fs_open_with_system, the checked command Open in Associated Application uses (local window, trusted project, existing file inside the project or its content roots), and still falls back to the editor when the backend refuses.

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

Co-authored-by: ntbang0901 <[email protected]>
2026-11-21 01:24:27 +08:00
ntbang0901 38f1c4810c fix(run): rerun a root Gradle test run's failed tests in their own subprojects (#4862)
After a run of a multi-project Gradle build's plain test task, Rerun Failed Tests and running a selection from the test tree put every --tests filter on that plain task, so the first subproject without a match failed the build. Each failed class is now resolved to its module (the source lookup Application configurations use, now classModules) and its filter goes on that subproject's own test task (:alpha:test --tests A :beta:test --tests B --continue); the command line is unchanged when a class is not found in exactly one module, all tests are the root project's, or the run already names a task.

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

Co-authored-by: ntbang0901 <[email protected]>
2026-11-21 01:23:57 +08:00
l0ng-ai 7fe7ec0fea style(cucumber): format the Python step files (#4877)
Runs oxfmt on the Python step files from #4859, which were merged unformatted and failed pnpm format:check on main.
2026-11-21 01:22:37 +08:00
118 changed files with 14518 additions and 365 deletions

No files matched your search

+178 -14
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -334,6 +334,31 @@ fn str_param<'a>(params: &'a Value, key: &str) -> Result<&'a str, ResponseError>
params.get(key).and_then(Value::as_str).ok_or_else(|| invalid(format!("missing {key}")))
}
/// Fills a `thread/start`/`thread/resume`/`thread/fork` request's `config` with the session's
/// MCP servers and its staged skills: the off ones, by path (`skills.config` entries with
/// `enabled = false`, which the CLI honors for the copies it discovers natively too).
fn apply_thread_config(params: &Value, request: &mut Value) {
let mut config = translate::mcp_config(params).unwrap_or_else(|| json!({}));
let off: Vec<Value> = params
.pointer("/_meta/openidea/skills/codexOff")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(|entry| {
let path = entry.get(1)?.as_str()?;
Some(json!({ "path": path, "enabled": false }))
})
.collect();
if !off.is_empty()
&& let Some(map) = config.as_object_mut()
{
map.insert("skills".into(), json!({ "config": off }));
}
if !config.as_object().is_some_and(|m| m.is_empty()) {
request["config"] = config;
}
}
impl CodexShim {
fn codex(&self) -> &Peer {
self.codex.get().expect("attached before any message")
@@ -414,6 +439,31 @@ impl CodexShim {
}
}
/// Hands the session's staged skills to the app-server: the farm's `codex` tree joins
/// its discovery roots. Best-effort: a CLI version without `skills/extraRoots/set`
/// (the method arrived later than some pinned installs) runs without the farm, as
/// before.
async fn apply_skill_roots(&self, session: &str, params: &Value) {
let roots = params
.pointer("/_meta/openidea/skills/codexExtraRoots")
.and_then(Value::as_array)
.map(|a| a.iter().filter_map(Value::as_str).collect::<Vec<_>>())
.unwrap_or_default();
if roots.is_empty() {
return;
}
let set = tokio::time::timeout(
Duration::from_secs(5),
self.call("skills/extraRoots/set", json!({ "extraRoots": roots })),
)
.await;
match set {
Ok(Ok(_)) => {}
Ok(Err(e)) => tracing::info!("codex session {session}: could not set the extra skill roots: {}", e.message),
Err(e) => tracing::info!("codex session {session}: could not set the extra skill roots: {e}"),
}
}
/// Registers a thread codex opened for a session of its own; returns its `configOptions`.
fn open_thread(&self, result: &Value, models: &[ModelInfo], settings: Option<Settings>) -> (String, Value) {
let thread = result.get("thread").unwrap_or(&Value::Null);
@@ -434,14 +484,13 @@ impl CodexShim {
let models = self.models().await?;
self.prepare_project_trust(params).await;
let mut request = json!({ "cwd": params.get("cwd") });
if let Some(config) = translate::mcp_config(params) {
request["config"] = config;
}
apply_thread_config(params, &mut request);
let result = self.call("thread/start", request).await?;
let (id, options) = self.open_thread(&result, &models, None);
if id.is_empty() {
return Err(error(codes::INTERNAL_ERROR, "codex started no thread"));
}
self.apply_skill_roots(&id, params).await;
self.publish_skills(&id).await;
Ok(json!({ "sessionId": id, "configOptions": options }))
}
@@ -452,9 +501,7 @@ impl CodexShim {
let models = self.models().await?;
self.prepare_project_trust(params).await;
let mut request = json!({ "threadId": id, "cwd": params.get("cwd") });
if let Some(config) = translate::mcp_config(params) {
request["config"] = config;
}
apply_thread_config(params, &mut request);
let result = self.call("thread/resume", request).await?;
let (_, options) = self.open_thread(&result, &models, None);
let cwd = self.state.lock().threads.get(id).and_then(|t| t.cwd.clone());
@@ -462,6 +509,7 @@ impl CodexShim {
for update in translate::history(thread, cwd.as_deref()) {
self.emit(id, update);
}
self.apply_skill_roots(id, params).await;
self.publish_skills(id).await;
Ok(json!({ "configOptions": options }))
}
@@ -472,9 +520,7 @@ impl CodexShim {
self.prepare_project_trust(params).await;
let settings = self.state.lock().threads.get(source).and_then(|t| t.settings.clone());
let mut request = json!({ "threadId": source, "cwd": params.get("cwd") });
if let Some(config) = translate::mcp_config(params) {
request["config"] = config;
}
apply_thread_config(params, &mut request);
if let Some(s) = &settings {
request["model"] = json!(s.model_slug(&models));
request["approvalPolicy"] = json!(s.mode.approval_policy());
@@ -482,6 +528,7 @@ impl CodexShim {
}
let result = self.call("thread/fork", request).await?;
let (id, options) = self.open_thread(&result, &models, settings);
self.apply_skill_roots(&id, params).await;
self.publish_skills(&id).await;
Ok(json!({ "sessionId": id, "configOptions": options }))
}
@@ -372,6 +372,24 @@ fn error(code: i64, message: impl Into<String>) -> ResponseError {
ResponseError { code, message: message.into(), data: None }
}
/// Adds the session's staged skills to a `session.create`/`session.resume` request:
/// `skillDirectories` (the farm's `copilot` tree) and `disabledSkills` (the off and
/// slash-only ones; Copilot invokes skills with the model only, so a slash-only skill has
/// no other switch here).
fn apply_skills(params: &Value, req: &mut Value) {
let skills = params.pointer("/_meta/openidea/skills");
if let Some(dirs) = skills.and_then(|s| s.get("copilotSkillDirectories")).and_then(Value::as_array)
&& !dirs.is_empty()
{
req["skillDirectories"] = json!(dirs.iter().filter_map(Value::as_str).collect::<Vec<_>>());
}
if let Some(disabled) = skills.and_then(|s| s.get("copilotDisabledSkills")).and_then(Value::as_array)
&& !disabled.is_empty()
{
req["disabledSkills"] = json!(disabled.iter().filter_map(Value::as_str).collect::<Vec<_>>());
}
}
fn invalid(message: impl Into<String>) -> ResponseError {
error(codes::INVALID_PARAMS, message)
}
@@ -496,6 +514,7 @@ impl CopilotShim {
if let Some(disabled) = translate::wire_disabled_mcp_servers(params) {
req["disabledMcpServers"] = disabled;
}
apply_skills(params, &mut req);
let created = self.call("session.create", req).await?;
let session_id = created
@@ -546,6 +565,7 @@ impl CopilotShim {
if let Some(disabled) = translate::wire_disabled_mcp_servers(params) {
req["disabledMcpServers"] = disabled;
}
apply_skills(params, &mut req);
let resumed = self.call("session.resume", req).await?;
if let Ok(current) = self.call("session.model.getCurrent", json!({ "sessionId": session_id })).await {
+604 -7
View File
@@ -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
View File
@@ -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());
}
+2
View File
@@ -102,6 +102,8 @@ pub enum IdeEvent {
WorkspaceEditApplied {
id: u32,
paths: Vec<crate::IpcPath>,
/// Files the edit renamed, as the edit named them: editors open on them follow.
moves: Vec<crate::FileMove>,
/// Made by an agent through the MCP server's tools: undoable like a refactoring, but
/// not announced as one.
by_agent: bool,
+34
View File
@@ -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>
+19
View File
@@ -110,6 +110,17 @@ pub struct WorkspaceEditPrecondition {
}
impl WorkspaceEdit {
/// The files and folders the edit renames, in order.
pub fn moves(&self) -> Vec<FileMove> {
self.files
.iter()
.filter_map(|f| match f {
FileEdit::Rename { from, to } => Some(FileMove { from: from.clone(), to: to.clone() }),
_ => None,
})
.collect()
}
/// Coalesces aliases of the same file before applying edits against its original text.
/// Resource operations separate batches because later edits may use the new contents.
pub fn deduplicate(&mut self) {
@@ -184,6 +195,14 @@ pub enum FileEdit {
},
}
/// One file or folder move.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct FileMove {
pub from: crate::IpcPath,
pub to: crate::IpcPath,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum Severity {
+2
View File
@@ -151,6 +151,7 @@ pub struct CommitSettings {
/// Commit from the Commit tool window; off = Local Changes in the Git tool
/// window and a Commit dialog.
pub non_modal: bool,
pub include_changes_by_default: bool,
/// Start with an empty message instead of the last one / the changelist's.
pub clear_initial_message: bool,
pub analyze_code: bool,
@@ -190,6 +191,7 @@ impl Default for CommitSettings {
fn default() -> Self {
Self {
non_modal: true,
include_changes_by_default: true,
clear_initial_message: false,
analyze_code: true,
check_todo: true,
+2 -2
View File
@@ -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(),
+7 -3
View File
@@ -668,8 +668,8 @@ async fn text_search(call: Call, is_regex: bool) -> IdeResult<Output> {
if hits.len() > limit {
break;
}
// Find in Files keeps a window of very long lines and drops the matches outside it:
// such lines are matched again in the file's whole text.
// Find in Files reports a very long line in windows cut around its matches: such lines
// are matched again in the file's whole text, so a match keeps its real end.
let long = |m: &ide_search::LineMatch| m.text_offset > 0 || m.text.encode_utf16().count() + 1 >= LINE_WINDOW;
let whole = if file.matches.iter().any(long) {
crate::ops::fs::fs_read_text(&host, call.window(), file.path.0.clone())
@@ -679,11 +679,15 @@ async fn text_search(call: Call, is_regex: bool) -> IdeResult<Output> {
} else {
None
};
// One window per far-apart match: a line is expanded once.
let mut expanded = std::collections::HashSet::new();
for m in &file.matches {
if let Some((ranges, text)) = &whole
&& long(m)
{
hits.extend(line_hits(path, text, ranges, m.line));
if expanded.insert(m.line) {
hits.extend(line_hits(path, text, ranges, m.line));
}
continue;
}
let line_end = m.text_offset + m.text.encode_utf16().count() as u32;
+148 -2
View File
@@ -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 -3
View File
@@ -85,7 +85,7 @@ pub async fn doc_set_line_ending(host: &Host, window: &str, doc: DocId, line_end
}
/// Structure view: LSP document symbols when available (with tree-sitter
/// visibility), tree-sitter otherwise.
/// visibility and type-alias kinds), tree-sitter otherwise.
/// Tree-sitter answers come from the per-document tree cache (incremental
/// re-parse); large documents get no syntax structure.
#[command(trust = always)]
@@ -113,10 +113,13 @@ pub async fn doc_outline(host: &Host, window: &str, doc: DocId) -> IdeResult<Vec
};
let syntax = || project.syntax.outline(doc, &snap.language, snap.version, &snap.text);
Ok(match lsp {
// Server symbols carry no visibility; borrow it from the syntax tree.
// Server symbols carry no visibility, nor a kind for type aliases; borrow them from
// the syntax tree.
Some(mut items) => {
if !snap.large {
ide_language::merge_visibility(&mut items, &syntax());
let syntax = syntax();
ide_language::merge_visibility(&mut items, &syntax);
ide_language::merge_kinds(&mut items, &syntax);
}
items
}
+6
View File
@@ -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"
+12 -4
View File
@@ -22,6 +22,17 @@ pub fn literal_range(l: ide_language::Literal) -> ide_search::LiteralRange {
ide_search::LiteralRange { start: l.start, end: l.end, kind }
}
/// Comments and string literals of `text`, for the search context of Find and Replace in Files.
pub(crate) fn literals_of(
project: &crate::project::Project,
syntax: &ide_language::Syntax,
path: &Path,
text: &str,
) -> Option<Vec<ide_search::LiteralRange>> {
let language = project.languages.detect(path, text.lines().next());
Some(syntax.literals(&language, text)?.into_iter().map(literal_range).collect())
}
/// Find in Files. Results stream through `on_event`; ends with `Done`.
/// Cancel with `cancel_request(request)`.
#[command(trust = always)]
@@ -98,10 +109,7 @@ pub(crate) fn search_project(
Some(ProjectFileSet::Test) => roots.is_test(rel),
_ => true,
};
let literals = |path: &Path, text: &str| {
let language = project.languages.detect(path, text.lines().next());
Some(syntax.literals(&language, text)?.into_iter().map(literal_range).collect())
};
let literals = |path: &Path, text: &str| literals_of(project, syntax, path, text);
let defaults = project.documents.file_defaults();
let decode = |path: &Path, bytes: &[u8]| ide_vfs::decode_text(bytes, defaults.fallback_for(path));
let mut total = SearchSummary::default();
+13 -3
View File
@@ -75,9 +75,19 @@ pub async fn replace_in_files(
let summary = tokio::task::spawn_blocking(move || {
let targets = if all_in_scope { scope_targets(&project, &syntax, &query, targets, &cancel)? } else { targets };
let host = DocumentsHost(&project.documents);
ide_search::replace_files(&host, &query, &replacement, preserve_case, &targets, &cancel, &|e| {
let _ = events.send(e);
})
let literals = |path: &Path, text: &str| super::literals_of(&project, &syntax, path, text);
ide_search::replace_files_in_context(
&host,
&query,
&replacement,
preserve_case,
&targets,
Some(&literals),
&cancel,
&|e| {
let _ = events.send(e);
},
)
})
.await
.map_err(|e| ide_core::IdeError::internal(e.to_string()));
+13
View File
@@ -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)
}));
+13
View File
@@ -187,6 +187,19 @@ async fn reads_unsaved_text_and_searches_the_overlay_with_a_limit() {
assert_eq!(std::fs::read_to_string(h.root.join("src/a.txt")).unwrap(), "old text\nneedle needle\n");
}
#[tokio::test(flavor = "multi_thread")]
async fn every_match_of_a_long_line_is_found_once() {
let h = Harness::new();
std::fs::write(
h.root.join("src/min.js"),
format!("a=1;{}b='longneedle';{}longneedle\n", "x".repeat(2000), "y".repeat(2000)),
)
.unwrap();
let found = h.json("search_text", json!({"q":"longneedle","limit":20})).await;
let columns: Vec<_> = found["items"].as_array().unwrap().iter().map(|i| i["startColumn"].clone()).collect();
assert_eq!(columns, [json!(2008), json!(4020)], "{found}");
}
#[tokio::test(flavor = "multi_thread")]
async fn window_reports_supply_editor_selection_and_problems_then_disappear_on_close() {
let h = Harness::new();
+53
View File
@@ -195,3 +195,56 @@ async fn replace_all_saves_open_buffers_without_unsaved_changes() {
assert_eq!(project.documents.text_snapshot(edited).unwrap().text, "DONE\nmore\n");
host.close_project("main");
}
/// Replace All past the limit replaces what the search lists: only the matches its Search
/// Context keeps (comments, string literals or code), as below the limit.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn replace_all_past_the_limit_keeps_to_the_search_context() {
use ide_search::SearchContext as C;
let comments = |word: &str| lines(2001, &format!("// {word}"));
let code = |name: &str, string: &str| format!("fn {name}() -> &'static str {{ \"{string}\" }}\n");
let original = format!("{}{}", comments("tok"), code("tok", "tok"));
let cases = [
(C::Any, format!("{}{}", comments("X"), code("X", "X"))),
(C::InComments, format!("{}{}", comments("X"), code("tok", "tok"))),
(C::InStringLiterals, format!("{}{}", comments("tok"), code("tok", "X"))),
(C::ExceptComments, format!("{}{}", comments("tok"), code("X", "X"))),
(C::ExceptStringLiterals, format!("{}{}", comments("X"), code("X", "tok"))),
(C::ExceptCommentsAndStringLiterals, format!("{}{}", comments("tok"), code("X", "tok"))),
];
for (context, expected) in cases {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
std::fs::create_dir_all(&root).unwrap();
std::fs::write(root.join("lib.rs"), &original).unwrap();
let host = Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(NullSink)),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
});
host.trust.decide(&root, true, false).unwrap();
host.open_project("main", &root).unwrap();
ops::search::replace_in_files(
&host,
"main",
RequestId::next(),
SearchQuery { context, ..query("tok", false) },
"X".into(),
false,
vec![],
true,
ops::Channel::new(|_| {}),
)
.await
.unwrap();
assert_eq!(std::fs::read_to_string(root.join("lib.rs")).unwrap(), expected, "{context:?}");
host.close_project("main");
}
}
+1 -1
View File
@@ -25,7 +25,7 @@ pub use syntax::{
CSS_CLASS, CSS_ID, CSS_VARIABLE, ClassBases, ConfigurationKey, ExternalFold, ExternalSymbol, ExternalSyntax,
ExternalToken, FileReference, Literal, LiteralKind, MAX_CACHED_TREES, MAX_PARSE_BYTES, ParsedTree, SpellingKind,
SpellingRegion, Syntax, SyntaxCache, SyntaxCacheStats, SyntaxHighlightKind, SyntaxHighlights, TreeError,
VueComponentImport, VueRefAccess, VueRefElement, WebReference, WebReferenceKind, merge_visibility,
VueComponentImport, VueRefAccess, VueRefElement, WebReference, WebReferenceKind, merge_kinds, merge_visibility,
set_external_syntax, shift_pos, shift_range,
};
pub use syntax::{MethodBody, PhpAlignment, PythonClassFacts, PythonFacts, PythonMethodFacts};
+1 -1
View File
@@ -28,7 +28,7 @@ use ide_core::{LanguageId, OutlineItem, Pos, Range};
pub use inheritance::ClassBases;
pub use lines::{shift_pos, shift_range};
pub use literals::{Literal, LiteralKind, SpellingKind, SpellingRegion};
pub use outline::merge_visibility;
pub use outline::{merge_kinds, merge_visibility};
pub use php_align::PhpAlignment;
pub use python_facts::{MethodBody, PythonClassFacts, PythonFacts, PythonMethodFacts};
use std::cell::RefCell;
+30
View File
@@ -495,6 +495,36 @@ pub fn merge_visibility(target: &mut [OutlineItem], source: &[OutlineItem]) {
}
}
/// Takes the syntax tree's kind where a server reported a declared type as a value or a type
/// parameter: LSP has no kind for type aliases, so servers fall back to one of those
/// (typescript-language-server: Variable; rust-analyzer, sourcekit-lsp: TypeParameter).
/// Matched by name and position like [`merge_visibility`].
pub fn merge_kinds(target: &mut [OutlineItem], source: &[OutlineItem]) {
fn index(items: &[OutlineItem], out: &mut HashMap<(ide_core::Pos, String), SymbolKind>) {
for i in items {
if i.kind.is_type_like() {
out.insert((i.selection_range.start, i.name.clone()), i.kind);
}
index(&i.children, out);
}
}
fn apply(items: &mut [OutlineItem], map: &HashMap<(ide_core::Pos, String), SymbolKind>) {
for i in items {
if matches!(i.kind, SymbolKind::Variable | SymbolKind::TypeParameter)
&& let Some(&kind) = map.get(&(i.selection_range.start, i.name.clone()))
{
i.kind = kind;
}
apply(&mut i.children, map);
}
}
let mut map = HashMap::new();
index(source, &mut map);
if !map.is_empty() {
apply(target, &map);
}
}
/// End of `node` without trailing whitespace (C macros and others include the newline).
fn trimmed_end(node: &Node, text: &str) -> usize {
let (s, e) = (node.start_byte(), node.end_byte());
+82
View File
@@ -1476,6 +1476,88 @@ fn merge_visibility_matches_by_name_and_position() {
assert_eq!(lsp[1].visibility, None);
}
#[test]
fn merge_kinds_names_types_a_server_reported_as_values_or_type_parameters() {
fn kinds(items: &[OutlineItem], out: &mut Vec<(String, SymbolKind)>) {
for i in items {
out.push((i.name.clone(), i.kind));
kinds(&i.children, out);
}
}
/// The syntax outline with each kind replaced as a server reports it.
fn as_server(ts: &[OutlineItem], server: &[(&str, SymbolKind)]) -> Vec<OutlineItem> {
fn set(items: &mut [OutlineItem], server: &[(&str, SymbolKind)], at: &mut usize) {
for i in items {
i.kind = server[*at].1;
assert_eq!(i.name, server[*at].0);
*at += 1;
set(&mut i.children, server, at);
}
}
let mut lsp = ts.to_vec();
set(&mut lsp, server, &mut 0);
lsp
}
fn merged(language: &str, src: &str, server: &[(&str, SymbolKind)]) -> Vec<(String, SymbolKind)> {
let ts = syntax().outline(&lang(language), src);
let mut lsp = as_server(&ts, server);
crate::merge_kinds(&mut lsp, &ts);
let mut out = Vec::new();
kinds(&lsp, &mut out);
out
}
use SymbolKind as K;
let owned = |v: &[(&str, SymbolKind)]| v.iter().map(|(n, k)| (n.to_string(), *k)).collect::<Vec<_>>();
// typescript-language-server: a type alias is a Variable; `const` is one too.
let ts = "type Cents = number;\ninterface Shape {}\nconst rate = 1;\n";
assert_eq!(
merged("typescript", ts, &[("Cents", K::Variable), ("Shape", K::Interface), ("rate", K::Variable)]),
owned(&[("Cents", K::TypeAlias), ("Shape", K::Interface), ("rate", K::Variable)]),
);
// rust-analyzer: type aliases and associated types are TypeParameters, a trait an Interface.
let rs = "pub type Meters = u32;\ntrait Measure { type Unit; }\nstruct Rope;\nimpl Measure for Rope { type Unit = Meters; }\n";
assert_eq!(
merged(
"rust",
rs,
&[
("Meters", K::TypeParameter),
("Measure", K::Interface),
("Unit", K::TypeParameter),
("Rope", K::Struct),
("impl Measure for Rope", K::Variable),
("Unit", K::TypeParameter),
],
),
owned(&[
("Meters", K::TypeAlias),
("Measure", K::Interface),
("Unit", K::TypeAlias),
("Rope", K::Struct),
("impl Measure for Rope", K::Variable),
("Unit", K::TypeAlias),
]),
);
// sourcekit-lsp: typealias and associatedtype are TypeParameters.
let swift = "typealias Meters = Int\nprotocol Measure { associatedtype Unit }\n";
assert_eq!(
merged("swift", swift, &[("Meters", K::TypeParameter), ("Measure", K::Interface), ("Unit", K::TypeParameter)]),
owned(&[("Meters", K::TypeAlias), ("Measure", K::Interface), ("Unit", K::TypeAlias)]),
);
// A type kind the server chose stays: clangd's Class for a typedef, gopls's Struct.
let c = "typedef unsigned int meters;\n";
assert_eq!(merged("c", c, &[("meters", K::Class)]), owned(&[("meters", K::Class)]));
let go = "package p\n\ntype Point struct{}\n";
assert_eq!(
merged("go", go, &[("p", K::Package), ("Point", K::Struct)]),
owned(&[("p", K::Package), ("Point", K::Struct)])
);
}
#[test]
fn spelling_regions_cover_declared_names_only() {
let src = "// note\nfn parse_input(raw_text: &str) -> Value { let mut counter = helper(raw_text); \"hi\" }\n";
+8 -12
View File
@@ -1,13 +1,12 @@
//! Parallel walk + per-file search.
use crate::iter::for_each_match;
use crate::line::line_match;
use crate::line::line_matches;
use crate::mask::FileMask;
use crate::pattern::ScopePattern;
use crate::query::{Compiled, line_terminator};
use crate::{
FileMatches, LineMatch, LiteralKind, LiteralRange, Literals, PathFilter, SearchContext, SearchScope, SearchSummary,
TextSource,
FileMatches, LineMatch, LiteralRange, Literals, PathFilter, SearchContext, SearchScope, SearchSummary, TextSource,
};
use grep_regex::RegexMatcher;
use grep_searcher::{BinaryDetection, Searcher, SearcherBuilder, Sink, SinkMatch};
@@ -52,6 +51,7 @@ struct Control<'a> {
matches: AtomicU32,
files: AtomicU32,
max: u32,
whole_word: bool,
}
impl Control<'_> {
@@ -131,6 +131,7 @@ pub(crate) fn run(req: Request<'_>) -> IdeResult<SearchSummary> {
matches: AtomicU32::new(0),
files: AtomicU32::new(0),
max: if req.max_matches == 0 { DEFAULT_MAX_MATCHES } else { req.max_matches },
whole_word: req.compiled.whole_word,
},
};
let mut searcher_builder = SearcherBuilder::new();
@@ -462,12 +463,6 @@ impl<'a> FileSink<'a> {
}
}
/// Kind of the comment or string literal containing byte `pos` (`literals` sorted).
fn literal_at(literals: &[LiteralRange], pos: usize) -> Option<LiteralKind> {
let i = literals.partition_point(|l| l.start <= pos);
literals[..i].last().filter(|l| pos < l.end).map(|l| l.kind)
}
impl Sink for FileSink<'_> {
type Error = io::Error;
@@ -488,12 +483,12 @@ impl Sink for FileSink<'_> {
let mut found = std::mem::take(&mut self.found);
let mut ranges = std::mem::take(&mut self.ranges);
found.clear();
for_each_match(self.matcher, &buffer[..range.end], range.start, |mm| {
for_each_match(self.matcher, self.ctl.whole_word, &buffer[..range.end], range.start, |mm| {
found.push((mm.start() - range.start, mm.end() - range.start));
});
if let Some((context, literals)) = self.context {
let block_start = usize::try_from(m.absolute_byte_offset()).unwrap_or(usize::MAX);
found.retain(|&(a, _)| context.accepts(literal_at(literals, block_start.saturating_add(a))));
found.retain(|&(a, _)| context.keeps(literals, block_start.saturating_add(a)));
}
let mut next = found.iter().copied().peekable();
@@ -521,7 +516,7 @@ impl Sink for FileSink<'_> {
if !ranges.is_empty() {
self.count = self.count.saturating_add(u32::try_from(ranges.len()).unwrap_or(u32::MAX));
let line_no = u32::try_from(line_no).unwrap_or(u32::MAX);
self.lines.push(line_match(line_no, &block[line_start..content_end], &ranges));
line_matches(line_no, &block[line_start..content_end], &ranges, &mut self.lines);
}
line_start = line_end_incl;
line_no += 1;
@@ -706,6 +701,7 @@ mod budget_tests {
matches: AtomicU32::new(0),
files: AtomicU32::new(0),
max,
whole_word: false,
}
}
+70 -7
View File
@@ -1,16 +1,27 @@
//! Match iteration that never splits a UTF-8 sequence after an empty match
//! (`grep-matcher`'s iterators advance by a single byte).
//! (`grep-matcher`'s iterators advance by a single byte), and that applies
//! IDEA's whole-word rule.
use grep_matcher::{Captures, Match, Matcher};
use grep_regex::{RegexCaptures, RegexMatcher};
/// Calls `f` for each non-overlapping match in `haystack[at..]`; `haystack[..at]`
/// is only used as look-behind context.
pub(crate) fn for_each_match(matcher: &RegexMatcher, haystack: &[u8], at: usize, mut f: impl FnMut(Match)) {
/// is only used as look-behind context. With `whole_word`, only [`is_whole_word`] matches.
pub(crate) fn for_each_match(
matcher: &RegexMatcher,
whole_word: bool,
haystack: &[u8],
at: usize,
mut f: impl FnMut(Match),
) {
let mut at = at;
let mut last_end = None;
while at <= haystack.len() {
let Ok(Some(m)) = matcher.find_at(haystack, at) else { break };
if whole_word && !is_whole_word(haystack, m) {
at = next_char(haystack, m.start());
continue;
}
at = advance(haystack, m);
if m.is_empty() && last_end == Some(m.end()) {
continue;
@@ -23,6 +34,7 @@ pub(crate) fn for_each_match(matcher: &RegexMatcher, haystack: &[u8], at: usize,
/// Like [`for_each_match`] but with capture groups.
pub(crate) fn for_each_captures(
matcher: &RegexMatcher,
whole_word: bool,
haystack: &[u8],
caps: &mut RegexCaptures,
mut f: impl FnMut(&RegexCaptures),
@@ -34,6 +46,10 @@ pub(crate) fn for_each_captures(
break;
}
let Some(m) = caps.get(0) else { break };
if whole_word && !is_whole_word(haystack, m) {
at = next_char(haystack, m.start());
continue;
}
at = advance(haystack, m);
if m.is_empty() && last_end == Some(m.end()) {
continue;
@@ -45,12 +61,59 @@ pub(crate) fn for_each_captures(
/// Where to resume after `m`: its end, or past the next char for empty matches.
fn advance(haystack: &[u8], m: Match) -> usize {
if !m.is_empty() {
return m.end();
}
let mut next = m.end() + 1;
if !m.is_empty() { m.end() } else { next_char(haystack, m.end()) }
}
/// The start of the char after the one at `at`.
fn next_char(haystack: &[u8], at: usize) -> usize {
let mut next = at + 1;
while next < haystack.len() && (haystack[next] & 0xC0) == 0x80 {
next += 1;
}
next
}
/// IDEA's whole word (`FindManagerBase.isWholeWord`): an edge where the match has an
/// identifier character must not touch another one, unless it follows an escape such as
/// `\n`; an edge with another character only must not repeat that character (`==` is not
/// in `===`).
fn is_whole_word(haystack: &[u8], m: Match) -> bool {
let (start, end) = (m.start(), m.end());
let word_start = match (char_before(haystack, start), char_at(haystack, start)) {
(Some(prev), Some(first)) if is_identifier(first) => {
let escaped = char_before(haystack, start - prev.len_utf8()) == Some('\\');
!is_identifier(prev) || escaped
}
(Some(prev), Some(first)) => prev != first,
_ => true,
};
let word_end = match (char_at(haystack, end), char_before(haystack, end)) {
(Some(next), Some(last)) if is_identifier(last) => !is_identifier(next),
(Some(next), Some(last)) => next != last,
(Some(_), None) | (None, _) => true,
};
word_start && word_end
}
/// Java's identifier part, near enough: letters, digits, `_` and `$`.
fn is_identifier(c: char) -> bool {
c.is_alphanumeric() || c == '_' || c == '$'
}
/// The char starting at byte `at` (`None` at the end or in invalid UTF-8).
fn char_at(haystack: &[u8], at: usize) -> Option<char> {
let rest = haystack.get(at..)?;
let len = rest.len().min(4);
let s = match std::str::from_utf8(&rest[..len]) {
Ok(s) => s,
Err(e) => std::str::from_utf8(&rest[..e.valid_up_to()]).ok()?,
};
s.chars().next()
}
/// The char ending at byte `at` (`None` at the start or in invalid UTF-8).
fn char_before(haystack: &[u8], at: usize) -> Option<char> {
let head = haystack.get(..at)?;
let from = head.len().saturating_sub(4);
(from..head.len()).find_map(|i| std::str::from_utf8(&head[i..]).ok().and_then(|s| s.chars().next_back()))
}
+15 -5
View File
@@ -22,7 +22,7 @@ pub use mask::FileMask;
pub use pattern::ScopePattern;
pub use replace::{
ReplaceEvent, ReplaceHost, ReplacePreview, ReplaceSummary, ReplaceTarget, apply_edits, preserve_case, preview,
replace_files, replacement_edits,
replace_files, replace_files_in_context, replacement_edits,
};
pub use words::{WordFiles, WordQuery, files_with_word};
@@ -99,8 +99,15 @@ impl SearchContext {
}
}
/// Whether a match starting at byte `at` is kept, given the file's sorted comments and
/// string literals. Find and Replace both filter with it, so they keep the same matches.
pub fn keeps(self, literals: &[LiteralRange], at: usize) -> bool {
let i = literals.partition_point(|l| l.start <= at);
self.accepts(literals[..i].last().filter(|l| at < l.end).map(|l| l.kind))
}
/// Only matches inside comments / string literals: files without any are skipped.
fn needs_literals(self) -> bool {
pub(crate) fn needs_literals(self) -> bool {
matches!(self, Self::InComments | Self::InStringLiterals)
}
}
@@ -160,7 +167,8 @@ pub type PathFilter<'a> = &'a (dyn Fn(&str) -> bool + Sync);
pub struct LineMatch {
/// 0-based line.
pub line: u32,
/// Line text, truncated around the match for very long lines.
/// Line text, truncated around the matches for very long lines: such a line comes as one
/// `LineMatch` per window, so the same `line` can repeat.
pub text: String,
/// UTF-16 column ranges within `text`.
pub ranges: Vec<(u32, u32)>,
@@ -285,7 +293,9 @@ pub fn match_ranges(text: &str, query: &SearchQuery) -> IdeResult<Vec<(usize, us
}
let compiled = query::compile(query)?;
let mut out = Vec::new();
iter::for_each_match(&compiled.matcher, text.as_bytes(), 0, |m| out.push((m.start(), m.end())));
iter::for_each_match(&compiled.matcher, compiled.whole_word, text.as_bytes(), 0, |m| {
out.push((m.start(), m.end()))
});
Ok(out)
}
@@ -308,7 +318,7 @@ pub fn replace_in_text(text: &str, query: &SearchQuery, replacement: &str) -> Id
let mut out = Vec::with_capacity(text.len());
let mut count = 0u32;
let mut last = 0;
iter::for_each_captures(matcher, haystack, &mut caps, |caps| {
iter::for_each_captures(matcher, compiled.whole_word, haystack, &mut caps, |caps| {
let Some(m) = caps.get(0) else { return };
out.extend_from_slice(&haystack[last..m.start()]);
last = m.end();
+65 -14
View File
@@ -1,5 +1,6 @@
//! Turns a matched line plus byte ranges into a [`LineMatch`] with UTF-16
//! columns, truncating very long lines to a window around the first match.
//! Turns a matched line plus byte ranges into [`LineMatch`]es with UTF-16
//! columns. A very long line is cut into windows: one around its first match
//! and the matches that fit with it, then one around each match left out.
use crate::LineMatch;
@@ -8,33 +9,57 @@ pub(crate) const MAX_LINE_LEN: usize = 500;
/// How much text before the first match a truncated line keeps.
const CONTEXT_BEFORE: usize = 100;
/// `line` excludes the line terminator; `ranges` are sorted, non-overlapping
/// Appends the matches of one line to `out`: a single [`LineMatch`], or one per window of a
/// very long line. `line` excludes the line terminator; `ranges` are sorted, non-overlapping
/// byte ranges within `line`.
pub(crate) fn line_match(line_no: u32, line: &[u8], ranges: &[(usize, usize)]) -> LineMatch {
pub(crate) fn line_matches(line_no: u32, line: &[u8], ranges: &[(usize, usize)], out: &mut Vec<LineMatch>) {
match std::str::from_utf8(line) {
Ok(s) => from_str(line_no, s, ranges),
Ok(s) => from_str(line_no, s, ranges, out),
Err(_) => {
let (s, mapped) = lossy(line, ranges);
from_str(line_no, &s, &mapped)
from_str(line_no, &s, &mapped, out)
}
}
}
fn from_str(line_no: u32, s: &str, ranges: &[(usize, usize)]) -> LineMatch {
let (start, end) = if s.len() <= MAX_LINE_LEN || utf16_len(s.as_bytes()) <= MAX_LINE_LEN {
(0, s.len())
} else {
window(s, floor_boundary(s, ranges.first().map_or(0, |r| r.0.min(s.len()))))
};
#[cfg(test)]
fn line_match(line_no: u32, line: &[u8], ranges: &[(usize, usize)]) -> LineMatch {
let mut out = Vec::new();
line_matches(line_no, line, ranges, &mut out);
out.swap_remove(0)
}
fn from_str(line_no: u32, s: &str, ranges: &[(usize, usize)], out: &mut Vec<LineMatch>) {
if s.len() <= MAX_LINE_LEN || utf16_len(s.as_bytes()) <= MAX_LINE_LEN {
out.push(in_window(line_no, s, ranges, (0, s.len())).0);
return;
}
let mut rest = ranges;
loop {
let bounds = window(s, floor_boundary(s, rest.first().map_or(0, |r| r.0.min(s.len()))));
let (m, used) = in_window(line_no, s, rest, bounds);
out.push(m);
rest = &rest[used.max(1)..];
if rest.is_empty() {
break;
}
}
}
/// The [`LineMatch`] of the text in `bounds` with the leading `ranges` that end inside it (at
/// least the first one, cut to the window), and how many ranges it took.
fn in_window(line_no: u32, s: &str, ranges: &[(usize, usize)], (start, end): (usize, usize)) -> (LineMatch, usize) {
let text = &s[start..end];
let text_offset = if start == 0 { 0 } else { utf16_len(&s.as_bytes()[..start]) };
let mut out = Vec::with_capacity(ranges.len());
let (mut pos, mut col) = (start, 0usize);
let mut used = 0;
for &(a, b) in ranges {
if a > end || (a == end && b > a) {
if a > end || (a == end && b > a) || (used > 0 && b > end) {
break;
}
used += 1;
let (a, b) = (floor_boundary(s, a.max(start)), ceil_boundary(s, b.min(end)));
if a < pos {
continue;
@@ -45,7 +70,7 @@ fn from_str(line_no: u32, s: &str, ranges: &[(usize, usize)]) -> LineMatch {
pos = b;
out.push((col_a as u32, col as u32));
}
LineMatch { line: line_no, text: text.to_owned(), ranges: out, text_offset: text_offset as u32 }
(LineMatch { line: line_no, text: text.to_owned(), ranges: out, text_offset: text_offset as u32 }, used)
}
/// Byte window `[start, end)` of at most `MAX_LINE_LEN` UTF-16 units that
@@ -186,4 +211,30 @@ mod tests {
assert_eq!(m.ranges, vec![(100, 106)]);
assert!(utf16_len(m.text.as_bytes()) <= MAX_LINE_LEN);
}
#[test]
fn matches_outside_the_first_window_get_their_own() {
// Two matches 100 apart share a window; the one 1000 further gets another.
let s = format!("{}ab{}cd{}ef{}", "x".repeat(1000), "x".repeat(100), "x".repeat(1000), "x".repeat(10));
let at = |needle: &str| s.find(needle).unwrap();
let ranges = [(at("ab"), at("ab") + 2), (at("cd"), at("cd") + 2), (at("ef"), at("ef") + 2)];
let mut out = Vec::new();
line_matches(7, s.as_bytes(), &ranges, &mut out);
let found: Vec<Vec<u32>> =
out.iter().map(|m| m.ranges.iter().map(|&(a, _)| m.text_offset + a).collect()).collect();
let col = |needle: &str| at(needle) as u32;
assert_eq!(found, vec![vec![col("ab"), col("cd")], vec![col("ef")]]);
assert!(out.iter().all(|m| m.line == 7 && utf16_len(m.text.as_bytes()) <= MAX_LINE_LEN));
assert_eq!(&out[1].text[out[1].ranges[0].0 as usize..out[1].ranges[0].1 as usize], "ef");
}
#[test]
fn a_match_longer_than_the_window_is_cut_to_it() {
let s = format!("{}{}tail", "x".repeat(100), "y".repeat(1000));
let mut out = Vec::new();
line_matches(0, s.as_bytes(), &[(100, 1100), (1100, 1104)], &mut out);
assert_eq!(out.len(), 2);
assert_eq!(out[0].ranges, vec![(100, 500)]);
assert_eq!(out[1].text_offset + out[1].ranges[0].0, 1100);
}
}
+7 -3
View File
@@ -9,6 +9,8 @@ use ide_core::{IdeError, IdeResult};
pub(crate) struct Compiled {
pub matcher: RegexMatcher,
pub multi_line: bool,
/// Keep only whole-word matches ([`crate::iter`] checks IDEA's rule on each match).
pub whole_word: bool,
}
/// The line terminator shared by the matcher and the searcher. CRLF mode lets
@@ -19,12 +21,13 @@ pub(crate) fn line_terminator() -> LineTerminator {
pub(crate) fn compile(query: &SearchQuery) -> IdeResult<Compiled> {
let multi_line = needs_multi_line(query);
let whole_word = query.whole_word;
match build(query, multi_line) {
Ok(matcher) => Ok(Compiled { matcher, multi_line }),
Ok(matcher) => Ok(Compiled { matcher, multi_line, whole_word }),
// Patterns such as `[\n]` or `\x0A` can only match across lines;
// retry in multi-line mode before reporting an error.
Err(err) if !multi_line => match build(query, true) {
Ok(matcher) => Ok(Compiled { matcher, multi_line: true }),
Ok(matcher) => Ok(Compiled { matcher, multi_line: true, whole_word }),
Err(_) => Err(invalid_pattern(query, &err)),
},
Err(err) => Err(invalid_pattern(query, &err)),
@@ -35,7 +38,8 @@ fn build(query: &SearchQuery, multi_line: bool) -> Result<RegexMatcher, grep_reg
let mut b = RegexMatcherBuilder::new();
b.case_smart(false)
.case_insensitive(!query.case_sensitive)
.word(query.whole_word)
// Not `.word()`: ripgrep's rule wants a non-word character on both sides even of
// `foo(`, IDEA's (in `iter`) only beside the match's identifier characters.
.fixed_strings(!query.is_regex)
.unicode(true)
// `^`/`$` always mean start/end of line, as in IDEA and ripgrep.
+35 -7
View File
@@ -3,7 +3,7 @@
//! (the document layer in the app, so open editors update and each file is one
//! undoable step).
use crate::{SearchQuery, iter, query};
use crate::{LiteralRange, Literals, SearchContext, SearchQuery, iter, query};
use grep_matcher::{Captures, Matcher};
use ide_core::{CancellationToken, IdeError, IdeResult, Pos, Range, TextEdit};
use serde::{Deserialize, Serialize};
@@ -128,10 +128,11 @@ pub fn replacement_edits(
preserve: bool,
only: Option<&[Pos]>,
) -> IdeResult<Vec<TextEdit>> {
edits_except(text, query, replacement, preserve, only, None)
edits_except(text, query, replacement, preserve, only, None, None)
}
/// [`replacement_edits`] leaving out the matches that start at `skip`.
/// [`replacement_edits`] leaving out the matches that start at `skip` and, given the text's
/// comments and string literals, those outside the query's [`crate::SearchContext`].
fn edits_except(
text: &str,
query: &SearchQuery,
@@ -139,6 +140,7 @@ fn edits_except(
preserve: bool,
only: Option<&[Pos]>,
skip: Option<&[Pos]>,
literals: Option<&[LiteralRange]>,
) -> IdeResult<Vec<TextEdit>> {
if query.pattern.is_empty() {
return Ok(Vec::new());
@@ -153,10 +155,13 @@ fn edits_except(
let mut caps = matcher.new_captures().map_err(|e| IdeError::internal(e.to_string()))?;
let mut edits = Vec::new();
let mut buf = Vec::new();
iter::for_each_captures(matcher, haystack, &mut caps, |caps| {
iter::for_each_captures(matcher, compiled.whole_word, haystack, &mut caps, |caps| {
let Some(m) = caps.get(0) else { return };
let start = lines.pos(m.start());
if only.as_ref().is_some_and(|o| !o.contains(&start)) || skip.contains(&start) {
if only.as_ref().is_some_and(|o| !o.contains(&start))
|| skip.contains(&start)
|| literals.is_some_and(|l| !query.context.keeps(l, m.start()))
{
return;
}
let mut new_text = if query.is_regex {
@@ -227,6 +232,23 @@ pub fn replace_files(
cancel: &CancellationToken,
on_event: &dyn Fn(ReplaceEvent),
) -> IdeResult<ReplaceSummary> {
replace_files_in_context(host, query, replacement, preserve, targets, None, cancel, on_event)
}
/// [`replace_files`] honouring [`SearchQuery::context`] with the comments and string literals
/// `literals` finds, as [`crate::search_in_context`] does; without it every match is plain code.
#[allow(clippy::too_many_arguments)]
pub fn replace_files_in_context(
host: &dyn ReplaceHost,
query: &SearchQuery,
replacement: &str,
preserve: bool,
targets: &[ReplaceTarget],
literals: Option<Literals<'_>>,
cancel: &CancellationToken,
on_event: &dyn Fn(ReplaceEvent),
) -> IdeResult<ReplaceSummary> {
let literals = literals.filter(|_| query.context != SearchContext::Any);
// Fail fast on an invalid pattern instead of once per file.
if !query.pattern.is_empty() {
query::compile(query)?;
@@ -244,8 +266,14 @@ pub fn replace_files(
if only.is_some_and(|o| o.is_empty()) {
continue;
}
let result =
host.edit_file(&target.path, &mut |text| edits_except(text, query, replacement, preserve, only, skip));
let result = host.edit_file(&target.path, &mut |text| {
let found = match literals.map(|l| l(&target.path, text)) {
// No syntax tree: nothing is in a comment or string, as in the search.
Some(None) if query.context.needs_literals() => return Ok(Vec::new()),
found => found.map(Option::unwrap_or_default),
};
edits_except(text, query, replacement, preserve, only, skip, found.as_deref())
});
match result {
Ok(n) => {
if n > 0 {
+45 -2
View File
@@ -1,7 +1,7 @@
use ide_core::{CancellationToken, IdeError, IdeResult, Pos, TextEdit};
use ide_search::{
ReplaceEvent, ReplaceHost, ReplaceTarget, SearchQuery, SearchScope, preserve_case, preview, replace_files,
replacement_edits,
LiteralKind, LiteralRange, ReplaceEvent, ReplaceHost, ReplaceTarget, SearchQuery, SearchScope, preserve_case,
preview, replace_files, replace_files_in_context, replacement_edits,
};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
@@ -169,3 +169,46 @@ fn replace_files_respects_selected_matches_and_invalid_patterns() {
let err = replace_files(&docs, &regex("("), "x", false, &t, &CancellationToken::new(), &|_| {}).unwrap_err();
assert_eq!(err.kind, ide_core::error::ErrorKind::InvalidInput);
}
/// `// …` comments and `"…"` strings of `.rs` files; other files have no syntax tree.
fn toy_literals(path: &Path, text: &str) -> Option<Vec<LiteralRange>> {
if path.extension().is_none_or(|e| e != "rs") {
return None;
}
let mut out = Vec::new();
for (i, _) in text.match_indices("//") {
let end = text[i..].find('\n').map_or(text.len(), |n| i + n);
out.push(LiteralRange { start: i, end, kind: LiteralKind::Comment });
}
let quotes: Vec<usize> = text.match_indices('"').map(|(i, _)| i).collect();
for pair in quotes.chunks(2) {
if let [a, b] = pair {
out.push(LiteralRange { start: *a, end: b + 1, kind: LiteralKind::String });
}
}
out.sort_by_key(|l| l.start);
Some(out)
}
#[test]
fn replace_files_in_context_keeps_to_the_search_context() {
use ide_search::SearchContext as C;
let text = "foo(\"foo\"); // foo\nfoo\n";
let plain = "foo // foo\n";
let cases = [
(C::Any, "x(\"x\"); // x\nx\n", "x // x\n"),
(C::InComments, "foo(\"foo\"); // x\nfoo\n", plain),
(C::InStringLiterals, "foo(\"x\"); // foo\nfoo\n", plain),
(C::ExceptComments, "x(\"x\"); // foo\nx\n", "x // x\n"),
(C::ExceptStringLiterals, "x(\"foo\"); // x\nx\n", "x // x\n"),
(C::ExceptCommentsAndStringLiterals, "x(\"foo\"); // foo\nx\n", "x // x\n"),
];
for (context, in_rs, in_txt) in cases {
let docs = FakeDocs::with(&[("a.rs", text), ("b.txt", plain)]);
let q = SearchQuery { context, ..query("foo") };
let t = targets(&["a.rs", "b.txt"]);
replace_files_in_context(&docs, &q, "x", false, &t, Some(&toy_literals), &CancellationToken::new(), &|_| {})
.unwrap();
assert_eq!((docs.text("a.rs").as_str(), docs.text("b.txt").as_str()), (in_rs, in_txt), "{context:?}");
}
}
+65
View File
@@ -132,6 +132,36 @@ fn whole_word() {
assert_eq!(views[0].matches[0].ranges, vec![(0, 3), (27, 30), (32, 35)]);
}
/// IDEA's whole word: a word boundary is needed only at an edge where the match has an
/// identifier character; a punctuation edge only needs a different character beside it.
#[test]
fn whole_word_needs_a_boundary_only_at_identifier_edges() {
let starts = |text: &str, q: SearchQuery| -> Vec<usize> {
let q = SearchQuery { whole_word: true, ..q };
ide_search::match_ranges(text, &q).unwrap().into_iter().map(|r| r.0).collect()
};
let text = "doWork(arg); redoWork(x); list: string[] = [];";
assert_eq!(starts(text, query("doWork(")), [0]);
assert_eq!(starts(text, query("(arg)")), [6]);
assert_eq!(starts(text, query("[]")), [38, 43]);
assert_eq!(starts(text, query("list")), [26]);
assert_eq!(starts("a == b; c === d", query("==")), [2]);
// `$` is part of an identifier (Java, Kotlin, JavaScript).
assert_eq!(starts("foo$bar foo", query("foo")), [8]);
// After an escape such as `\n`, a word starts.
assert_eq!(starts(r#"s = "\nfoo";"#, query("foo")), [7]);
assert_eq!(starts("é1 1 éé", query("1")), [4]);
// Regex matches follow the same rule.
assert_eq!(starts(text, regex(r"\w+\(")), [0, 13]);
assert_eq!(starts(text, regex(r"\[\]")), [38, 43]);
let p = project(&[("a.ts", text.as_bytes())]);
let (views, summary) = run(p.path(), &SearchQuery { whole_word: true, ..query("[]") });
assert_eq!((summary.matches, views[0].matches[0].ranges.clone()), (2, vec![(38, 40), (43, 45)]));
let (out, n) = replace_in_text(text, &SearchQuery { whole_word: true, ..query("doWork(") }, "run(").unwrap();
assert_eq!((out.as_str(), n), ("run(arg); redoWork(x); list: string[] = [];", 1));
}
#[test]
fn invalid_regex_is_reported() {
let p = project(&[("a.txt", b"x\n")]);
@@ -431,6 +461,41 @@ fn long_lines_are_truncated() {
assert_eq!(second.text, "short needle");
}
#[test]
fn every_match_of_a_long_line_is_reported_in_its_own_window() {
let long = format!("a='needle';{}b='needle';{}needle!\n", "x".repeat(2000), "y".repeat(2000));
let p = project(&[("min.js", long.as_bytes())]);
let (views, summary) = run(p.path(), &query("needle"));
assert_eq!(summary.matches, 3);
let lines = &views[0].matches;
assert_eq!(lines.len(), 3, "one window per far-apart match");
let line_utf16: Vec<u16> = long.trim_end().encode_utf16().collect();
let mut starts = Vec::new();
for m in lines {
assert_eq!(m.line, 0);
assert!(m.text.encode_utf16().count() <= 500);
let [(a, b)] = m.ranges[..] else { panic!("{:?}", m.ranges) };
let text: Vec<u16> = m.text.encode_utf16().collect();
assert_eq!(String::from_utf16(&text[a as usize..b as usize]).unwrap(), "needle");
let col = (m.text_offset + a) as usize;
assert_eq!(String::from_utf16(&line_utf16[col..col + 6]).unwrap(), "needle");
starts.push(ide_core::Pos::new(0, m.text_offset + a));
}
// The reported positions are the ones Replace takes: all of them are replaced.
let edits = ide_search::replacement_edits(&long, &query("needle"), "pin", false, Some(&starts)).unwrap();
assert_eq!(edits.len(), 3);
assert!(!ide_search::apply_edits(&long, &edits).contains("needle"));
}
#[test]
fn match_limit_counts_every_match_of_a_long_line() {
let long = format!("needle{}needle{}needle\n", "x".repeat(1000), "y".repeat(1000));
let p = project(&[("min.js", long.as_bytes())]);
let (views, summary) = run(p.path(), &SearchQuery { max_matches: 2, ..query("needle") });
assert!(summary.limit_hit);
assert_eq!((summary.matches, total(&views)), (2, 2));
}
#[test]
fn multi_line_matches() {
let p = project(&[("a.rs", b"fn foo() {\n bar();\n}\nfoo\nbar\n")]);
+31 -2
View File
@@ -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() {
@@ -422,6 +422,8 @@ impl Documents {
}
// Validate project rules before path resolution can erase linked components.
crate::file_ops::validate_workspace_edit_paths(edit)?;
// Editors know the paths as the edit named them, before link resolution.
let moves = edit.moves();
let mut edit = normalize_edit(edit)?;
let captured = !edit.preconditions.is_empty();
crate::file_ops::expand_workspace_edit(&mut edit)?;
@@ -501,7 +503,7 @@ impl Documents {
});
}
history.prune(SystemTime::now(), MAX_HISTORY_BYTES, MAX_HISTORY_AGE);
self.sink.emit(IdeEvent::WorkspaceEditApplied { id, paths: affected, by_agent });
self.sink.emit(IdeEvent::WorkspaceEditApplied { id, paths: affected, moves, by_agent });
}
Ok(())
}
+1 -8
View File
@@ -4,20 +4,13 @@
use crate::documents::Documents;
use crate::history::LocalHistory;
pub use ide_core::FileMove;
use ide_core::{FileEdit, IdeError, IdeResult, WorkspaceEdit};
use parking_lot::Mutex;
use serde::{Deserialize, Serialize};
use specta::Type;
use std::path::{Path, PathBuf};
/// One file or folder move.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct FileMove {
pub from: ide_core::IpcPath,
pub to: ide_core::IpcPath,
}
/// What [`FileMoves::undo`] did.
#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
+10
View File
@@ -898,6 +898,16 @@ mod tests {
);
}
#[test]
fn commit_default_inclusion_persists() {
let tmp = tempfile::tempdir().unwrap();
let store = SettingsStore::load(tmp.path(), None);
assert!(store.effective().vcs.commit.include_changes_by_default);
let settings = store.set(SettingsScope::Global, "vcs.commit.includeChangesByDefault", json!(false)).unwrap();
assert!(!settings.vcs.commit.include_changes_by_default);
assert!(!SettingsStore::load(tmp.path(), None).effective().vcs.commit.include_changes_by_default);
}
#[test]
fn inspection_profiles_live_in_their_layers() {
let tmp = tempfile::tempdir().unwrap();
+40 -1
View File
@@ -1,4 +1,4 @@
use ide_core::{ChangeSet, FileEdit, LanguageId, NullSink, Pos, Range, TextChange, TextEdit, WorkspaceEdit};
use ide_core::{ChangeSet, FileEdit, FileMove, LanguageId, NullSink, Pos, Range, TextChange, TextEdit, WorkspaceEdit};
use ide_core::{IdeEvent, error::ErrorKind};
use ide_workspace::Documents;
use parking_lot::Mutex;
@@ -162,6 +162,45 @@ fn undo_id(events: &Mutex<Vec<IdeEvent>>) -> u32 {
.expect("successful transaction has one undo record")
}
#[test]
fn applied_event_lists_the_files_the_edit_renamed() {
for by_agent in [false, true] {
let tmp = tempfile::tempdir().unwrap();
let from = tmp.path().join("ListPrice.java");
let to = tmp.path().join("BasePrice.java");
let user = tmp.path().join("BulkDiscount.java");
std::fs::write(&from, "old").unwrap();
std::fs::write(&user, "old\n").unwrap();
let (docs, events) = recorded_documents();
let edit = WorkspaceEdit {
files: vec![edit(&user, "new"), FileEdit::Rename { from: from.clone().into(), to: to.clone().into() }],
..Default::default()
};
if by_agent { docs.apply_agent_workspace_edit(&edit) } else { docs.apply_workspace_edit(&edit) }.unwrap();
let moves = events
.lock()
.iter()
.find_map(|event| match event {
IdeEvent::WorkspaceEditApplied { moves, .. } => Some(moves.clone()),
_ => None,
})
.unwrap();
assert_eq!(moves, vec![FileMove { from: from.into(), to: to.into() }], "by_agent: {by_agent}");
}
}
#[test]
fn applied_event_lists_no_moves_for_text_edits() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("a.txt");
std::fs::write(&path, "old\n").unwrap();
let (docs, events) = recorded_documents();
docs.apply_workspace_edit(&WorkspaceEdit { files: vec![edit(&path, "new")], ..Default::default() }).unwrap();
assert!(
events.lock().iter().any(|e| matches!(e, IdeEvent::WorkspaceEditApplied { moves, .. } if moves.is_empty()))
);
}
#[test]
fn undo_keeps_the_encoding_chosen_for_a_file_opened_after_the_edit() {
let tmp = tempfile::tempdir().unwrap();
+8
View File
@@ -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
View File
@@ -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
+62 -2
View File
@@ -1,7 +1,18 @@
import type { Page } from "@playwright/test";
import type { BuildModel, BuildTool } from "../src/platform/ipc";
import type { BuildModel, BuildTool, MavenDependency } from "../src/platform/ipc";
import { expect, stubDesktop, test } from "./fixtures";
const jsonCore: MavenDependency = {
groupId: "com.example.json",
artifactId: "json-core",
version: "2.1.0",
type: "jar",
classifier: null,
scope: "compile",
optional: false,
children: [],
};
const model: BuildModel = {
maven: {
projects: [
@@ -17,7 +28,14 @@ const model: BuildModel = {
modules: [],
aggregated: false,
plugins: [],
dependencies: [],
dependencies: [
jsonCore,
{
...jsonCore,
artifactId: "json-mapper",
children: [{ ...jsonCore, version: "2.0.0", omitted: "conflict", conflictWith: "2.1.0" }],
},
],
profiles: [],
javaVersion: 21,
command: "mvn",
@@ -97,3 +115,45 @@ for (const tool of ["maven", "gradle"] as const) {
await expect(menu).toBeHidden();
});
}
test("Dependency Analyzer pairs its pane controls and stacks usages in a narrow editor", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 1360, height: 780 });
await showTool(page, "maven");
const toolActions = page.getByRole("toolbar", { name: "Maven actions" });
await toolActions.getByRole("button", { name: "More Actions", exact: true }).click();
await page.getByRole("menuitem", { name: "Analyze Dependencies…", exact: true }).click();
const filters = page.getByRole("toolbar", { name: "Dependency Analyzer", exact: true });
const resolved = page.getByRole("heading", { name: "Resolved Dependencies", exact: true });
const usages = page.getByRole("heading", { name: "Usages of com.example.json:json-core:2.1.0", exact: true });
const dependencies = page.getByRole("tree", { name: "Dependencies", exact: true });
const core = dependencies.getByRole("treeitem", { name: /^com\.example\.json:json-core\b/ });
const treeMode = page.getByRole("button", { name: "Show as Tree", exact: true });
const conflicts = filters.getByRole("button", { name: "Show conflicts only", exact: true });
await expect(resolved).toBeVisible();
await expect(filters.getByRole("button", { name: "Show as Tree" })).toHaveCount(0);
await treeMode.click();
await expect(treeMode).toHaveAttribute("aria-pressed", "true");
await page.getByRole("button", { name: "Show as List", exact: true }).click();
await conflicts.press("Space");
await expect(conflicts).toHaveAttribute("aria-pressed", "true");
await expect(dependencies.getByRole("treeitem")).toHaveCount(1);
await core.click();
await expect(usages).toBeVisible();
await expect(page.getByText("omitted for conflict with 2.1.0")).toBeVisible();
const wideLeft = (await resolved.boundingBox())!;
const wideRight = (await usages.boundingBox())!;
expect(Math.abs(wideLeft.y - wideRight.y)).toBeLessThan(1);
expect(wideRight.x).toBeGreaterThan(wideLeft.x + wideLeft.width);
await page.setViewportSize({ width: 790, height: 780 });
await expect
.poll(async () => (await usages.boundingBox())!.y - (await resolved.boundingBox())!.y)
.toBeGreaterThan(100);
expect(Math.abs((await usages.boundingBox())!.x - (await resolved.boundingBox())!.x)).toBeLessThan(1);
expect(await filters.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await expect(core).toHaveAttribute("aria-selected", "true");
await expect(page.getByRole("button", { name: "Copy Coordinates" })).toBeInViewport({ ratio: 1 });
});
+28
View File
@@ -76,6 +76,34 @@ test("⌘K commits the checked changes with the typed message", async ({ workben
await expect(changes.getByRole("checkbox", { name: "Include build.gradle.kts in commit" })).toBeHidden();
});
test("turning off default inclusion starts Commit with all files unchecked", async ({ workbench: page }) => {
await page.keyboard.press("Meta+,");
const settings = page.getByRole("dialog", { name: "Settings", exact: true });
const label = "Include changes in the commit by default";
await settings.getByRole("textbox", { name: "Search settings" }).fill(label);
await settings.getByRole("treeitem", { name: "Commit", exact: true }).click();
const toggle = settings.getByRole("checkbox", { name: label, exact: true });
await expect(toggle).toBeChecked();
await toggle.click();
await settings.getByRole("button", { name: "OK", exact: true }).click();
await expect(settings).not.toBeVisible();
await stubRepository(page);
await page.keyboard.press("Meta+k");
const panel = page.getByRole("region", { name: "Commit", exact: true });
const changes = panel.getByRole("tree", { name: "Changes" });
const tracked = changes.getByRole("checkbox", { name: "Include build.gradle.kts in commit" });
await expect(tracked).toHaveAttribute("aria-checked", "false");
await expect(changes.getByRole("checkbox", { name: "Include Unversioned Files in commit" })).not.toBeChecked();
await tracked.click();
await expect(tracked).toBeChecked();
await panel.getByRole("textbox", { name: "Commit message" }).fill("Commit the selected file");
await panel.getByRole("button", { name: "Commit", exact: true }).click();
await expect.poll(() => ipcCalls(page, "vcs_commit")).toHaveLength(1);
const [committed] = await ipcCalls(page, "vcs_commit");
expect(committed!.options).toMatchObject({ stage: [`${ROOT}/build.gradle.kts`] });
});
test("commit message history opens above the message without an empty icon column", async ({ workbench: page }) => {
await stubRepository(page);
await page.keyboard.press("Meta+k");
+20
View File
@@ -65,6 +65,26 @@ for (const locale of ["en", "zh"]) {
});
}
test("keeps Open project in options within narrow System Settings", async ({ workbench: page }) => {
await page.keyboard.press("Meta+,");
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
await expect(dialog).toBeVisible();
await selectPage(page, "general");
const group = dialog.getByRole("radiogroup", { name: "Open project in", exact: true });
const longest = group.getByRole("radio", { name: "New tab in current window", exact: true });
await expect(longest).toBeVisible();
await page.setViewportSize({ width: 520, height: 760 });
const overflow = await longest.evaluate(async (radio) => {
await new Promise<void>((resolve) => requestAnimationFrame(() => requestAnimationFrame(() => resolve())));
const label = radio.closest("label")!;
const group = radio.closest('[role="radiogroup"]')!;
const text = document.createRange();
text.selectNodeContents(label);
return text.getBoundingClientRect().right - group.getBoundingClientRect().right;
});
expect(overflow).toBeLessThanOrEqual(1);
});
test("settings sidebar resizes with mouse and keyboard and remembers its width", async ({ workbench: page }) => {
await page.keyboard.press("Meta+,");
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
+5
View File
@@ -71,12 +71,17 @@ test("⌘1 focuses, hides and re-shows the Project tool window", async ({ workbe
test("⌘4 toggles Run; Shift+Escape hides the active tool window", async ({ workbench: page }) => {
const run = page.getByRole("region", { name: "Run" });
// The shortcut hides the window only once it is active: activation focuses it a frame after it shows.
const focusedInRun = () =>
expect.poll(() => page.evaluate(() => !!document.activeElement?.closest('[data-toolwindow="run"]'))).toBe(true);
await page.keyboard.press("Meta+4");
await expect(run).toBeVisible();
await focusedInRun();
await page.keyboard.press("Meta+4");
await expect(run).toBeHidden();
await page.keyboard.press("Meta+4");
await expect(run).toBeVisible();
await focusedInRun();
await page.keyboard.press("Shift+Escape");
await expect(run).toBeHidden();
});
+3
View File
@@ -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
+114 -2
View File
@@ -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 })),
/**
@@ -538,7 +550,7 @@ export const commands = {
docOpenVirtual: (uri: string) => typedError<DocumentInfo, IdeError>(__TAURI_INVOKE("doc_open_virtual", { uri })),
/**
* Structure view: LSP document symbols when available (with tree-sitter
* visibility), tree-sitter otherwise.
* visibility and type-alias kinds), tree-sitter otherwise.
* Tree-sitter answers come from the per-document tree cache (incremental
* re-parse); large documents get no syntax structure.
*/
@@ -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,
};
@@ -3802,6 +3906,7 @@ export type CommitSettings = {
* window and a Commit dialog.
*/
nonModal?: boolean,
includeChangesByDefault?: boolean,
/** Start with an empty message instead of the last one / the changelist's. */
clearInitialMessage?: boolean,
analyzeCode?: boolean,
@@ -7126,6 +7231,8 @@ version: number } |
{ type: "docDiskConflict"; doc: DocId; path: string } |
/** A complete workspace edit can be undone as one operation. */
{ type: "workspaceEditApplied"; id: number; paths: IpcPath[];
/** Files the edit renamed, as the edit named them: editors open on them follow. */
moves: FileMove[];
/**
* Made by an agent through the MCP server's tools: undoable like a refactoring, but
* not announced as one.
@@ -8161,7 +8268,10 @@ export type LineMarkerInfo = {
export type LineMatch = {
/** 0-based line. */
line: number,
/** Line text, truncated around the match for very long lines. */
/**
* Line text, truncated around the matches for very long lines: such a line comes as one
* `LineMatch` per window, so the same `line` can repeat.
*/
text: string,
/** UTF-16 column ranges within `text`. */
ranges: ([number, number])[],
@@ -9014,6 +9124,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
View File
@@ -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
View File
@@ -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);
}),
),
+68 -3
View File
@@ -1,9 +1,14 @@
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { redo, redoDepth, undo, undoDepth, history } from "@codemirror/commands";
import { EditorView } from "@codemirror/view";
import { workspaceEditHistory } from "@/editor/api";
import { _provideOpenEditorPaths, workspaceEditHistory } from "@/editor/api";
import { installWorkspaceEditUndo } from "@/features/code-insight/workspaceUndo";
import { provideNotificationService, type NotificationService } from "@/workbench/contributions";
import {
provideEditorService,
provideNotificationService,
type EditorService,
type NotificationService,
} from "@/workbench/contributions";
import { emitLocalIdeEvent } from "@/platform/ipc";
import { createMemoryBackend, type MemoryBackend } from "../backend";
import { _resetLanguages } from "../cm/languages";
@@ -61,6 +66,7 @@ async function rename() {
type: "workspaceEditApplied",
id: 9,
paths: ["/p/A.java", "/p/B.java", "/p/closed.java"],
moves: [],
byAgent: false,
});
}
@@ -188,7 +194,13 @@ it("rebuilds multiple redo markers in order when a closed file opens", async ()
const a = await open("/p/A.java");
await rename();
await replace("alt");
emitLocalIdeEvent({ type: "workspaceEditApplied", id: 10, paths: ["/p/A.java", "/p/B.java"], byAgent: true });
emitLocalIdeEvent({
type: "workspaceEditApplied",
id: 10,
paths: ["/p/A.java", "/p/B.java"],
moves: [],
byAgent: true,
});
commands.undoWorkspaceEdit.mockImplementation(async (id: number) => {
await replace(id === 10 ? "new" : "old");
return { status: "ok", data: null };
@@ -257,3 +269,56 @@ it("keeps refactoring markers current while a secondary view is unmounted", asyn
expect(commands.undoWorkspaceEdit).toHaveBeenCalledOnce();
att.release();
});
it("editors on a file the edit renamed reopen at its new path, through Undo and Redo", async () => {
const live = () => slots.filter((s) => !closed.has(s));
const closed = new Set<EditorSlot>();
const openFile = vi.fn(async (path: string) => {
if (!live().some((s) => s.model.path === path)) await open(path);
});
const closePath = vi.fn(async (path: string) => {
for (const s of live())
if (s.model.path === path) {
closed.add(s);
s.dispose();
}
return true;
});
provideEditorService({
openFile,
closePath,
activePath: () => live().at(-1)?.model.path ?? null,
saveAll: vi.fn(),
} as unknown as EditorService);
_provideOpenEditorPaths(() => live().map((s) => s.model.path));
backend.files.set("/p/Renamed.java", "old");
const moved = async (from: string, to: string, run: () => Promise<unknown>) => {
openFile.mockClear();
await run();
await vi.waitFor(() => expect(openFile).toHaveBeenCalledExactlyOnceWith(to, { focus: false }));
expect(closePath).toHaveBeenCalledWith(from);
expect(live().map((s) => s.model.path)).toEqual(["/p/B.java", to]);
};
try {
await open("/p/B.java");
await open("/p/A.java");
await moved("/p/A.java", "/p/Renamed.java", async () => {
await replace("new");
emitLocalIdeEvent({
type: "workspaceEditApplied",
id: 11,
paths: ["/p/A.java", "/p/Renamed.java", "/p/B.java"],
moves: [{ from: "/p/A.java", to: "/p/Renamed.java" }],
byAgent: false,
});
});
// Reopened editors take part in the refactoring's history like the ones they replace.
await moved("/p/Renamed.java", "/p/A.java", () => workspaceEditHistory(11));
await moved("/p/A.java", "/p/Renamed.java", () => workspaceEditHistory(11, true));
await moved("/p/Renamed.java", "/p/A.java", () => workspaceEditHistory(11));
expect(notify).not.toHaveBeenCalled();
} finally {
provideEditorService(undefined as unknown as EditorService);
_provideOpenEditorPaths(() => []);
}
});
+22 -12
View File
@@ -3,7 +3,8 @@ import { invertedEffects, isolateHistory, redo, undo } from "@codemirror/command
import { EditorState, Prec, StateEffect, type Transaction, type Extension } from "@codemirror/state";
import { EditorView, keymap } from "@codemirror/view";
import { _emitWorkspaceEditHistory, _provideWorkspaceHistory, isExternalChange } from "@/editor/api";
import { call, commands, onIdeEvent } from "@/platform/ipc";
import { editorsFollowAppliedMoves, reversedMoves, withEditorsFollowing } from "@/editor/fileMoves";
import { call, commands, onIdeEvent, type FileMove } from "@/platform/ipc";
import { useProject } from "@/platform/project";
interface Marker {
@@ -20,7 +21,7 @@ export interface WorkspaceHistoryTarget {
export class WorkspaceHistory {
private targets = new Set<WorkspaceHistoryTarget>();
private records = new Map<number, { paths: string[]; undone: boolean }>();
private records = new Map<number, { paths: string[]; moves: FileMove[]; undone: boolean }>();
private project = useProject.getState().project;
private busy = false;
private moving = false;
@@ -31,7 +32,7 @@ export class WorkspaceHistory {
) {}
start(): () => void {
const stop = onIdeEvent("workspaceEditApplied", ({ id, paths }) => {
const stop = onIdeEvent("workspaceEditApplied", ({ id, paths, moves }) => {
if (this.project !== useProject.getState().project) {
this.records.clear();
this.project = useProject.getState().project;
@@ -43,9 +44,11 @@ export class WorkspaceHistory {
record.paths.some((path) => this.affects(paths, path) || paths.some((root) => root.startsWith(`${path}/`)))
)
this.records.delete(key);
this.records.set(id, { paths, undone: false });
this.records.set(id, { paths, moves, undone: false });
while (this.records.size > 20) this.records.delete(this.records.keys().next().value!);
for (const target of this.targets) if (this.affects(paths, target.path)) this.mark(target, id);
// Now, before the file watcher reports the old paths gone and their tabs close.
void editorsFollowAppliedMoves(moves);
});
const unprovide = _provideWorkspaceHistory((id, redo) => this.run(id, redo));
return () => {
@@ -154,14 +157,21 @@ export class WorkspaceHistory {
for (const target of targets)
if (!this.step(target, id, forward))
throw new Error("Undo newer editor changes before undoing this refactoring");
await call(forward ? commands.redoWorkspaceEdit(id) : commands.undoWorkspaceEdit(id));
await this.synced();
for (const target of targets) {
if (!this.targets.has(target)) continue;
const tr = this.step(target, id, forward);
if (tr) target.dispatch(tr);
}
record.undone = !forward;
await withEditorsFollowing(
async () => {
await call(forward ? commands.redoWorkspaceEdit(id) : commands.undoWorkspaceEdit(id));
await this.synced();
for (const target of targets) {
if (!this.targets.has(target)) continue;
const tr = this.step(target, id, forward);
if (tr) target.dispatch(tr);
}
// Editors reopened at moved paths build their history from the record: settle it first.
record.undone = !forward;
},
() => (forward ? record.moves : reversedMoves(record.moves)),
{ save: false },
);
_emitWorkspaceEditHistory({ id, undone: record.undone });
} catch (error) {
// A refused backend restore must leave the initiating editor's history intact.
+59
View File
@@ -0,0 +1,59 @@
import { afterEach, expect, it } from "vitest";
import { onIdeEvent } from "@/platform/ipc";
import { provideEditorService, type EditorService } from "@/workbench/contributions";
import { createMemoryBackend } from "./core/backend";
import { EditorController, useTabs } from "./core/controller";
import { initialTabsState } from "./core/model/tabs";
import { editorsFollowAppliedMoves } from "./fileMoves";
let ctrl: EditorController | null = null;
afterEach(() => {
ctrl?.stop();
ctrl = null;
useTabs.setState(initialTabsState(), true);
});
function setup(files: Record<string, string>) {
const backend = createMemoryBackend(files);
backend.onFsChanged = (h) => onIdeEvent("fsChanged", h);
const controller = new EditorController(backend);
controller.start();
ctrl = controller;
provideEditorService({
openFile: (path, o) => controller.openFile(path, o),
activePath: () => controller.activePath(),
closePath: (path) => controller.closePath(path),
saveAll: async () => {},
} as Partial<EditorService> as EditorService);
return { controller, backend };
}
const tabPaths = () =>
Object.values(useTabs.getState().panes).flatMap((pane) => pane.tabs.map((tab) => tab.input.path));
it("a renamed active file stays the active editor", async () => {
const { controller, backend } = setup({ "/p/A.java": "class A {}", "/p/B.java": "class B {}" });
await controller.openFile("/p/B.java", { focus: false });
await controller.openFile("/p/A.java", { focus: false });
backend.files.set("/p/Renamed.java", backend.files.get("/p/A.java")!);
backend.files.delete("/p/A.java");
await editorsFollowAppliedMoves([{ from: "/p/A.java", to: "/p/Renamed.java" }]);
expect(tabPaths()).toEqual(["/p/B.java", "/p/Renamed.java"]);
expect(controller.activePath()).toBe("/p/Renamed.java");
});
it("a renamed background file leaves the active editor in place", async () => {
const { controller, backend } = setup({ "/p/A.java": "class A {}", "/p/B.java": "class B {}" });
await controller.openFile("/p/A.java", { focus: false });
await controller.openFile("/p/B.java", { focus: false });
backend.files.set("/p/Renamed.java", backend.files.get("/p/A.java")!);
backend.files.delete("/p/A.java");
await editorsFollowAppliedMoves([{ from: "/p/A.java", to: "/p/Renamed.java" }]);
expect(tabPaths().sort()).toEqual(["/p/B.java", "/p/Renamed.java"]);
expect(controller.activePath()).toBe("/p/B.java");
});
+81
View File
@@ -0,0 +1,81 @@
/** IDEA keeps editors on files that a refactoring moves or renames: they reopen at the new paths. */
import type { FileMove } from "@/bindings";
import { openEditorPaths } from "@/editor/api";
import { notifyFilesMoved, trackFileMove } from "@/platform/fileOps";
import { emitLocalIdeEvent } from "@/platform/ipc";
import { isSameOrInside } from "@/platform/paths";
import { useProject } from "@/platform/project";
import { maybeEditorService } from "@/workbench/contributions";
export async function saveAllQuietly(editor: { saveAll(): Promise<void> }) {
try {
await editor.saveAll();
} catch {
/* unsaved files are reported by the editor */
}
}
/** `path` after `moves`. */
export function movedPath(path: string, moves: readonly FileMove[]): string {
let p = path;
for (const m of moves) if (isSameOrInside(p, m.from)) p = m.to + p.slice(m.from.length);
return p;
}
/** Moves in the opposite direction, last first: what Undo of `moves` does. */
export function reversedMoves(moves: readonly FileMove[]): FileMove[] {
return [...moves].reverse().map((m) => ({ from: m.to, to: m.from }));
}
/**
* Runs `run`, which moves the files `done` names, with the editors following: unsaved changes
* are saved first (unless `save` is false), tabs reopen at the new paths.
*/
export async function withEditorsFollowing<T>(
run: () => Promise<T>,
done: (r: T) => readonly FileMove[],
{ save = true }: { save?: boolean } = {},
): Promise<T> {
const projectRoot = () => useProject.getState().project?.root ?? null;
const root = projectRoot();
const editor = maybeEditorService();
const openBefore = editor ? openEditorPaths() : [];
if (editor && save) await saveAllQuietly(editor);
const active = editor?.activePath() ?? null;
const { result, applied } = await trackFileMove(root, async () => {
const result = await run();
const applied = done(result);
if (root === projectRoot()) await notifyFilesMoved(applied);
return { result, applied };
});
if (root !== projectRoot()) return result;
const open = openBefore.filter((p) => applied.some((m) => isSameOrInside(p, m.from)));
if (applied.length)
emitLocalIdeEvent({
type: "fsChanged",
created: applied.map((m) => m.to),
modified: [],
removed: applied.map((m) => m.from),
});
if (!editor || !open.length) return result;
// The editor closes tabs of removed files in a queue; an open that starts before an
// active tab's close counts as superseded and stays in the background.
for (const p of open) await editor.closePath?.(p).catch(() => false);
const ordered = active && open.includes(active) ? [...open.filter((p) => p !== active), active] : open;
for (const p of ordered) await editor.openFile(movedPath(p, applied), { focus: false }).catch(() => {});
if (active && !open.includes(active)) await editor.openFile(active, { focus: false }).catch(() => {});
return result;
}
/**
* Editors follow `moves` that a workspace edit already made (a server's rename, Move, a quick
* fix): called when the backend reports the edit, before the file watcher closes their tabs.
*/
export function editorsFollowAppliedMoves(moves: readonly FileMove[]): Promise<void> {
if (!moves.length) return Promise.resolve();
return withEditorsFollowing(
() => Promise.resolve(),
() => moves,
{ save: false },
);
}
+16
View File
@@ -323,6 +323,22 @@ describe("applying completions", () => {
}
});
it("puts the caret inside the parentheses of a server-inserted call that takes arguments", async () => {
setInvokeRoute(() => Promise.resolve(null));
try {
const { view, req } = setup("x.rea|\n", "", [completionExtension()]);
view.dispatch({ effects: StateEffect.appendConfig.of(lspDoc.of({ doc: 1 } as EditorDocContext)) });
const command = { title: "Apply Completion", command: "jetbrains.kotlin.completion.apply", arguments: ["1"] };
const kotlin = item({ label: "read", kind: "method", labelDetail: "(name: String)", insertText: "", command });
applyLspCompletion(view, makeCompletion(kotlin, req), 5, 5, "insert");
view.dispatch({ changes: { from: 5, insert: "d()" }, annotations: remoteChange.of(true) });
expect(view.state.doc.toString()).toBe("x.read()\n");
expect(view.state.selection.main.head).toBe(7);
} finally {
setInvokeRoute(null);
}
});
it("completes at every caret whose typed prefix matches the main caret's", () => {
const { view, req } = setup("a.cr|\nb.cr\nc.xy", "", [EditorState.allowMultipleSelections.of(true)]);
// Carets after both `cr`s (the main one first) and after `xy`.
+20 -3
View File
@@ -462,6 +462,8 @@ async function applyLateEdits(view: EditorView, c: LspCompletion, insertedAt: nu
interface ServerInsert {
at: number;
others: readonly number[];
/** The item is a call that takes arguments: the caret goes inside an inserted `()`. */
inside?: boolean;
}
const awaitServerInsert = StateEffect.define<ServerInsert | null>();
const serverInsertAt = StateField.define<ServerInsert | null>({
@@ -470,7 +472,11 @@ const serverInsertAt = StateField.define<ServerInsert | null>({
for (const e of tr.effects) if (e.is(awaitServerInsert)) return e.value;
// The edit landed, or the caret moved on before it did.
if (value === null || tr.annotation(remoteChange) || tr.selection) return null;
return { at: tr.changes.mapPos(value.at, -1), others: value.others.map((p) => tr.changes.mapPos(p, -1)) };
return {
at: tr.changes.mapPos(value.at, -1),
others: value.others.map((p) => tr.changes.mapPos(p, -1)),
inside: value.inside,
};
},
});
@@ -541,7 +547,9 @@ const caretAfterServerInsert = EditorState.transactionFilter.of((tr) => {
if (tr.changes.touchesRange(from, to)) continue;
others.push({ from: tr.changes.mapPos(from, 1), to: tr.changes.mapPos(to, -1) });
}
const selection = EditorSelection.cursor(mainAfter);
const inside =
pending.inside && /\(\)$/.test(landed.insert) && tr.newDoc.sliceString(mainAfter - 2, mainAfter) === "()";
const selection = EditorSelection.cursor(inside ? mainAfter - 1 : mainAfter);
if (!others.length) return [tr, { selection, sequential: true }];
// Not part of this transaction: a remote one is not sent back to the document model.
const changes = others
@@ -553,6 +561,12 @@ const caretAfterServerInsert = EditorState.transactionFilter.of((tr) => {
/** Client-side commands handled by the editor itself (VS Code ids servers commonly send). */
const CLIENT_COMMANDS = new Set(["editor.action.triggerParameterHints", "editor.action.triggerSuggest"]);
/** A function or method whose signature lists parameters (`(name: String)`), as far as the item tells. */
function takesArguments(item: Pick<CompletionItem, "kind" | "labelDetail" | "detail">): boolean {
if (item.kind && !CALLABLE.has(item.kind)) return false;
return /^\s*\(\s*[^)\s]/.test(item.labelDetail ?? item.detail ?? "");
}
/** kotlin-lsp inserts the item itself (`jetbrains.kotlin.completion.apply`): nothing goes in here. */
function serverInserts(item: CompletionItem): boolean {
const cmd = item.command?.command;
@@ -564,7 +578,10 @@ function runCommand(view: EditorView, item: CompletionItem, others: readonly num
if (!command?.command) return;
const cmd = command.command;
const serverInserted = serverInserts(item);
if (serverInserted) view.dispatch({ effects: awaitServerInsert.of({ at: view.state.selection.main.head, others }) });
if (serverInserted)
view.dispatch({
effects: awaitServerInsert.of({ at: view.state.selection.main.head, others, inside: takesArguments(item) }),
});
if (cmd === "editor.action.triggerParameterHints") setTimeout(() => triggerSignatureHelp(view), 0);
else if (cmd === "editor.action.triggerSuggest") setTimeout(() => startCompletion(view), 0);
else if (!CLIENT_COMMANDS.has(cmd) && !cmd.startsWith("editor.")) {
+11
View File
@@ -37,6 +37,17 @@ describe("markdown LaTeX math", () => {
expect(root.querySelector("p")?.textContent?.startsWith("Prices $5 and $10, with ")).toBe(true);
});
it("leaves separate code spans inside dollar signs as code", () => {
const root = parseSafe("($`x` `y`$)");
expect(root.querySelector("p")?.innerHTML).toBe("($<code>x</code> <code>y</code>$)");
});
it("matches a longer backtick delimiter around math inside emphasis", () => {
const root = parseSafe("**($``x` + y``$)**");
expect(root.querySelector("strong .katex annotation")?.textContent).toBe("x` + y");
expect(root.querySelector("code")).toBeNull();
});
it("keeps an unfinished protected delimiter from swallowing a later formula", () => {
const root = parseSafe("Unfinished $`x` and $y$.");
expect(root.querySelector("p > code")?.textContent).toBe("x");
+4 -3
View File
@@ -39,9 +39,10 @@ function findClosingDelimiter(src: string, from: number, delim: string): number
return -1;
}
const PROTECTED_INLINE_DOLLAR = /^\$`([^`\r\n]+)`\$/;
// The first backtick run of the opening length ends the code span.
const PROTECTED_INLINE_DOLLAR = /^\$(?<ticks>`+)(?!`)(?<tex>(?:[^`\r\n]|(?!\k<ticks>(?!`))`+(?!`))+)\k<ticks>\$/;
// Marked masks code spans as `[aaa]` before calling emStrongMask
const MASKED_PROTECTED_INLINE_DOLLAR = /^\$\[(a+)\]\$/;
const MASKED_PROTECTED_INLINE_DOLLAR = /^\$\[(?<tex>a+)\]\$/;
/**
* Matches inline `$...$` from index 0 using Pandoc-style guards so currency
@@ -87,7 +88,7 @@ function matchInlineMath(
if (src[0] === "$") {
const match = protectedDollar.exec(src);
if (match) {
const text = match[1]!;
const text = match.groups!.tex!;
return text.trim() ? { raw: match[0], text, display: false } : null;
}
if (src[1] === "`") return null;
+90
View File
@@ -205,6 +205,96 @@ describe("locationItems", () => {
expect((await locationItems([target("/p/src/a.py", "refresh", 3)]))[0]!.label).toBe("refresh");
});
describe("takes the container only from a type whose body holds the target", () => {
const cart = [
'import { type Cents } from "./money.ts";',
"",
"export interface Product {",
" id: string;",
" price: Cents;",
"}",
"",
"export interface CartLine {",
" product: Product;",
" quantity: number;",
"}",
"",
'export type Discount = { kind: "percent"; percent: number } | { kind: "fixed"; amount: Cents };',
"",
"export class Cart {",
" private discount: Discount | null = null;",
"",
" total(): Cents {",
" return 0;",
" }",
"}",
];
const at = (line: number, col: number) => ({
path: "/p/src/cart.ts",
uri: null,
range: { start: { line, col }, end: { line, col: col + 1 } },
});
beforeEach(() => {
readManyFileLines.mockResolvedValue(new Map([["/p/src/cart.ts", cart]]));
project("/p");
});
it("anonymous targets after a closed interface", async () => {
const union = cart[12]!;
const items = await locationItems([at(12, union.indexOf("{")), at(12, union.lastIndexOf("{ kind"))]);
expect(items.map((i) => [i.label, i.detail])).toEqual([
["cart.ts", "src/cart.ts:13"],
["cart.ts", "src/cart.ts:13"],
]);
});
it("a named target after a closed interface", async () => {
const item = (await locationItems([at(7, cart[7]!.indexOf("CartLine"))]))[0]!;
expect([item.label, item.detail]).toEqual(["CartLine", "src/cart.ts:8"]);
});
it("a member after a closed type, inside its own class", async () => {
const item = (await locationItems([at(17, cart[17]!.indexOf("total"))]))[0]!;
expect([item.label, item.detail]).toEqual(["total", "Cart · src/cart.ts:18"]);
});
it("indentation-delimited bodies: a function after a class, a method after a dict literal", async () => {
const lines = [
"class Config:",
" defaults = {}",
"",
" def load(self) -> None:",
" pass",
"",
"def main() -> None:",
" pass",
];
readManyFileLines.mockResolvedValue(new Map([["/p/src/mod.py", lines]]));
const items = await locationItems([target("/p/src/mod.py", "load", 3), target("/p/src/mod.py", "main", 6)]);
expect(items.map((i) => i.detail)).toEqual(["Config · src/mod.py:4", "src/mod.py:7"]);
const main = {
...target("/p/src/mod.py", "main", 6),
range: { start: { line: 6, col: 0 }, end: { line: 6, col: 3 } },
};
expect((await locationItems([main]))[0]!.detail).toBe("src/mod.py:7");
});
it("Go: a method's container is its receiver, declared outside the struct's body", async () => {
const lines = [
"type Square struct {",
"\tside float64",
"}",
"",
"func (s *Square) Area() float64 {",
"\treturn 0",
"}",
];
readManyFileLines.mockResolvedValue(new Map([["/p/shapes.go", lines]]));
const at = { path: "/p/shapes.go", uri: null, range: { start: { line: 4, col: 17 }, end: { line: 4, col: 21 } } };
expect((await locationItems([at]))[0]!.detail).toBe("Square · shapes.go:5");
});
});
it("does not query the index for index symbols, which carry their container", async () => {
readManyFileLines.mockResolvedValue(new Map());
project("/p");
+61 -13
View File
@@ -172,41 +172,89 @@ const GO_RECEIVER = /^\s*func\s*\(\s*(?:[\p{L}_][\p{L}\p{N}_]*\s+)?\*?\s*([\p{L}
const FENCES = [`"""`, `'''`];
/** Code of a line without comments, strings and docstring text; null for a line with no code. */
type CodeLine = string | null;
/**
* Name of the type a target sits in (the nearest type declaration above it); null without one.
* Name of the type a target sits in (the nearest type declaration above it whose body is still
* open at the target); null without one.
* Text heuristic: docstrings (`"""` / `'''` fences) and line comments (`#`, `//`, `*`…) cannot
* declare a type, so "the base class does all that is needed" in a comment is not one.
*/
export function enclosingType(lines: readonly string[] | null | undefined, target: Location): string | null {
if (!lines) return null;
let container: string | null = null;
const targetLine = lines[target.range.start.line] ?? "";
const receiver = GO_RECEIVER.exec(targetLine)?.[1];
if (receiver) return receiver;
const from = Math.max(0, target.range.start.line - 2000);
const code: CodeLine[] = [];
const declarations: { line: number; end: number; name: string }[] = [];
let fence: string | null = null;
for (let l = Math.max(0, target.range.start.line - 2000); l < target.range.start.line; l++) {
for (let l = from; l < target.range.start.line; l++) {
const line = lines[l] ?? "";
code.push(null);
if (fence) {
if ((line.split(fence).length - 1) % 2 === 1) fence = null;
continue;
}
// Comments first: a `#`/`//` line cannot open a docstring fence either.
const code = line.replace(/(^|\s)(#|\/\/).*$/, "$1");
if (!code.trim()) continue;
const opened = FENCES.find((f) => (code.split(f).length - 1) % 2 === 1);
const text = line.replace(/(^|\s)(#|\/\/).*$/, "$1");
if (!text.trim()) continue;
const opened = FENCES.find((f) => (text.split(f).length - 1) % 2 === 1);
if (opened) {
fence = opened;
continue;
}
// A single-line docstring (fences open and close on the line) is text too.
if (FENCES.some((f) => code.includes(f))) continue;
const m = TYPE_DECLARATION.exec(code);
if (m && !/^\s*(\*|\/\*)/.test(line)) container = (m[1] ?? m[2])!;
if (FENCES.some((f) => text.includes(f)) || /^\s*(\*|\/\*)/.test(line)) continue;
code[l - from] = text;
const m = TYPE_DECLARATION.exec(text);
if (m) declarations.push({ line: l - from, end: m.index + m[0].length, name: (m[1] ?? m[2])! });
}
return container;
code.push(targetLine);
const col = target.range.start.col;
for (const d of declarations.reverse()) if (bodyHolds(code, d.line, d.end, col)) return d.name;
return null;
}
/** Name of the type a target sits in: the nearest type declaration above it, else the file name. */
const STRING_LITERAL = /"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`/g;
/**
* Whether the body of the declaration on `code[line]` (ending at `end`) is still open at `col`
* of the last entry of `code` (the target's line): braces when the body opens with one on the
* declaration's line or the next (Allman style), else indentation (Python, Ruby, a declaration
* without a body).
*/
function bodyHolds(code: readonly CodeLine[], line: number, end: number, col: number): boolean {
const last = code.length - 1;
const next = code.findIndex((c, i) => i > line && i < last && c !== null);
const braced = code[line]!.slice(end).includes("{") || (next > 0 && /^\s*\{/.test(code[next]!));
if (braced) {
let depth = 0;
let opened = false;
for (let i = line; i <= last; i++) {
const text = (i === line ? code[i]!.slice(end) : i === last ? code[i]!.slice(0, col) : code[i]) ?? "";
for (const c of text.replace(STRING_LITERAL, "")) {
if (c === "{") {
depth++;
opened = true;
} else if (c === "}" && --depth === 0 && opened) return false;
}
}
return depth > 0;
}
const indent = (s: string) => s.length - s.trimStart().length;
const own = indent(code[line]!);
for (let i = line + 1; i < code.length; i++) {
const text = code[i];
// A wrapped header (`) : Base {`) continues the declaration.
if (text?.trim() && indent(text) <= own && !/^\s*[)\]]/.test(text)) return false;
}
return true;
}
/** Name of the type a target sits in: the type declaration around it, else the file name. */
export function enclosingTypeName(lines: readonly string[] | null | undefined, target: Location): string {
const receiver = GO_RECEIVER.exec(lines?.[target.range.start.line] ?? "")?.[1];
if (receiver) return receiver;
const found = enclosingType(lines, target);
if (found) return found;
const file = target.path.split(/[\\/]/).pop() ?? target.path;
+44 -11
View File
@@ -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
View File
@@ -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={
@@ -357,3 +357,56 @@ describe("SessionAssets component", () => {
expect(await screen.findByRole("button", { name: "1 Artifact" })).toBeInTheDocument();
});
});
describe("SessionAssets binary file artifacts", () => {
const entries: AgentEntry[] = [
{
type: "tool",
id: "t-doc",
title: "Write spec",
kind: "edit",
status: "completed",
locations: ["/repo/spec.docx"],
output: null,
diffs: [{ path: "/repo/spec.docx", added: 1, removed: 0 }],
},
];
beforeEach(() => {
vi.clearAllMocks();
resetSessionAssetsCacheForTests();
clearDismissedAssets("task-1");
useAgents.setState({ composers: new Map([["task-1", emptyDraft()]]) });
vi.spyOn(ipc, "isTauri").mockReturnValue(true);
vi.spyOn(ipc, "call").mockImplementation(async (promise) => promise);
vi.spyOn(ipc.commands, "vcsRemotes").mockResolvedValue([] as never);
});
afterEach(() => {
vi.restoreAllMocks();
});
async function openArtifact() {
render(<SessionAssets task={makeTask()} entries={entries} head="feat/session" />);
fireEvent.click(await screen.findByRole("button", { name: "1 Artifact" }));
const dialog = await screen.findByRole("dialog", { name: "Artifacts" });
fireEvent.click(within(dialog).getByText("spec.docx"));
}
it("opens a binary file with its application through the backend's checked command", async () => {
const open = vi.spyOn(ipc.commands, "fsOpenWithSystem").mockResolvedValue(null as never);
await openArtifact();
await waitFor(() => expect(open).toHaveBeenCalledWith("/repo/spec.docx"));
expect(openFileMock).not.toHaveBeenCalled();
});
it("falls back to the editor when the backend refuses the launch", async () => {
vi.spyOn(console, "warn").mockImplementation(() => {});
const open = vi
.spyOn(ipc.commands, "fsOpenWithSystem")
.mockRejectedValue({ kind: "unavailable", message: "Project is in Restricted Mode." } as never);
await openArtifact();
await waitFor(() => expect(openFileMock).toHaveBeenCalledWith("/repo/spec.docx", { focus: true }));
expect(open).toHaveBeenCalledWith("/repo/spec.docx");
});
});
+2 -9
View File
@@ -5,6 +5,7 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { AgentEntry, AgentTask, PullRequestSummary } from "@/bindings";
import { call, commands, isTauri, onIdeEvent } from "@/platform/ipc";
import { openWithSystemApp } from "@/platform/fileManager";
import { useTx } from "@/platform/i18n";
import { openExternalUrl } from "@/platform/openUrl";
import { useProject } from "@/platform/project";
@@ -148,15 +149,7 @@ function issueIcon(state: IssueAssetState | undefined): IconName {
}
async function openFileArtifact(artifact: Extract<SessionArtifact, { kind: "file" }>) {
if (artifact.externalBinary && isTauri()) {
try {
const { openPath } = await import("@tauri-apps/plugin-opener");
await openPath(artifact.path);
return;
} catch {
/* fall back to editor */
}
}
if (artifact.externalBinary && (await openWithSystemApp(artifact.path))) return;
await editorService().openFile(artifact.path, { focus: true });
}
+334
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -21,6 +21,7 @@ export const AGENT_SETTINGS_DEFAULTS: ResolvedAgentSettings = {
newTaskApprovals: "bypass",
defaults: {},
mcpServers: {},
skills: {},
};
export function resolveAgentSettings(s: AgentSettings | null | undefined): ResolvedAgentSettings {
@@ -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
View File
@@ -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";
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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();
@@ -16,22 +16,28 @@
border-bottom: 1px solid var(--border);
}
.module {
min-width: 160px;
max-width: 260px;
min-width: min(136px, 100%);
max-width: min(260px, 100%);
}
.search {
flex: 1 1 140px;
min-width: 140px;
min-width: min(140px, 100%);
max-width: 360px;
}
.scope {
min-width: 110px;
min-width: min(96px, 100%);
max-width: min(240px, 100%);
}
.sep {
width: 1px;
height: 16px;
margin: 0 2px;
background: var(--border);
.toolbarActions,
.viewActions {
display: flex;
align-items: center;
gap: var(--space-1);
flex: none;
}
.toolbarActions {
padding-inline-start: var(--space-1);
border-inline-start: 1px solid var(--border);
}
.banner {
flex: none;
@@ -60,13 +66,7 @@
flex: 1;
min-width: 0;
}
.panel {
display: flex;
flex-direction: column;
min-width: 0;
min-height: 0;
}
.panel > * {
.tree {
flex: 1;
min-height: 0;
}
@@ -94,7 +94,6 @@
}
.version {
flex: none;
font-family: var(--font-mono);
font-size: var(--fs-small);
color: var(--fg-secondary);
}
@@ -120,22 +119,24 @@
min-height: 0;
height: 100%;
}
.usagesHeader {
.paneHeader {
flex: none;
display: flex;
align-items: center;
gap: var(--space-1-5);
min-height: 32px;
min-height: calc(var(--h-field) + var(--space-1));
padding: 0 10px;
border-bottom: 1px solid var(--border);
}
.usagesTitle {
.paneTitle {
flex: 1;
min-width: 0;
margin: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-family: var(--font-mono);
font-size: var(--fs-ui);
font-weight: 500;
color: var(--fg-strong);
}
.conflictNote {
@@ -167,7 +168,6 @@
}
.usageVersion {
flex: none;
font-family: var(--font-mono);
color: var(--fg);
}
.usageStatus {
@@ -114,7 +114,8 @@ describe("dependency analyzer", () => {
it("marks conflicts, shows their usages and excludes through the direct dependency", async () => {
ipc.exclude.mockResolvedValue({ path: "/p/pom.xml", range: {} });
render(<DependencyAnalyzer input={{ kind: ANALYZER_KIND, key: ANALYZER_KIND }} />);
fireEvent.click(screen.getByRole("checkbox", { name: "Show conflicts only" }));
fireEvent.click(screen.getByRole("button", { name: "Show conflicts only", pressed: false }));
expect(screen.getByRole("button", { name: "Show conflicts only", pressed: true })).toBeTruthy();
expect(screen.queryByText("com.google.inject:guice")).toBeNull();
fireEvent.mouseDown(screen.getByText("com.google.guava:guava").closest("[role=treeitem]")!, { button: 0 });
expect(screen.getByText("omitted for conflict with 32.1.3-jre")).toBeTruthy();
@@ -213,7 +214,7 @@ describe("dependency analyzer for Gradle", () => {
render(<DependencyAnalyzer input={{ kind: ANALYZER_KIND, key: ANALYZER_KIND }} />);
expect(ipc.gradle).toHaveBeenCalledWith(":app", "runtimeClasspath", false, expect.any(Number), "");
await screen.findByText("com.fasterxml.jackson.core:jackson-databind");
fireEvent.click(screen.getByRole("checkbox", { name: "Show conflicts only" }));
fireEvent.click(screen.getByRole("button", { name: "Show conflicts only", pressed: false }));
expect(screen.queryByText("org.springframework.boot:spring-boot-starter-json")).toBeNull();
fireEvent.mouseDown(screen.getByText("com.fasterxml.jackson.core:jackson-databind").closest("[role=treeitem]")!, {
button: 0,
+93 -58
View File
@@ -4,7 +4,7 @@
* selected artifact every path that brings it in, with Exclude / Jump to Source (Maven)
* and Copy Coordinates. Gradle trees are read per configuration, on demand.
*/
import { useEffect, useMemo, useRef, useState, type MouseEvent } from "react";
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type MouseEvent } from "react";
import clsx from "clsx";
import {
call,
@@ -15,11 +15,10 @@ import {
type MavenDependency,
type MavenProject,
} from "@/platform/ipc";
import { useTx, useTxTemplate, tx } from "@/platform/i18n";
import { useTx, useTxTemplate } from "@/platform/i18n";
import { editorService, notifications, type EditorInput } from "@/workbench/contributions";
import {
Button,
Checkbox,
EmptyState,
Icon,
IconButton,
@@ -313,28 +312,37 @@ function UsagesPane({
moduleIcon: string;
pom: string | null;
}) {
if (!artifact) return <EmptyState title="Select a dependency to see its usages" />;
const usages = sortedUsages(artifact.usages);
const coords = coordinates({ ...artifact, version: artifact.version });
const tx = useTx();
const symbol = artifact ? coordinates(artifact) : null;
return (
<div className={styles.usages}>
<div className={styles.usagesHeader}>
<span className={clsx(styles.usagesTitle, artifact.conflict && styles.conflict)}>{coords}</span>
<IconButton icon="copy" size="small" title="Copy Coordinates" onClick={() => void copyText(coords)} />
<div className={styles.paneHeader}>
<h2 className={styles.paneTitle} title={symbol ?? undefined}>
{symbol ? tx`Usages of ${symbol}` : tx("Usages")}
</h2>
{symbol && (
<IconButton icon="copy" size="small" title="Copy Coordinates" onClick={() => void copyText(symbol)} />
)}
</div>
{artifact.conflict && (
<div className={styles.conflictNote} role="note">
<Icon name="warning" size={16} />
<span>
<T>Versions requested</T>: {artifact.requested.join(", ")}
</span>
</div>
{artifact ? (
<>
{artifact.conflict && (
<div className={styles.conflictNote} role="note">
<Icon name="warning" size={16} />
<span>
<T>Versions requested</T>: {artifact.requested.join(", ")}
</span>
</div>
)}
<div className={styles.usageList} aria-label={tx("Usages")}>
{sortedUsages(artifact.usages).map((u, i) => (
<UsageBlock key={i} usage={u} moduleName={moduleName} moduleIcon={moduleIcon} pom={pom} />
))}
</div>
</>
) : (
<EmptyState title="Select a dependency to see its usages" />
)}
<div className={styles.usageList} aria-label={tx("Usages")}>
{usages.map((u, i) => (
<UsageBlock key={i} usage={u} moduleName={moduleName} moduleIcon={moduleIcon} pom={pom} />
))}
</div>
</div>
);
}
@@ -347,6 +355,18 @@ export function DependencyAnalyzer(_props: { input: EditorInput }) {
const gradleSync = useBuild((s) => s.syncing.gradle);
const root = useBuild((s) => s.root);
const chosen = useAnalyzer((s) => s.module);
const hasProject = !!maven || !!gradle?.length;
const view = useRef<HTMLDivElement>(null);
const [stacked, setStacked] = useState(false);
useLayoutEffect(() => {
const frame = view.current;
if (!frame) return;
const measure = () => setStacked(frame.clientWidth < 580);
measure();
const observer = new ResizeObserver(measure);
observer.observe(frame);
return () => observer.disconnect();
}, [hasProject]);
const [query, setQuery] = useState("");
const [conflictsOnly, setConflictsOnly] = useState(false);
const [scope, setScope] = useState<string>(ALL_SCOPES);
@@ -460,17 +480,41 @@ export function DependencyAnalyzer(_props: { input: EditorInput }) {
showContextMenu({ x: e.clientX, y: e.clientY }, items);
};
if (!maven && !gradle?.length) return <EmptyState title="No Maven or Gradle projects" />;
if (!hasProject) return <EmptyState title="No Maven or Gradle projects" />;
const treeView = (
<div className={styles.body}>
<SplitGroup
orientation="horizontal"
orientation={stacked ? "vertical" : "horizontal"}
id="maven-dependency-analyzer-split"
storageKey="openidea.dependencyAnalyzer.split"
storageKey={stacked ? "openidea.dependencyAnalyzer.split.vertical" : "openidea.dependencyAnalyzer.split"}
>
<SplitPanel id="dependencies" minSize={200} className={styles.panel}>
<SplitPanel id="dependencies" minSize={stacked ? "30%" : 200}>
<div className={styles.paneHeader}>
<h2 className={styles.paneTitle}>
<T>Resolved Dependencies</T>
</h2>
<div className={styles.viewActions}>
<IconButton
icon="list"
size="small"
iconSize={16}
title="Show as List"
pressed={mode === "list"}
onClick={() => setMode("list")}
/>
<IconButton
icon="hierarchy"
size="small"
iconSize={16}
title="Show as Tree"
pressed={mode === "tree"}
onClick={() => setMode("tree")}
/>
</div>
</div>
<Tree<Node>
className={styles.tree}
aria-label="Dependencies"
roots={roots}
getKey={(n) => n.key}
@@ -501,7 +545,7 @@ export function DependencyAnalyzer(_props: { input: EditorInput }) {
/>
</SplitPanel>
<SplitHandle />
<SplitPanel id="usages" minSize={240} className={styles.panel}>
<SplitPanel id="usages" minSize={stacked ? "30%" : 240}>
<UsagesPane
artifact={selected}
moduleName={module?.displayName ?? gradleProject?.name ?? ""}
@@ -514,7 +558,7 @@ export function DependencyAnalyzer(_props: { input: EditorInput }) {
);
return (
<div className={styles.view}>
<div ref={view} className={styles.view}>
<div className={styles.toolbar} role="toolbar" aria-label={tx("Dependency Analyzer")}>
<Select
aria-label="Module"
@@ -534,7 +578,6 @@ export function DependencyAnalyzer(_props: { input: EditorInput }) {
aria-label="Search dependencies"
clearable
/>
<Checkbox checked={conflictsOnly} onChange={setConflictsOnly} label="Show conflicts only" />
{gradlePath != null ? (
<Select
aria-label="Configuration"
@@ -556,37 +599,29 @@ export function DependencyAnalyzer(_props: { input: EditorInput }) {
onChange={setScope}
/>
)}
<span className={styles.sep} />
<IconButton
icon="list"
size="small"
iconSize={16}
title="Show as List"
pressed={mode === "list"}
onClick={() => setMode("list")}
/>
<IconButton
icon="hierarchy"
size="small"
iconSize={16}
title="Show as Tree"
pressed={mode === "tree"}
onClick={() => setMode("tree")}
/>
<span className={styles.sep} />
{gradlePath != null ? (
configuration === null && gradleSync ? (
<IconButton icon="stop" size="small" iconSize={16} title="Stop" onClick={() => cancelSync("gradle")} />
) : report.loading ? (
<IconButton icon="stop" size="small" iconSize={16} title="Stop" onClick={report.cancel} />
<div className={styles.toolbarActions}>
<IconButton
icon="warning"
size="small"
iconSize={16}
title="Show conflicts only"
pressed={conflictsOnly}
onClick={() => setConflictsOnly((current) => !current)}
/>
{gradlePath != null ? (
configuration === null && gradleSync ? (
<IconButton icon="stop" size="small" iconSize={16} title="Stop" onClick={() => cancelSync("gradle")} />
) : report.loading ? (
<IconButton icon="stop" size="small" iconSize={16} title="Stop" onClick={report.cancel} />
) : (
<IconButton icon="refresh" size="small" iconSize={16} title="Refresh" onClick={refreshGradle} />
)
) : syncing ? (
<IconButton icon="stop" size="small" iconSize={16} action="maven.cancelReload" />
) : (
<IconButton icon="refresh" size="small" iconSize={16} title="Refresh" onClick={refreshGradle} />
)
) : syncing ? (
<IconButton icon="stop" size="small" iconSize={16} action="maven.cancelReload" />
) : (
<IconButton icon="refresh" size="small" iconSize={16} action="maven.reload" />
)}
<IconButton icon="refresh" size="small" iconSize={16} action="maven.reload" />
)}
</div>
</div>
{gradlePath != null ? (
<>
@@ -35,7 +35,7 @@ it("waits for pending typing before undoing the entire backend transaction", asy
release = resolve;
}),
);
emitLocalIdeEvent({ type: "workspaceEditApplied", id: 17, paths: [], byAgent: false });
emitLocalIdeEvent({ type: "workspaceEditApplied", id: 17, paths: [], moves: [], byAgent: false });
const action = notices[0]!.actions![0]!;
expect(action.label).toBe("Undo");
const pending = action.run();
@@ -47,13 +47,13 @@ it("waits for pending typing before undoing the entire backend transaction", asy
it("reports a refused undo instead of discarding newer work", async () => {
mocks.undo.mockRejectedValue(new Error("a.txt changed"));
emitLocalIdeEvent({ type: "workspaceEditApplied", id: 18, paths: [], byAgent: false });
emitLocalIdeEvent({ type: "workspaceEditApplied", id: 18, paths: [], moves: [], byAgent: false });
await notices[0]!.actions![0]!.run();
expect(notices[1]).toMatchObject({ level: "error", title: "Cannot undo refactoring", body: "a.txt changed" });
});
it("does not apply an old notification's id to a different project", async () => {
emitLocalIdeEvent({ type: "workspaceEditApplied", id: 19, paths: [], byAgent: false });
emitLocalIdeEvent({ type: "workspaceEditApplied", id: 19, paths: [], moves: [], byAgent: false });
const previous = useProject.getState().project;
useProject.setState({ project: { ...previous, root: "/different-project" } as NonNullable<typeof previous> });
try {
@@ -66,6 +66,6 @@ it("does not apply an old notification's id to a different project", async () =>
});
it("does not announce an agent's edit as a refactoring", () => {
emitLocalIdeEvent({ type: "workspaceEditApplied", id: 20, paths: [], byAgent: true });
emitLocalIdeEvent({ type: "workspaceEditApplied", id: 20, paths: [], moves: [], byAgent: true });
expect(notices).toEqual([]);
});
+16 -2
View File
@@ -1,7 +1,21 @@
import { describe, expect, it } from "vitest";
import { definitionInsertions, matchesStep, snippetStyle, stepDefinitions, stepSnippet, type FeatureStep } from "./steps";
import {
definitionInsertions,
matchesStep,
snippetStyle,
stepDefinitions,
stepSnippet,
type FeatureStep,
} from "./steps";
const step = (text: string): FeatureStep => ({ from: 0, to: 0, keyword: "Given ", type: "Given", text, matchText: text });
const step = (text: string): FeatureStep => ({
from: 0,
to: 0,
keyword: "Given ",
type: "Given",
text,
matchText: text,
});
const apply = (text: string, insertions: { at: number; text: string }[]) =>
[...insertions].sort((a, b) => b.at - a.at).reduce((out, i) => out.slice(0, i.at) + i.text + out.slice(i.at), text);
+4 -1
View File
@@ -141,7 +141,10 @@ export function pythonStepSnippet(
const decorator = keyword.toLowerCase();
const quoted = (s: string) => `'${s.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
if (framework === "pytest-bdd")
return { text: [`@${decorator}(${quoted(text)})`, "def _():", " raise NotImplementedError", ""].join("\n"), body: 2 };
return {
text: [`@${decorator}(${quoted(text)})`, "def _():", " raise NotImplementedError", ""].join("\n"),
body: 2,
};
// behave reads the pattern as a `parse` format: braces in the step are literal.
const format = text.replace(/[{}]/g, "$&$&");
return {
@@ -1,12 +1,12 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import type { FileMove, WorkspaceEdit } from "@/bindings";
import { movedPath } from "@/editor/fileMoves";
import { onFilesMoved } from "@/platform/fileOps";
import { provideNotificationService } from "@/workbench/contributions";
import {
lastFileRefactoring,
mergeEdits,
movedPath,
runFileRefactoring,
setRefactorBackendForTests,
touchesOtherFiles,
+2 -52
View File
@@ -5,10 +5,8 @@
* files change, then the move itself — one step that Undo reverts.
*/
import type { FileMove, UndoOutcome, WorkspaceEdit } from "@/bindings";
import { openEditorPaths } from "@/editor/api";
import { notifyFilesMoved, trackFileMove } from "@/platform/fileOps";
import { call, commands, emitLocalIdeEvent, isCancelled, isTauri, nextRequestId } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { saveAllQuietly, withEditorsFollowing } from "@/editor/fileMoves";
import { call, commands, isCancelled, isTauri, nextRequestId } from "@/platform/ipc";
import { maybeEditorService, notifications } from "@/workbench/contributions";
import { projectFs } from "./fs";
import { isSameOrInside, nameOf, parentOf } from "./paths";
@@ -166,54 +164,6 @@ export function touchesOtherFiles(edit: WorkspaceEdit, moves: readonly FileMove[
);
}
// ---------------------------------------------------------------------------
// Editors follow the move
async function saveAllQuietly(editor: { saveAll(): Promise<void> }) {
try {
await editor.saveAll();
} catch {
/* unsaved files are reported by the editor */
}
}
/** `path` after `moves`. */
export function movedPath(path: string, moves: readonly FileMove[]): string {
let p = path;
for (const m of moves) if (isSameOrInside(p, m.from)) p = m.to + p.slice(m.from.length);
return p;
}
/** IDEA retargets editors of moved files: unsaved changes are saved first, tabs reopen at the new paths. */
async function withEditorsFollowing<T>(run: () => Promise<T>, done: (r: T) => FileMove[]): Promise<T> {
const projectRoot = () => useProject.getState().project?.root ?? null;
const root = projectRoot();
const editor = maybeEditorService();
const openBefore = editor ? openEditorPaths() : [];
if (editor) await saveAllQuietly(editor);
const active = editor?.activePath() ?? null;
const { result, applied } = await trackFileMove(root, async () => {
const result = await run();
const applied = done(result);
if (root === projectRoot()) await notifyFilesMoved(applied);
return { result, applied };
});
if (root !== projectRoot()) return result;
const open = openBefore.filter((p) => applied.some((m) => isSameOrInside(p, m.from)));
if (applied.length)
emitLocalIdeEvent({
type: "fsChanged",
created: applied.map((m) => m.to),
modified: [],
removed: applied.map((m) => m.from),
});
if (!editor || !open.length) return result;
const ordered = active && open.includes(active) ? [...open.filter((p) => p !== active), active] : open;
for (const p of ordered) await editor.openFile(movedPath(p, applied), { focus: false }).catch(() => {});
if (active && !open.includes(active)) await editor.openFile(active, { focus: false }).catch(() => {});
return result;
}
// ---------------------------------------------------------------------------
// Run / undo
+89
View File
@@ -0,0 +1,89 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { RunConfig } from "@/platform/ipc";
import {
provideNotificationService,
provideToolWindowService,
type ToolWindowService,
} from "@/workbench/contributions";
import { resetRuns, rerunFailed, runSelectedTests, runtime, startRun, useRun } from "./store";
const classModules = vi.hoisted(() =>
vi.fn(async (cls: string) => ({ "com.a.AlphaTest": ["alpha"], "com.b.BetaTest": ["beta"] })[cls] ?? []),
);
vi.mock("@/platform/javaLaunch", async (importOriginal) => ({
...(await importOriginal<typeof import("@/platform/javaLaunch")>()),
classModules,
}));
vi.mock("./dialogs", () => ({
confirmRerun: vi.fn(async () => true),
confirmTerminate: vi.fn(async () => true),
promptValue: vi.fn(),
RunDialogsOverlay: () => null,
}));
const rootTests: RunConfig = {
id: "gradle:test",
name: "gradle test",
kind: "gradle",
command: "./gradlew",
args: ["test"],
cwd: null,
env: {},
detected: true,
isTest: true,
debugAdapter: null,
};
beforeEach(() => {
resetRuns();
provideToolWindowService({ show: vi.fn(), isVisible: () => true } as unknown as ToolWindowService);
provideNotificationService({ notify: () => undefined });
});
const failedRootRun = async () => {
const session = (await startRun(rootTests))!;
runtime(session.id)!.tests!.apply([
{ type: "result", path: ["com.a.AlphaTest", "one"], status: "failed" },
{ type: "result", path: ["com.b.BetaTest", "two"], status: "failed" },
]);
useRun.setState({
sessions: useRun.getState().sessions.map((s) => (s.id === session.id ? { ...s, status: "finished" } : s)),
});
return session;
};
const lastArgs = () => useRun.getState().sessions.at(-1)!.config.args;
describe("Gradle reruns after a run of the root test task", () => {
it("Rerun Failed Tests runs each test in its own subproject's test task", async () => {
const session = await failedRootRun();
expect(await rerunFailed(session.id)).toBe(true);
await vi.waitFor(() =>
expect(lastArgs()).toEqual([
":alpha:test",
"--tests",
"com.a.AlphaTest.one",
":beta:test",
"--tests",
"com.b.BetaTest.two",
"--continue",
]),
);
});
it("running a selection from the tree does the same", async () => {
const session = await failedRootRun();
const beta = runtime(session.id)!.tests!.node(["com.b.BetaTest", "two"]);
expect(await runSelectedTests(session.id, [beta.id], false)).toBe(true);
expect(lastArgs()).toEqual([":beta:test", "--tests", "com.b.BetaTest.two"]);
});
it("keeps today's command line when a class is not found", async () => {
classModules.mockResolvedValueOnce([]);
const session = await failedRootRun();
expect(await rerunFailed(session.id)).toBe(true);
await vi.waitFor(() =>
expect(lastArgs()).toEqual(["test", "--tests", "com.a.AlphaTest.one", "--tests", "com.b.BetaTest.two"]),
);
});
});
+9 -3
View File
@@ -55,6 +55,7 @@ import { TeamcityOutput } from "./testing/teamcity";
import type { TestStdout } from "./testing/types";
import { recordTestStates } from "./testing/states";
import { failedTestPaths, leafTestPaths, rerunFailedConfigs, testsConfigs } from "./testing/rerun";
import { testsBySubproject } from "./testing/gradleSubprojects";
import { buildCMake, isCMakeBuild } from "./cmake";
import { compoundChildren } from "./configs";
import { remoteLabel, startWithRemedies } from "./remote";
@@ -1539,8 +1540,11 @@ export async function rerunFailed(sessionId: string): Promise<boolean> {
const session = getSession(sessionId);
if (!session || isLive(session)) return false;
const base = baseConfigOf(session);
const selection = rerunFailedConfigs(base, failedTests(sessionId));
const derived = selection instanceof Promise ? await selection : selection;
const paths = failedTests(sessionId);
const selection = rerunFailedConfigs(base, paths);
const derived = await Promise.all(
(selection instanceof Promise ? await selection : selection).map((c) => testsBySubproject(c, paths)),
);
if (getSession(sessionId) !== session || isLive(session)) return false;
if (!derived.length) return false;
derived.forEach((config, index) => void startRun(config, index === 0 ? sessionId : undefined, base));
@@ -1564,7 +1568,9 @@ export async function runSelectedTests(
const base = baseConfigOf(session);
const name = nodes.length === 1 ? nodes[0]!.name : `${paths.length} tests`;
const selection = testsConfigs(base, paths, name);
const derived = selection instanceof Promise ? await selection : selection;
const derived = await Promise.all(
(selection instanceof Promise ? await selection : selection).map((c) => testsBySubproject(c, paths)),
);
if (getSession(sessionId) !== session) return false;
if (!derived.length) return false;
for (const [index, next] of derived.entries()) {
@@ -0,0 +1,91 @@
import { describe, expect, it } from "vitest";
import type { RunConfig } from "@/platform/ipc";
import { testsBySubproject } from "./gradleSubprojects";
const cfg = (args: string[], over: Partial<RunConfig> = {}): RunConfig => ({
id: "gradle:test",
name: "Failed: gradle test",
kind: "gradle",
command: "./gradlew",
args,
cwd: null,
env: {},
detected: true,
isTest: true,
debugAdapter: null,
...over,
});
const modules: Record<string, string[]> = {
"com.a.AlphaTest": ["alpha"],
"com.b.BetaTest": ["services/beta"],
"com.r.RootTest": [""],
"com.x.Twice": ["alpha", "services/beta"],
};
const find = async (cls: string) => modules[cls] ?? [];
describe("Gradle tests by subproject", () => {
it("runs each failed test with its own subproject's test task", async () => {
const derived = cfg(["test", "--tests", "com.a.AlphaTest.one", "--tests", "com.b.BetaTest$Inner.two"]);
const paths = [
["com.a.AlphaTest", "one()"],
["com.b.BetaTest$Inner", "two"],
];
expect((await testsBySubproject(derived, paths, find)).args).toEqual([
":alpha:test",
"--tests",
"com.a.AlphaTest.one",
":services:beta:test",
"--tests",
"com.b.BetaTest$Inner.two",
"--continue",
]);
});
it("keeps the other options and needs no --continue for one subproject", async () => {
const derived = cfg(["--offline", "test", "--tests", "com.b.BetaTest"]);
expect((await testsBySubproject(derived, [["com.b.BetaTest"]], find)).args).toEqual([
"--offline",
":services:beta:test",
"--tests",
"com.b.BetaTest",
]);
});
it("addresses the root project's own tests as :test next to a subproject's", async () => {
const derived = cfg(["test", "--tests", "com.r.RootTest.a", "--tests", "com.a.AlphaTest.one"]);
const paths = [
["com.r.RootTest", "a"],
["com.a.AlphaTest", "one"],
];
expect((await testsBySubproject(derived, paths, find)).args).toEqual([
":test",
"--tests",
"com.r.RootTest.a",
":alpha:test",
"--tests",
"com.a.AlphaTest.one",
"--continue",
]);
});
it("keeps the configuration when a class is not found in exactly one module", async () => {
const derived = cfg(["test", "--tests", "com.a.AlphaTest.one", "--tests", "com.z.Gone.x"]);
const paths = [
["com.a.AlphaTest", "one"],
["com.z.Gone", "x"],
];
expect(await testsBySubproject(derived, paths, find)).toBe(derived);
const twice = cfg(["test", "--tests", "com.x.Twice"]);
expect(await testsBySubproject(twice, [["com.x.Twice"]], find)).toBe(twice);
});
it("leaves runs alone that already name a task, run only root tests, or are not Gradle", async () => {
const scoped = cfg([":alpha:test", "--tests", "com.a.AlphaTest.one"]);
expect(await testsBySubproject(scoped, [["com.a.AlphaTest", "one"]], find)).toBe(scoped);
const root = cfg(["test", "--tests", "com.r.RootTest.a"]);
expect(await testsBySubproject(root, [["com.r.RootTest", "a"]], find)).toBe(root);
const maven = cfg(["test", "-Dtest=com.a.AlphaTest#one"], { kind: "maven", command: "./mvnw" });
expect(await testsBySubproject(maven, [["com.a.AlphaTest", "one"]], find)).toBe(maven);
});
});
@@ -0,0 +1,51 @@
import type { RunConfig } from "@/platform/ipc";
import { classModules } from "@/platform/javaLaunch";
import { inGradleModule } from "../gradleModuleTests";
const isGradle = (config: Pick<RunConfig, "kind" | "command">) =>
config.kind === "gradle" || /(^|[/\\])gradlew?(\.bat)?$/.test(config.command);
/** `--tests` filter of a test tree path, as `rerun.ts` writes it. */
const filterOf = (path: string[]) =>
path.length >= 2 ? `${path[0]}.${path[path.length - 1]!.replace(/\(\)$/, "")}` : path[0]!;
/**
* `derived`, a run of the build's plain `test` task narrowed to the tests at `paths`, with each
* test's filter on its own subproject's test task (`:alpha:test --tests A :beta:test --tests B`;
* a task's `--tests` applies to that task only). The plain task filters every subproject's tests,
* and one without a match fails the build before the others run. IDEA reruns the original tasks
* and fails the same way. `derived` unchanged when a test class is not found in exactly one
* module, or every test is the root project's.
*/
export async function testsBySubproject(
derived: RunConfig,
paths: readonly string[][],
findModules: (className: string) => Promise<string[]> = classModules,
): Promise<RunConfig> {
if (!isGradle(derived) || !derived.args.includes("test") || !paths.length) return derived;
const groups = new Map<string, string[]>();
for (const path of paths) {
const modules = await findModules(path[0]!.split("$")[0]!);
if (modules.length !== 1) return derived;
const filters = groups.get(modules[0]!) ?? [];
filters.push(filterOf(path));
groups.set(modules[0]!, filters);
}
if (groups.size === 1 && groups.has("")) return derived;
let cwd = derived.cwd;
const tasks = [...groups].flatMap(([module, filters]) => {
const scoped = inGradleModule({ ...derived, args: ["test"] }, module);
cwd = scoped.cwd;
const task = scoped.args[0] === "test" ? ":test" : scoped.args[0]!;
return [task, ...[...new Set(filters)].flatMap((f) => ["--tests", f])];
});
const args: string[] = [];
for (let i = 0; i < derived.args.length; i++) {
const a = derived.args[i]!;
if (a === "--tests") i++;
else if (a === "test") args.push(...tasks);
else if (!a.startsWith("--tests=")) args.push(a);
}
if (groups.size > 1 && !args.includes("--continue")) args.push("--continue");
return { ...derived, cwd, args };
}
@@ -165,6 +165,15 @@ describe("items and rows", () => {
expect([t!.col, t!.endCol]).toEqual([8, 13]);
});
it("textItems keeps each window of a long line as its own item", () => {
const items = textItems("/p/min.js", "min.js", [
{ line: 0, text: "x foo x", ranges: [[2, 5]], textOffset: 0 },
{ line: 0, text: "x foo x", ranges: [[2, 5]], textOffset: 2000 },
]);
expect(new Set(items.map((i) => i.key)).size).toBe(2);
expect(items.map((i) => i.col)).toEqual([2, 2002]);
});
it("buildRows orders sections, adds headers and more rows", () => {
const sections = new Map<SectionId, SectionState>([
[
@@ -219,6 +219,24 @@ describe("result helpers", () => {
expect(rows[0]).toMatchObject({ text: "let foo = 1", ranges: [[4, 7]], col: 18, endCol: 21, matched: ["foo"] });
});
it("matchRows keeps each window of a long line as its own row", () => {
const rows = matchRows([
{
path: "/p/min.js",
relPath: "min.js",
matches: [
{ line: 0, text: "x foo x", ranges: [[2, 5]], textOffset: 0 },
{ line: 0, text: "x foo x", ranges: [[2, 5]], textOffset: 2000 },
],
},
]);
expect(new Set(rows.map((r) => r.key)).size).toBe(2);
expect(rows.flatMap((r) => r.starts)).toEqual([
{ line: 0, col: 2 },
{ line: 0, col: 2002 },
]);
});
it("previewReplacement supports Rust-style regex groups", () => {
const re = { pattern: "(\\w+)=(\\d+)", isRegex: true, caseSensitive: true };
expect(previewReplacement("a=1", re, "${2}:$1")).toBe("1:a");
@@ -87,6 +87,14 @@ describe("buildFindTree", () => {
expect(roots.map((n) => n.key)).toEqual(["f:/p/a.ts", "f:/p/src/a.ts", "f:/p/src/b.ts"]);
});
it("keeps each window of a long line as its own node", () => {
const long = file("min.js");
long.matches.push({ ...long.matches[0]!, textOffset: 2000 });
const [f] = buildFindTree([long]);
const children = f?.kind === "file" ? f.children : [];
expect(new Set(children.map((n) => n.key)).size).toBe(2);
});
it("groups files by directory on request", () => {
const roots = buildFindTree(files, true);
expect(roots.map((n) => (n.kind === "dir" ? [n.label, n.count] : n.kind))).toEqual([
+1 -1
View File
@@ -442,7 +442,7 @@ export function textItems(path: string, rel: string, matches: readonly LineMatch
const first = m.ranges[0] ?? [0, 0];
out.push({
kind: "text",
key: `t:${path}:${m.line}:${first[0]}`,
key: `t:${path}:${m.line}:${first[0] + m.textOffset}`,
path,
rel,
line: m.line,
+1 -1
View File
@@ -95,7 +95,7 @@ export function buildFindTree(files: readonly FileMatches[], groupByDirectory =
const first = m.ranges[0] ?? [0, 0];
return {
kind: "match",
key: `m:${f.path}:${m.line}`,
key: `m:${f.path}:${m.line}:${first[0] + m.textOffset}`,
path: f.path,
line: m.line,
col: first[0] + m.textOffset,
+2 -1
View File
@@ -197,7 +197,8 @@ export function matchRows(files: readonly FileMatches[]): MatchRow[] {
.filter(([s, e]) => e > s);
const first = m.ranges[0] ?? [0, 0];
rows.push({
key: `${f.path}:${m.line}`,
// A long line comes in several windows: the column tells them apart.
key: `${f.path}:${m.line}:${first[0] + m.textOffset}`,
path: f.path,
relPath: f.relPath,
line: m.line,
@@ -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
View File
@@ -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),
@@ -123,11 +123,12 @@
.radio {
display: inline-flex;
flex: none;
white-space: nowrap;
max-inline-size: 100%;
align-items: center;
gap: var(--space-1-5);
}
.radio input {
flex: none;
margin: 0;
accent-color: var(--accent);
}
+5
View File
@@ -643,6 +643,11 @@ export const VCS_PAGES: PageSpec[] = [
label: "Use non-modal commit interface",
hint: "When off, Local Changes and Stash are tabs of the Git tool window and Commit opens a dialog.",
},
{
kind: "toggle",
key: "vcs.commit.includeChangesByDefault",
label: "Include changes in the commit by default",
},
{ kind: "toggle", key: "vcs.commit.clearInitialMessage", label: "Clear initial commit message" },
],
},
+45
View File
@@ -422,6 +422,51 @@ describe("terminal open", () => {
});
});
describe("deferred terminal focus", () => {
function openable(key: string) {
const container = document.createElement("div");
document.body.appendChild(container);
const session = new TerminalSession({ key, cwd: "/tmp", onChange: () => undefined, onFocus: () => undefined });
Object.defineProperty(session.host, "offsetWidth", { configurable: true, get: () => 400 });
Object.defineProperty(session.host, "offsetHeight", { configurable: true, get: () => 300 });
const textarea = document.createElement("textarea");
vi.spyOn(session.term, "open").mockImplementation(() => undefined);
Object.defineProperty(session.term, "textarea", { configurable: true, get: () => textarea });
const focus = vi.spyOn(session.term, "focus").mockImplementation(() => undefined);
return { container, session, focus };
}
afterEach(() => vi.useRealTimers());
it("takes the caret once xterm opens when focus stayed put", () => {
vi.useFakeTimers();
const { container, session, focus } = openable("s-stay");
session.focus();
session.attach(container);
vi.advanceTimersByTime(FIT_SETTLE_MS);
expect(focus).toHaveBeenCalledTimes(1);
session.dispose();
container.remove();
});
it("leaves focus that moved elsewhere before xterm opened", () => {
vi.useFakeTimers();
const { container, session, focus } = openable("s-moved");
const tree = document.createElement("div");
tree.tabIndex = 0;
document.body.appendChild(tree);
session.focus();
tree.focus();
session.attach(container);
vi.advanceTimersByTime(FIT_SETTLE_MS);
expect(focus).not.toHaveBeenCalled();
expect(document.activeElement).toBe(tree);
session.dispose();
container.remove();
tree.remove();
});
});
describe("terminal font zoom", () => {
afterEach(() => {
unbindTerminals();
+14 -1
View File
@@ -254,6 +254,8 @@ export class TerminalSession {
private opened = false;
/** `focus()` arrived before the textarea existed (the pane is focused while xterm is still closed). */
private pendingFocus = false;
/** What had focus when `pendingFocus` was set: a later move elsewhere cancels it. */
private pendingFocusFrom: Element | null = null;
/** Bounds retries when the pane has no box yet, or xterm cannot measure a cell. */
private fitAttempts = 0;
private disposed = false;
@@ -679,7 +681,17 @@ export class TerminalSession {
this.opts.onFocus(this.key);
});
this.watchImeCommit();
if (this.pendingFocus) this.focus();
if (this.pendingFocus) {
this.pendingFocus = false;
if (this.focusStayedHere()) this.focus();
}
}
/** Whether focus is still where the deferred `focus()` left it, or in this terminal's own window. */
private focusStayedHere(): boolean {
const active = document.activeElement;
if (!active || active === document.body || active === this.pendingFocusFrom) return true;
return this.host.contains(active) || !!this.host.closest("[data-toolwindow]")?.contains(active);
}
detach(container: HTMLElement) {
@@ -990,6 +1002,7 @@ export class TerminalSession {
this.clearUnseenDone();
if (!this.opened || !this.term.textarea) {
this.pendingFocus = true;
this.pendingFocusFrom = document.activeElement;
this.scheduleFit();
return;
}
+13 -6
View File
@@ -3,7 +3,7 @@
* parts also make the Git window's Local Changes / Stash tabs and the Commit dialog.
*/
import { writeClipboardText } from "@/platform/clipboard";
import { useWorkflowSettings } from "@/platform/workflowSettings";
import { useWorkflowSettings, workflowSettings } from "@/platform/workflowSettings";
import { formatBinding, isMacHost, macStroke, normalizeBinding, shortcutLabel, strokeOf } from "@/platform/keymap";
import {
useCallback,
@@ -536,7 +536,11 @@ function useCommitChecks() {
export function useIncludedCount(): number {
const status = useVcs((s) => s.status);
const checks = useCommitChecks();
return useMemo(() => planCommit(status, checks).included.length, [status, checks]);
const includeByDefault = useWorkflowSettings((s) => s.vcs.commit.includeChangesByDefault);
return useMemo(
() => planCommit(status, checks, includeByDefault).included.length,
[status, checks, includeByDefault],
);
}
/**
@@ -641,6 +645,7 @@ export function ChangesTree({ mode }: { mode: "commit" | "local" | "dialog" }) {
const changelists = useChangelists((s) => s.state);
const lists = staging ? undefined : changelists;
const checks = useCommitChecks();
const includeByDefault = useWorkflowSettings((s) => s.vcs.commit.includeChangesByDefault);
const checkboxes = mode !== "local" && !staging;
const [dropTarget, setDropTarget] = useState<string | null>(null);
// IDEA starts with Unversioned Files collapsed.
@@ -755,10 +760,12 @@ export function ChangesTree({ mode }: { mode: "commit" | "local" | "dialog" }) {
const files = filesOf(nodes);
const { status: st, root: r } = useVcs.getState();
const cur = withListDefaults(st, r ?? "", useChangelists.getState().state, useCommit.getState().checks);
const agg = aggregateCheck(files, cur);
const includeByDefault = workflowSettings().vcs.commit.includeChangesByDefault;
const agg = aggregateCheck(files, cur, includeByDefault);
const target = agg.on === files.length && !agg.indeterminate ? "none" : "all";
const next = new Map(cur);
for (const f of files) next.set(f.path, files.length === 1 ? toggledCheck(checkOf(f, cur)) : target);
for (const f of files)
next.set(f.path, files.length === 1 ? toggledCheck(checkOf(f, cur, includeByDefault)) : target);
useCommit.setState({ checks: next });
}, []);
@@ -934,7 +941,7 @@ export function ChangesTree({ mode }: { mode: "commit" | "local" | "dialog" }) {
</span>
}
renderNode={(n, st) => {
const agg = aggregateCheck(n.files, checks);
const agg = aggregateCheck(n.files, checks, includeByDefault);
const label = (
<span
className={clsx(
@@ -1323,7 +1330,7 @@ function CommitPanel({ included }: { included: number }) {
return (
<div className={styles.commit}>
<CommitMessageField included={included} runner={runner} />
<CommitMessageField included={included} runner={runner} autoFocus />
<div className={styles.commitActions}>
<Button variant="primary" disabled={!canCommit} onClick={() => void runner.run(false)} title="⌘↩">
<T>{commitLabel(amend, checkProblems.length > 0, commitAll)}</T>
Loaded 100 of 118 files, more files were not shown because too many files have changed in this diff. Show more