Compare commits

...
Author SHA1 Message Date
l0ng-ai 4abad32250 fix(vcs): keep focus on the commit message when the Commit window opens
Activating a tool window focuses its first field or tree one frame later
unless its content marks a preferred target. The Commit window's message
wasn't marked, so after ⌘K focused the message, the activation could move
focus to the Changes tree, depending on timing. The message is now the
window's preferred focus.
2026-11-21 03:55:12 +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
l0ng-ai 423bf2c733 fix(settings): align Code Completion case choices (#4852)
Settings > Editor > General > Code Completion shows both case-matching choices beside the Match case checkbox; the options wrap when space is limited and stay visible when disabled, so the saved choice is easy to see.
2026-11-21 01:11:23 +08:00
l0ng-ai 73d1470940 fix(settings): align Actions on Save in a table (#4848)
Settings > Tools > Actions on Save groups the three save preferences in a table: each row keeps its description with the checkbox and shows Save or Save All in the trigger column while enabled; the scope switch and the whitespace settings link stay below the table.
2026-11-21 00:57:56 +08:00
l0ng-ai c83b0b1442 fix(settings): pair postfix templates with a code preview (#4843)
Settings > Editor > General > Postfix Completion puts the template list beside a preview of the selected template, showing the typed expression and its expansion from the existing template body; in narrow panes the preview moves below the list.
2026-11-21 00:41:46 +08:00
l0ng-ai d16993e175 fix(lsp): end a cancelled server task the server never ends (#4842)
Cancelling a server-reported background task (window/workDoneProgress/cancel) left it on Cancelling for good when the server never sent end, e.g. Pyright stuck before loading its workspace. The server now gets five seconds to end the task; after that the IDE ends it and clears the server's busy state, ignoring later reports on that token.
2026-11-21 00:36:53 +08:00
l0ng-ai 5d4cdac3c7 fix(settings): align the File Colors rules table (#4839)
Settings > Editor > File Colors puts the placement switches together above the rules; a table keeps scope names aligned with their swatches and colour names, with the toolbar and headings sticky while the rules scroll. The selected rule's editor sits directly below the table, and the colour controls wrap in narrow panes so the full hex value stays visible.
2026-11-21 00:25:48 +08:00
l0ng-ai 9c414cc75c fix(settings): align Editor General controls (#4827)
Settings > Editor > General: the mouse-wheel zoom scope choices sit beneath their checkbox as radio buttons, the soft-wrap file patterns field sits beside its checkbox (wrapping underneath in a narrow pane), and Scrolling follows Virtual Space with each caret behaviour on its own line.
2026-11-21 00:10:18 +08:00
Vladislav Kuzmin 3bbc90d750 test(debugger): expect watch for explicit Quick Evaluate (#4837)
Explicit Quick Evaluate sends DAP context watch since #4801 so method calls can run; the layout e2e test now expects watch for both evaluations.

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

Co-authored-by: principalwater <[email protected]>
2026-11-21 00:03:02 +08:00
ntbang0901 6d157c8b71 fix(debugger): stop at an uncaught exception from a traced stream so its records stay (#4851)
When a traced stream's terminal operation threw something the program does not catch, the trace lost its records: ide-dap reads them in the stop after its stepOut, and an uncaught exception ends the thread without one. Before parking a trace whose terminal threw, the jvm-inspect bundle now adds an uncaught-only ExceptionRequest on the traced thread (unless an enabled java-debug request already stops there), so the program stops at that throw and the trace shows the records with the exception. Bundle 1.1.1; the jar was rebuilt from source and matches byte for byte.

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

Co-authored-by: ntbang0901 <[email protected]>
2026-11-20 23:57:05 +08:00
l0ng-ai f2c0fcdc96 fix(settings): align Smart Keys backspace and paste controls (#4823)
Settings > Editor > General > Smart Keys places the Backspace and paste formatting controls directly below the Enter options; the two controls share a label column and the paste escaping option sits below the formatting control.
2026-11-20 23:54:10 +08:00
ntbang0901 a4574fdc92 fix(debugger): show toString() of Java values instead of a nameless child row (#4857)
Java values whose class overrides toString() showed without their text, and opening them showed one nameless row with the fields a level deeper. java-debug marks these values with DAP presentationHint.lazy and the IDE ignored it. Variables now carry lazy; debug_resolve_variable merges the adapter's single inner variable into the row; debugger configs can declare resolve-lazy-variables (on for java-debug) so variables/evaluate return resolved values; other adapters resolve a lazy row in place when it is opened or its (...) marker is clicked.

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

Co-authored-by: ntbang0901 <[email protected]>
2026-11-20 23:53:34 +08:00
ntbang0901 4bc87f5d84 fix(debugger): stay suspended on a thread its breakpoint still holds after another resumes (#4858)
Java debugging suspends only the thread that hits a breakpoint, but the Debug window tracked one stopped thread: after resuming it, the window showed Running with Resume and Step disabled while another thread was still stopped. The session now tracks every thread stopped alone (stopped adds, continued removes) and moves to a remaining stopped thread when the shown one continues; steps report all_threads_continued false since they run only their thread.

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

Co-authored-by: ntbang0901 <[email protected]>
2026-11-20 23:50:14 +08:00
ntbang0901 39671ff55b fix(vcs): merge and rebase branches by their short name (#4850)
Merging a branch from the Branches popup recorded "Merge branch 'refs/heads/feature'" (and the rebase reflog "checkout refs/heads/feature") because the popup passes the full ref to avoid tags of the same name. Merge and rebase now pass the short name when it resolves to that same branch, and keep the full ref when a tag shares the name.

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

Co-authored-by: ntbang0901 <[email protected]>
2026-11-20 23:47:32 +08:00
ntbang0901 881812547d fix(vcs): open the Conflicts dialog when an unstash stops on conflicts (#4849)
Applying or popping a stash that conflicts with the working tree showed an error balloon instead of the conflict resolver. unstash() was the only operation that can stop on conflicts without the conflict handler; it now uses conflictsInstead like merge, rebase and unshelve, so the Conflicts dialog opens. Other unstash failures still report the error.

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

Co-authored-by: ntbang0901 <[email protected]>
2026-11-20 23:46:47 +08:00
ntbang0901 9c145ea258 fix(run): run a Gradle subproject's tests with that subproject's test task (#4846)
In a Gradle multi-project build, gutter class/method runs, Run on a test file and JUnit configurations used the build's plain test task, so --tests filtered every subproject and the first one without a match failed the build before the subproject holding the test ran. They now share inGradleModule (the lookup directory runs already used) and run :<subproject>:test --tests ...; reruns and test-tree selections inherit that task.

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

Co-authored-by: ntbang0901 <[email protected]>
2026-11-20 23:45:45 +08:00
ntbang0901 4f192a12bc fix(run): let Maven reactor modules without the selected tests pass in every test run (#4845)
In a Maven multi-module project, Rerun Failed Tests and Run on a test file failed before the selected tests ran: -Dtest reached the first module without a matching test and Surefire stopped the build, skipping the module with the test. Those two paths built -Dtest themselves without -Dsurefire.failIfNoSpecifiedTests=false; every Maven test selection now goes through withMavenTests, which replaces an earlier -Dtest and always adds the flag.

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

Co-authored-by: ntbang0901 <[email protected]>
2026-11-20 23:44:02 +08:00
ntbang0901 1d857375dc fix(vcs): open a multi-line selection's lines on the Git remote from Open In (#4844)
Editor > Open In > GitHub / GitLab / Bitbucket opened only the caret line even with several lines selected. The editor menu passed the caret line only and vcs.openOnRemote dropped endLine; the menu now takes its lines from the helper Copy Path/Reference uses (moved to selectedLines.ts) and Open In keeps endLine.

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

Co-authored-by: ntbang0901 <[email protected]>
2026-11-20 23:43:20 +08:00
Vladislav Kuzmin 6543cdb36b test(debugger): expect unquoted strings in the value dialog (#4836)
The full-value dialog shows a string without its adapter quotes; the debugger layout e2e test now asserts the unquoted text there and keeps the quoted value in the Variables row.

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

Co-authored-by: principalwater <[email protected]>
2026-11-20 23:42:46 +08:00
Vladislav Kuzmin 684c92ce90 test(settings): target the exact font preview textbox (#4833)
The font-family e2e test matched both the editable preview and its resize handle through a substring label lookup; it now targets the textbox by its exact accessible name.

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

Co-authored-by: principalwater <[email protected]>
2026-11-20 23:42:38 +08:00
l0ng-ai 9a77a95180 feat(cucumber): behave and pytest-bdd step definitions in Python (#4859)
Python step definitions for Gherkin: behave decorators with its parse / cfparse / re matchers (use_step_matcher switches them), and pytest-bdd's exact strings and parsers.parse / cfparse / re. Covers navigation both ways, the Undefined step check and Create step definition (pending step_impl for behave, def _() for pytest-bdd, decorator added to the existing import). The backend scan reads .py files with a step decorator and skips site-packages.
2026-11-20 23:41:43 +08:00
183 changed files with 17106 additions and 756 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,
+13 -6
View File
@@ -49,6 +49,8 @@ pub struct AdapterSpec {
pub connect: Option<String>,
/// A plugin language's adapter: start exactly this approved program.
pub pinned: Option<ProgramPin>,
/// See [`DebuggerConfig::resolve_lazy_variables`].
pub resolve_lazy_variables: bool,
}
/// Built-in adapters used when no language definition names `adapter`.
@@ -60,6 +62,7 @@ fn builtin(adapter: &str) -> Option<DebuggerConfig> {
transport: transport.to_owned(),
connect: None,
install_hint: Some(hint.to_owned()),
resolve_lazy_variables: false,
pinned: None,
};
Some(match adapter {
@@ -130,12 +133,15 @@ fn builtin(adapter: &str) -> Option<DebuggerConfig> {
),
"rdbg" => cfg("rdbg", &["-O", "--port", PORT_PLACEHOLDER, "-c"], "tcp", "gem install debug"),
// A jdtls bundle: the session is started through jdtls and reached via `debugServer`.
"java-debug" => cfg(
"com.microsoft.java.debug.plugin.jar",
&[],
"tcp",
"Install Microsoft java-debug (Settings › Languages & Frameworks › Language Servers)",
),
"java-debug" => DebuggerConfig {
resolve_lazy_variables: true,
..cfg(
"com.microsoft.java.debug.plugin.jar",
&[],
"tcp",
"Install Microsoft java-debug (Settings › Languages & Frameworks › Language Servers)",
)
},
// The Java language server's own debugger, for modules jdtls doesn't serve; the host
// runs the executable of the java-analyzer serving the module.
JAVA_ANALYZER => cfg(
@@ -186,6 +192,7 @@ pub fn resolve(config: &DebuggerConfig, cwd: PathBuf) -> AdapterSpec {
server_host: None,
connect: config.connect.clone(),
pinned: config.pinned.clone(),
resolve_lazy_variables: config.resolve_lazy_variables,
}
}
@@ -102,6 +102,7 @@ pub(crate) fn bare_session_of(name: &str, request: &str) -> BareSession {
server_host: None,
connect: None,
pinned: None,
resolve_lazy_variables: false,
};
let session = Session::new(
DebugSessionId(1),
+64 -14
View File
@@ -236,6 +236,11 @@ pub struct Variable {
/// > 0 when expandable.
pub variables_reference: i64,
pub evaluate_name: Option<String>,
/// `value` is not computed yet (DAP `presentationHint.lazy`): the single variable that
/// `variables` returns for `variables_reference` holds the value and its children.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
#[specta(optional)]
pub lazy: bool,
}
/// A completion the adapter offers for an expression (DAP `completions`).
@@ -727,9 +732,46 @@ pub(crate) fn variable_from(v: &Value) -> Variable {
type_name: s("type").filter(|t| !t.is_empty()),
variables_reference: v.get("variablesReference").and_then(Value::as_i64).unwrap_or(0),
evaluate_name: s("evaluateName"),
lazy: v.pointer("/presentationHint/lazy").and_then(Value::as_bool).unwrap_or(false),
}
}
async fn session_variables(session: &Session, reference: i64) -> IdeResult<Vec<Variable>> {
let body =
session.conn.request_timeout("variables", json!({ "variablesReference": reference }), REQUEST_TIMEOUT).await?;
Ok(body
.get("variables")
.and_then(Value::as_array)
.map(|v| v.iter().map(variable_from).collect())
.unwrap_or_default())
}
async fn resolve_in(session: &Session, variable: Variable) -> IdeResult<Variable> {
if !variable.lazy || variable.variables_reference <= 0 {
return Ok(variable);
}
let mut inner = session_variables(session, variable.variables_reference).await?;
Ok(match (inner.pop(), inner.is_empty()) {
(Some(value), true) => Variable {
type_name: value.type_name.or(variable.type_name),
evaluate_name: variable.evaluate_name.or(value.evaluate_name),
name: variable.name,
value: value.value,
variables_reference: value.variables_reference,
lazy: value.lazy,
},
_ => variable,
})
}
/// A value that cannot be computed stays lazy, so the row can still be opened by hand.
async fn resolve_lazy(session: &Session, variable: Variable) -> Variable {
if !variable.lazy {
return variable;
}
resolve_in(session, variable.clone()).await.unwrap_or(variable)
}
impl DebugManager {
pub fn new(languages: Arc<LanguageRegistry>) -> Arc<Self> {
Self::with_launcher(languages, Arc::new(ProcessLauncher))
@@ -1497,6 +1539,7 @@ impl DebugManager {
type_name: body.get("type").and_then(Value::as_str).filter(|t| !t.is_empty()).map(str::to_owned),
variables_reference: body.get("variablesReference").and_then(Value::as_i64).unwrap_or(0),
evaluate_name: evaluate_name.or(Some(name)),
lazy: false,
})
}
@@ -1567,16 +1610,18 @@ impl DebugManager {
}
pub async fn variables(&self, s: DebugSessionId, reference: i64) -> IdeResult<Vec<Variable>> {
let body = self
.session(s)?
.conn
.request_timeout("variables", json!({ "variablesReference": reference }), REQUEST_TIMEOUT)
.await?;
Ok(body
.get("variables")
.and_then(Value::as_array)
.map(|v| v.iter().map(variable_from).collect())
.unwrap_or_default())
let session = self.session(s)?;
let vars = session_variables(&session, reference).await?;
if !session.spec.resolve_lazy_variables {
return Ok(vars);
}
Ok(join_all(vars.into_iter().map(|v| resolve_lazy(&session, v))).await)
}
/// Computes a lazy variable's value (DAP `presentationHint.lazy`); any other variable, or one
/// whose value the adapter does not give as a single variable, comes back unchanged.
pub async fn resolve_variable(&self, s: DebugSessionId, variable: Variable) -> IdeResult<Variable> {
resolve_in(&*self.session(s)?, variable).await
}
/// Evaluates in the `repl` context.
@@ -1602,13 +1647,18 @@ impl DebugManager {
args["frameId"] = f.into();
}
let body = session.conn.request_timeout("evaluate", args, REQUEST_TIMEOUT).await?;
Ok(Variable {
let result = Variable {
name: expression.clone(),
value: body.get("result").and_then(Value::as_str).unwrap_or_default().to_owned(),
type_name: body.get("type").and_then(Value::as_str).filter(|t| !t.is_empty()).map(str::to_owned),
variables_reference: body.get("variablesReference").and_then(Value::as_i64).unwrap_or(0),
evaluate_name: Some(expression),
})
lazy: body.pointer("/presentationHint/lazy").and_then(Value::as_bool).unwrap_or(false),
};
if !session.spec.resolve_lazy_variables {
return Ok(result);
}
Ok(resolve_lazy(&session, result).await)
}
/// Completions for `text` at `line` / `column` (0-based, UTF-16) in the frame's scope; none
@@ -1713,7 +1763,7 @@ impl DebugManager {
// A step runs its thread; other threads stopped by their own events stay stopped.
session.suspended.resumed(ticket, thread_id, false);
stream_trace::release_done(&session);
session.emit(ide_core::event::DebugEvent::Continued { thread_id, all_threads_continued: true });
session.emit(ide_core::event::DebugEvent::Continued { thread_id, all_threads_continued: false });
Ok(())
}
@@ -1825,7 +1875,7 @@ impl DebugManager {
step_settled(&session, sent)?;
session.suspended.resumed(ticket, thread_id, false);
stream_trace::release_done(&session);
session.emit(ide_core::event::DebugEvent::Continued { thread_id, all_threads_continued: true });
session.emit(ide_core::event::DebugEvent::Continued { thread_id, all_threads_continued: false });
Ok(())
}
+71 -7
View File
@@ -505,13 +505,29 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
"scopes" => {
ok!(msg, json!({"scopes": [{"name": "Locals", "variablesReference": 100, "expensive": false}]}))
}
"variables" => ok!(
msg,
json!({"variables": [
{"name": "x", "value": "1", "type": "int", "variablesReference": 0},
{"name": "req", "value": "{Req}", "type": "Req", "variablesReference": 101, "evaluateName": "req"},
]})
),
// 200 holds a lazy value (java-debug's toString(), js-debug's getters): asked for, its
// reference answers one nameless child with the value and the reference of its fields.
"variables" => match msg["arguments"]["variablesReference"].as_i64() {
Some(200) => ok!(
msg,
json!({"variables": [
{"name": "order", "value": "Order@7", "type": "Order", "variablesReference": 201,
"evaluateName": "order", "presentationHint": {"lazy": true}},
{"name": "n", "value": "2", "type": "int", "variablesReference": 0, "presentationHint": {"lazy": false}},
]})
),
Some(201) => ok!(
msg,
json!({"variables": [{"name": "", "value": "Order@7 \"Order(1)\"", "variablesReference": 202, "evaluateName": "order"}]})
),
_ => ok!(
msg,
json!({"variables": [
{"name": "x", "value": "1", "type": "int", "variablesReference": 0},
{"name": "req", "value": "{Req}", "type": "Req", "variablesReference": 101, "evaluateName": "req"},
]})
),
},
"evaluate" => ok!(msg, json!({"result": "42", "type": "int", "variablesReference": 0})),
"completions" => ok!(
msg,
@@ -2020,6 +2036,7 @@ fn godot_registry(port: u16, command: &str, args: &[&str]) -> Arc<LanguageRegist
transport: "tcp".into(),
connect: Some(format!("127.0.0.1:{port}")),
install_hint: Some("Open the project in the Godot editor".into()),
resolve_lazy_variables: false,
pinned: None,
}),
};
@@ -2763,6 +2780,53 @@ async fn step_of_one_thread_keeps_the_others_suspended() {
assert_eq!(session.suspended.ticket(), ticket + 1);
h.manager.step_in_target(id, 7, 1).await.unwrap();
assert!(!session.suspended.get());
// The UI stays on a thread that is still stopped only when told the step ran one thread.
for thread in [7, 8] {
let continued =
h.wait_event(|e| matches!(e, DebugEvent::Continued { thread_id, .. } if *thread_id == thread)).await;
assert!(matches!(continued, DebugEvent::Continued { all_threads_continued: false, .. }), "{continued:?}");
}
}
#[tokio::test]
async fn lazy_variables_are_resolved_when_the_adapter_declares_them_safe() {
let h = harness(Script::default());
let id = h.start(java_config("launch")).await.unwrap();
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
let vars = h.manager.variables(id, 200).await.unwrap();
let order = &vars[0];
assert_eq!(
(order.name.as_str(), order.value.as_str(), order.type_name.as_deref()),
("order", "Order@7 \"Order(1)\"", Some("Order"))
);
assert_eq!((order.variables_reference, order.lazy), (202, false));
assert_eq!(order.evaluate_name.as_deref(), Some("order"));
assert_eq!((vars[1].name.as_str(), vars[1].lazy), ("n", false));
}
#[tokio::test]
async fn lazy_variables_stay_lazy_for_other_adapters() {
let h = harness(Script::default());
let id = h.start(config()).await.unwrap();
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
let vars = h.manager.variables(id, 200).await.unwrap();
assert_eq!((vars[0].value.as_str(), vars[0].variables_reference, vars[0].lazy), ("Order@7", 201, true));
assert_eq!(requests(&h, "variables").len(), 1, "nothing is computed until asked for");
let order = h.manager.resolve_variable(id, vars[0].clone()).await.unwrap();
assert_eq!((order.name.as_str(), order.value.as_str()), ("order", "Order@7 \"Order(1)\""));
assert_eq!((order.variables_reference, order.lazy), (202, false));
let n = h.manager.resolve_variable(id, vars[1].clone()).await.unwrap();
assert_eq!((n.value.as_str(), requests(&h, "variables").len()), ("2", 2), "only lazy values are computed");
}
#[test]
fn java_debug_declares_its_lazy_variables_safe_to_resolve() {
let languages = LanguageRegistry::load(None).unwrap();
for registry in [&languages, &LanguageRegistry::from_configs(Vec::new())] {
assert!(adapter::find_config(registry, "java-debug").unwrap().resolve_lazy_variables);
assert!(!adapter::find_config(registry, "js-debug").unwrap().resolve_lazy_variables);
}
}
#[tokio::test]
+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,
+25 -4
View File
@@ -1,6 +1,7 @@
//! Cucumber sources: the project's `.feature` files and the JavaScript / TypeScript files
//! (`@cucumber/cucumber`, `playwright-bdd`) and Java / Kotlin files (cucumber-jvm's
//! `@Given("…")` annotations and Java 8 lambdas) that could define steps, with their text. The UI
//! `@Given("…")` annotations and Java 8 lambdas) and Python files (behave and pytest-bdd's
//! `@given('…')` decorators) that could define steps, with their text. The UI
//! owns the Gherkin and step-expression parsing and the index it feeds (as for `routes`),
//! so this side stays a cheap scan.
@@ -21,6 +22,8 @@ const MAX_FILE_BYTES: u64 = 2 << 20;
/// What a step definition call starts with (`Given('…'`, `defineStep(/…/`).
const STEP_CALLS: [&str; 5] = ["Given(", "When(", "Then(", "Step(", "defineStep("];
/** What a Python step decorator starts with (behave also takes the capitalized names). */
const PYTHON_STEP_CALLS: [&str; 8] = ["@given(", "@when(", "@then(", "@step(", "@Given(", "@When(", "@Then(", "@Step("];
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
@@ -38,10 +41,14 @@ fn is_feature(path: &Path) -> bool {
fn is_script(path: &Path) -> bool {
matches!(
path.extension().and_then(|e| e.to_str()),
Some("js" | "jsx" | "mjs" | "cjs" | "ts" | "tsx" | "mts" | "cts" | "java" | "kt")
Some("js" | "jsx" | "mjs" | "cjs" | "ts" | "tsx" | "mts" | "cts" | "java" | "kt" | "py")
)
}
fn is_python(path: &Path) -> bool {
path.extension().and_then(|e| e.to_str()) == Some("py")
}
/// The feature files and step definition files under `root`.
pub(crate) fn sources_in(root: &Path, excludes: &[String]) -> Vec<StepSource> {
let found: Mutex<Vec<StepSource>> = Mutex::new(Vec::new());
@@ -55,7 +62,8 @@ pub(crate) fn sources_in(root: &Path, excludes: &[String]) -> Vec<StepSource> {
return;
}
let Ok(text) = std::fs::read_to_string(path) else { return };
if !feature && !STEP_CALLS.iter().any(|call| text.contains(call)) {
let calls: &[&str] = if is_python(path) { &PYTHON_STEP_CALLS } else { &STEP_CALLS };
if !feature && !calls.iter().any(|call| text.contains(call)) {
return;
}
let Ok(mut found) = found.lock() else { return };
@@ -76,6 +84,7 @@ pub fn cucumber_sources(host: &Host, window: &str) -> IdeResult<Vec<StepSource>>
let mut excludes = project.search_excludes();
// Cucumber's own sources (and every other package's) are not the project's steps.
excludes.push("node_modules".to_owned());
excludes.push("site-packages".to_owned());
let mut out = Vec::new();
for root in std::iter::once(project.root.clone()).chain(project.content_roots()) {
out.extend(sources_in(&root, &excludes));
@@ -104,11 +113,23 @@ mod tests {
std::fs::write(root.join("src/CartSteps.java"), "@Given(\"an empty cart\")\npublic void empty() {}").unwrap();
std::fs::write(root.join("src/App.java"), "class App {}").unwrap();
std::fs::write(root.join("src/notes.md"), "Given('x')").unwrap();
std::fs::write(root.join("steps/cart_steps.py"), "@given('an empty cart')\ndef step_impl(context): pass")
.unwrap();
std::fs::write(root.join("src/util.py"), "def given(x): return x\nWhen = given('x')").unwrap();
std::fs::write(root.join("node_modules/@cucumber/cucumber/lib/index.js"), "Given('x')").unwrap();
let files = sources_in(root, &["node_modules".to_owned()]);
let names: Vec<String> =
files.iter().map(|f| f.path.0.strip_prefix(root).unwrap().to_string_lossy().replace('\\', "/")).collect();
assert_eq!(names, ["features/cart.feature", "src/CartSteps.java", "steps/bdd.mjs", "steps/cart.steps.ts"]);
assert_eq!(
names,
[
"features/cart.feature",
"src/CartSteps.java",
"steps/bdd.mjs",
"steps/cart.steps.ts",
"steps/cart_steps.py"
]
);
assert!(files[0].feature && !files[1].feature);
assert!(files[3].text.contains("an empty cart"));
}
+6
View File
@@ -342,6 +342,11 @@ pub async fn debug_variables(host: &Host, session: DebugSessionId, reference: i6
host.debugger.variables(session, reference).await
}
#[command(trust = trusted)]
pub async fn debug_resolve_variable(host: &Host, session: DebugSessionId, variable: Variable) -> IdeResult<Variable> {
host.debugger.resolve_variable(session, variable).await
}
#[command(trust = trusted)]
pub async fn debug_evaluate(
host: &Host,
@@ -834,6 +839,7 @@ ide_command::domain!(
debug_listen_for_jvm,
debug_pause,
debug_redefine_classes,
debug_resolve_variable,
debug_restart_frame,
debug_resume,
debug_run_to,
+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");
}
}
+6 -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};
@@ -245,6 +245,11 @@ pub struct DebuggerConfig {
pub connect: Option<String>,
#[serde(default)]
pub install_hint: Option<String>,
/// The adapter's lazy values (DAP `presentationHint.lazy`) are renderings such as `toString()`,
/// safe to compute for every value shown: they are resolved before the UI sees them, as IDEA
/// shows `toString()` at once. Off (getters with side effects), a value resolves when opened.
#[serde(default)]
pub resolve_lazy_variables: bool,
/// Set on plugin languages: start exactly this approved program.
#[serde(skip)]
pub pinned: Option<ProgramPin>,
+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";
+44 -5
View File
@@ -25,6 +25,17 @@ const PROGRESS_SWEEP: Duration = Duration::from_secs(15);
/// visible, but stops holding the server busy while the work behind it keeps running.
const PROGRESS_STALE: Duration = Duration::from_secs(180);
/// How long a cancelled progress task waits for its server to end it.
const CANCEL_GRACE: Duration = Duration::from_secs(5);
/// The key of progress token `token` in [`Server::progress`].
fn progress_key(token: &Value) -> String {
match token {
Value::String(s) => s.clone(),
other => other.to_string(),
}
}
/// Task message after [`PROGRESS_STALE`] of silence: keep the server's last message and
/// say how long nothing happened.
fn stalled_message(message: Option<&str>) -> String {
@@ -97,22 +108,50 @@ impl ClientHandler {
}
/// Cancelling task `task` asks this server instance to stop the work of progress `token`.
/// A server that never ends it (Pyright waiting on a workspace that never loads) would
/// leave the task "Cancelling…" for good: after [`CANCEL_GRACE`] the task ends here.
fn cancel_handle(&self, task: TaskId, token: &Value) -> ide_core::task::CancelHandle {
let (server, generation, token) = (self.server.clone(), self.generation, token.clone());
let (mgr, server, generation, token) = (self.mgr.clone(), self.server.clone(), self.generation, token.clone());
ide_core::task::on_cancel(task, move || {
if let Some(run) = server.initialized_gen(generation)
&& let Err(e) = run.peer.notify("window/workDoneProgress/cancel", json!({ "token": token }))
{
tracing::debug!("{}: cannot cancel progress: {e}", server.name);
}
let Some(runtime) = mgr.upgrade().map(|m| m.runtime.clone()) else { return };
runtime.spawn(async move {
tokio::time::sleep(CANCEL_GRACE).await;
let Some(mgr) = mgr.upgrade() else { return };
let key = progress_key(&token);
let ended = {
let mut progress = server.progress.lock();
if progress.get(&key).is_none_or(|p| p.task != task) {
return; // the server ended it, or the token began new work
}
progress.remove(&key)
};
if let Some(p) = ended {
tracing::info!("{}: progress '{key}' did not end after cancel; ending its task", server.name);
server.emit(
mgr.sink(),
IdeEvent::Task {
id: p.task,
title: p.title,
message: p.message,
fraction: None,
done: true,
cancellable: false,
},
);
server.refresh_busy_status(mgr.sink());
server.progress_ended();
}
});
})
}
fn progress(&self, mgr: &LspManager, params: Value) {
let token = match &params["token"] {
Value::String(s) => s.clone(),
other => other.to_string(),
};
let token = progress_key(&params["token"]);
let value = &params["value"];
let kind = value.get("kind").and_then(Value::as_str);
let message = value.get("message").and_then(Value::as_str).map(str::to_owned);
+46 -1
View File
@@ -2,7 +2,7 @@
use ide_core::event::{LspRefreshKind, ServerStatus};
use ide_core::{
CancellationToken, DocId, FileEdit, IdeEvent, LanguageId, Pos, Range, ServerId, Severity, WorkspaceEdit,
CancellationToken, DocId, FileEdit, IdeEvent, LanguageId, Pos, Range, ServerId, Severity, TaskId, WorkspaceEdit,
};
use ide_jsonrpc::{Handler, NoopHandler, Peer};
use ide_language::{LanguageConfig, LanguageRegistry, LanguageServerConfig};
@@ -2182,6 +2182,51 @@ async fn replacing_progress_keeps_cancellation_reports_and_indexing_on_the_new_t
);
}
/// A server that ignores `window/workDoneProgress/cancel` (Pyright waiting on a workspace
/// that never loads) does not keep the task "Cancelling…": it ends after a grace period,
/// once, and later reports on the token change nothing. A server that ends it in time ends it.
#[tokio::test(flavor = "multi_thread")]
async fn a_cancelled_progress_the_server_never_ends_ends_on_its_own() {
let h = harness(&[("mock", incremental_caps())]);
h.open("a.mk", "x");
h.wait_status("mock", ServerStatus::Ready).await;
let s = h.launcher.state("mock");
let peer = s.peer();
let begin = |token: &str, title: &str| json!({ "token": token, "value": { "kind": "begin", "title": title, "cancellable": true } });
let task_of = |title: &str| {
h.events.lock().iter().find_map(|e| match e {
IdeEvent::Task { id, title: t, done: false, .. } if t == title => Some(*id),
_ => None,
})
};
let ends = |task: TaskId| {
h.events.lock().iter().filter(|e| matches!(e, IdeEvent::Task { id, done: true, .. } if *id == task)).count()
};
peer.notify("$/progress", begin("ignored", "Finding references")).unwrap();
peer.notify("$/progress", begin("honoured", "Indexing")).unwrap();
eventually(|| task_of("Finding references").is_some() && task_of("Indexing").is_some()).await;
h.wait_status("mock", ServerStatus::Busy).await;
let (ignored, honoured) = (task_of("Finding references").unwrap(), task_of("Indexing").unwrap());
assert!(ide_core::task::cancel(ignored));
assert!(ide_core::task::cancel(honoured));
eventually(|| s.notified("window/workDoneProgress/cancel").len() == 2).await;
peer.notify("$/progress", json!({ "token": "honoured", "value": { "kind": "end" } })).unwrap();
eventually(|| ends(honoured) == 1).await;
assert_eq!(ends(ignored), 0, "the server still has its grace period");
eventually(|| ends(ignored) == 1).await;
h.wait_status("mock", ServerStatus::Ready).await;
// Late reports on the token reach no task.
peer.notify("$/progress", json!({ "token": "ignored", "value": { "kind": "report", "message": "late" } })).unwrap();
peer.notify("$/progress", json!({ "token": "ignored", "value": { "kind": "end" } })).unwrap();
peer.notify("$/progress", begin("after", "After")).unwrap();
eventually(|| task_of("After").is_some()).await;
assert_eq!(ends(ignored), 1);
assert_eq!(ends(honoured), 1);
assert!(!h.events.lock().iter().any(|e| matches!(e, IdeEvent::Task { message: Some(m), .. } if m == "late")));
}
#[tokio::test(flavor = "multi_thread")]
async fn cancelling_a_cancellable_progress_task_asks_the_server_to_stop() {
let h = harness(&[("mock", incremental_caps())]);
+2 -2
View File
@@ -1649,7 +1649,7 @@ pub fn jvm_inspect_bundle(data_dir: &Path) -> Option<PathBuf> {
install_bundle(
data_dir,
"jvm-inspect",
"1.1.0",
"1.1.1",
include_bytes!("../../../java/jvm-inspect/openidea-jvm-inspect.jar"),
)
}
@@ -1745,7 +1745,7 @@ mod usages_bundle_tests {
std::fs::write(dir.path().join(name), b"old").unwrap();
}
let jar = super::jvm_inspect_bundle(dir.path()).unwrap();
assert_eq!(jar, dir.path().join("jvm-inspect-1.1.0.jar"));
assert_eq!(jar, dir.path().join("jvm-inspect-1.1.1.jar"));
assert_eq!(std::fs::read(&jar).unwrap(), include_bytes!("../../../java/jvm-inspect/openidea-jvm-inspect.jar"));
assert!(!dir.path().join("jvm-inspect-0.9.0.jar").exists());
assert_eq!(std::fs::read(dir.path().join("java-usages-1.7.0.jar")).unwrap(), b"old");
+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() {
+17 -2
View File
@@ -1155,16 +1155,31 @@ fn check_rev(rev: &str) -> IdeResult<&str> {
Ok(rev)
}
/// The short name of a full branch ref (`refs/heads/x`, `refs/remotes/origin/x`) when it
/// names that same branch: git writes the name it is given into the merge message and the
/// reflog. A name a tag shares stays a full ref, the case IDEA also passes in full.
fn unambiguous_branch_name<'a>(r: &Repo, rev: &'a str) -> &'a str {
let Some(short) = rev.strip_prefix("refs/heads/").or_else(|| rev.strip_prefix("refs/remotes/")) else {
return rev;
};
// An ambiguous name prints nothing (git reports it on stderr).
let full = cli::run_raw(r.root(), &["rev-parse", "--verify", "-q", "--symbolic-full-name", short], None);
match full {
Ok(out) if out.code == Some(0) && out.stdout_str().trim() == rev => short,
_ => rev,
}
}
/// Local changes are stashed and restored around the merge (IDEA's "save local changes").
pub(crate) fn merge(r: &Repo, branch: &str) -> IdeResult<()> {
let branch = check_rev(branch)?;
let branch = unambiguous_branch_name(r, check_rev(branch)?);
crate::preserve::around(r, "Local changes saved before merge", || {
run(r.root(), &["merge", "--no-edit", branch], None).map(|_| ())
})
}
pub(crate) fn rebase(r: &Repo, onto: &str) -> IdeResult<()> {
let onto = check_rev(onto)?;
let onto = unambiguous_branch_name(r, check_rev(onto)?);
crate::preserve::around(r, "Local changes saved before rebase", || {
run(r.root(), &["rebase", onto], None).map(|_| ())
})
+31
View File
@@ -505,6 +505,37 @@ fn rebase_and_merge_onto_a_branch_named_like_a_tag_use_the_branch() {
assert_eq!(fx.head(), tip, "fast-forwarded to the branch, not the tag");
}
#[test]
fn merge_and_rebase_record_the_branch_name_git_would_show() {
let (fx, _bare) = Fixture::with_origin();
fx.git(&["switch", "-q", "-c", "topic"]);
fx.write("t.txt", "t\n");
fx.commit_all("topic");
fx.git(&["push", "-q", "origin", "topic"]);
fx.git(&["switch", "-q", "main"]);
fx.write("m.txt", "m\n");
fx.commit_all("main");
let repo = fx.repo();
let subject = || fx.git(&["log", "-1", "--format=%s"]);
repo.merge("refs/heads/topic").unwrap();
assert_eq!(subject(), "Merge branch 'topic'");
fx.git(&["reset", "-q", "--hard", "HEAD~1"]);
repo.merge("refs/remotes/origin/topic").unwrap();
assert_eq!(subject(), "Merge remote-tracking branch 'origin/topic'");
fx.git(&["reset", "-q", "--hard", "HEAD~1"]);
repo.rebase("refs/heads/topic").unwrap();
let reflog = fx.git(&["reflog", "--format=%gs"]);
assert!(reflog.contains("rebase (start): checkout topic"), "{reflog}");
fx.git(&["reset", "-q", "--hard", "ORIG_HEAD"]);
// A tag of the same name makes the short name ambiguous: the full ref stays.
fx.git(&["tag", "topic", "main~1"]);
repo.merge("refs/heads/topic").unwrap();
assert_eq!(subject(), "Merge branch 'refs/heads/topic'");
}
#[test]
fn interactive_rebase_edit_stops_for_amend() {
let (fx, ids) = linear();
@@ -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
+88
View File
@@ -0,0 +1,88 @@
import type { Page } from "@playwright/test";
import { expect, test } from "./fixtures";
async function openSaveActions(page: Page) {
await page.keyboard.press("Meta+,");
const settings = page.getByRole("dialog", { name: "Settings", exact: true });
const search = settings.getByRole("textbox", { name: "Search settings" });
await search.fill("Optimize imports");
await settings.getByRole("treeitem", { name: "Actions on Save", exact: true }).click();
await search.clear();
return settings;
}
test("Actions on Save aligns each enabled action with its trigger in wide and narrow panes", async ({
workbench: page,
}) => {
const settings = await openSaveActions(page);
const table = settings.getByRole("table", { name: "Actions on Save", exact: true });
const action = table.getByRole("columnheader", { name: "Action", exact: true });
const heading = table.getByRole("columnheader", { name: "Activated on", exact: true });
const format = table.getByRole("row", { name: /Reformat code/ });
const imports = table.getByRole("row", { name: /Optimize imports/ });
const cleanup = table.getByRole("row", { name: /Run code cleanup/ });
const trigger = (action: typeof format) => action.getByRole("cell").nth(1);
await expect(table.getByRole("row")).toHaveCount(4);
await format.getByRole("checkbox").check();
await imports.getByRole("checkbox").press("Space");
await expect(trigger(format)).toHaveText("Save or Save All");
await expect(trigger(imports)).toHaveText("Save or Save All");
await expect(trigger(cleanup)).toBeEmpty();
for (const width of [1120, 520]) {
await page.setViewportSize({ width, height: 740 });
await expect(heading).toBeInViewport({ ratio: 1 });
await expect(trigger(imports)).toBeInViewport({ ratio: 1 });
const column = (await heading.boundingBox())!;
expect((await action.boundingBox())!.width).toBeGreaterThan(column.width);
expect(
await trigger(imports).evaluate((cell) => {
const range = document.createRange();
range.selectNodeContents(cell.firstElementChild!);
return range.getClientRects().length;
}),
).toBe(1);
for (const row of [format, imports, cleanup]) {
const cell = (await trigger(row).boundingBox())!;
expect(Math.abs(column.x - cell.x)).toBeLessThan(1);
expect(Math.abs(column.width - cell.width)).toBeLessThan(1);
}
expect(await table.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await expect(settings.getByRole("button", { name: "Editor › General", exact: true })).toBeInViewport();
}
await format.getByRole("checkbox").uncheck();
await expect(trigger(format)).toBeEmpty();
await expect(trigger(imports)).toHaveText("Save or Save All");
});
test("Actions on Save stages the same preferences as Editor General and honors Apply and Cancel", async ({
workbench: page,
}) => {
const settings = await openSaveActions(page);
const format = settings.getByRole("checkbox", { name: "Reformat code", exact: true });
const imports = settings.getByRole("checkbox", { name: "Optimize imports", exact: true });
const cleanup = settings.getByRole("checkbox", { name: "Run code cleanup", exact: true });
const apply = settings.getByRole("button", { name: "Apply", exact: true });
const cancel = settings.getByRole("button", { name: "Cancel", exact: true });
await format.check();
await imports.check();
await settings.getByRole("button", { name: "Editor › General", exact: true }).click();
await expect(settings.getByRole("checkbox", { name: "Reformat code on save", exact: true })).toBeChecked();
await settings.getByRole("button", { name: "Back", exact: true }).click();
await expect(format).toBeChecked();
await expect(imports).toBeChecked();
await apply.click();
await expect(apply).toBeDisabled();
await cancel.click();
await openSaveActions(page);
await expect(format).toBeChecked();
await expect(imports).toBeChecked();
await cleanup.check();
await cancel.click();
await openSaveActions(page);
await expect(cleanup).not.toBeChecked();
await expect(format).toBeChecked();
await expect(imports).toBeChecked();
});
+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 });
});
+80
View File
@@ -0,0 +1,80 @@
import type { Page } from "@playwright/test";
import { expect, test } from "./fixtures";
async function openCompletionSettings(page: Page) {
await page.keyboard.press("Meta+,");
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
const search = dialog.getByRole("textbox", { name: "Search settings" });
await search.fill("First letter only");
await dialog.getByRole("treeitem", { name: "Code Completion", exact: true }).click();
await search.clear();
return dialog;
}
test("Code Completion puts both case-matching choices beside the checkbox and keeps them in view", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 1120, height: 740 });
const dialog = await openCompletionSettings(page);
const matchCase = dialog.getByRole("checkbox", { name: "Match case:", exact: true });
const choices = dialog.getByRole("radiogroup", { name: "Match case:", exact: true });
const first = choices.getByRole("radio", { name: "First letter only", exact: true });
const all = choices.getByRole("radio", { name: "All letters", exact: true });
await expect(first).toBeChecked();
await expect(all).not.toBeChecked();
const matchBox = (await matchCase.boundingBox())!;
const firstBox = (await first.boundingBox())!;
const allBox = (await all.boundingBox())!;
expect(Math.abs(matchBox.y - firstBox.y)).toBeLessThan(1);
expect(Math.abs(firstBox.y - allBox.y)).toBeLessThan(1);
expect(firstBox.x).toBeGreaterThan(matchBox.x + matchBox.width);
expect(allBox.x).toBeGreaterThan(firstBox.x + firstBox.width);
for (const width of [580, 520]) {
await page.setViewportSize({ width, height: 740 });
await expect(matchCase).toBeInViewport({ ratio: 1 });
await expect(first).toBeInViewport({ ratio: 1 });
await expect(all).toBeInViewport({ ratio: 1 });
await expect(dialog.getByText("All letters", { exact: true })).toBeInViewport({ ratio: 1 });
}
});
test("Code Completion preserves case and popup delay preferences across Apply and Cancel", async ({
workbench: page,
}) => {
const dialog = await openCompletionSettings(page);
const matchCase = dialog.getByRole("checkbox", { name: "Match case:", exact: true });
const first = dialog.getByRole("radio", { name: "First letter only", exact: true });
const all = dialog.getByRole("radio", { name: "All letters", exact: true });
await matchCase.uncheck();
await expect(first).toBeDisabled();
await expect(all).toBeDisabled();
await expect(first).toBeChecked();
await matchCase.check();
await first.press("ArrowRight");
await expect(all).toBeChecked();
const docs = dialog.getByRole("textbox", { name: "Show the documentation popup in", exact: true });
const params = dialog.getByRole("textbox", { name: "Show the parameter info popup in", exact: true });
await dialog.getByRole("checkbox", { name: "Show the documentation popup in", exact: true }).check();
await dialog.getByRole("checkbox", { name: "Show the parameter info popup in", exact: true }).check();
await docs.fill("750");
await params.fill("1250");
const apply = dialog.getByRole("button", { name: "Apply", exact: true });
const cancel = dialog.getByRole("button", { name: "Cancel", exact: true });
await apply.click();
await expect(apply).toBeDisabled();
await cancel.click();
await openCompletionSettings(page);
await expect(all).toBeChecked();
await expect(docs).toHaveValue("750");
await expect(params).toHaveValue("1250");
await matchCase.uncheck();
await expect(all).toBeDisabled();
await expect(all).toBeChecked();
await cancel.click();
await openCompletionSettings(page);
await expect(matchCase).toBeChecked();
await expect(all).toBeChecked();
});
+28
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");
+3 -2
View File
@@ -2,7 +2,8 @@ import { expect, stubDesktop, test } from "./fixtures";
const amountName = "regionalSettlementAmountFromExternalProcessorBeforeRounding";
const routingName = "settlementRoutingReferenceForCrossBorderReconciliation";
const routingValue = "'APR-2026 / eu-west / batch-701 / settlement complete'";
const routingText = "APR-2026 / eu-west / batch-701 / settlement complete";
const routingValue = "'" + routingText + "'";
test("keeps values and their full-value action readable in a narrow debugger", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1220, height: 760 });
@@ -46,7 +47,7 @@ test("keeps values and their full-value action readable in a narrow debugger", a
await expect(show).toBeInViewport({ ratio: 1 });
await show.click();
const dialog = page.getByRole("dialog", { name: `Value of ${routingName}` });
await expect(dialog.getByText(routingValue, { exact: true })).toBeVisible();
await expect(dialog.getByText(routingText, { exact: true })).toBeVisible();
await page.keyboard.press("Escape");
await expect(dialog).toBeHidden();
+87
View File
@@ -0,0 +1,87 @@
import type { Page } from "@playwright/test";
import { expect, test } from "./fixtures";
async function openGeneral(page: Page) {
await page.keyboard.press("Meta+,");
const settings = page.getByRole("dialog", { name: "Settings", exact: true });
const search = settings.getByRole("textbox", { name: "Search settings" });
await search.fill("File patterns");
await settings.getByRole("treeitem", { name: "General", exact: true }).click();
await search.clear();
return settings;
}
test("Editor General fits the soft-wrap pattern field and stacks the scrolling choices", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 1120, height: 850 });
const settings = await openGeneral(page);
const softWraps = settings.getByRole("region", { name: "Soft Wraps", exact: true });
const wrap = softWraps.getByRole("checkbox", { name: "Soft-wrap files", exact: true });
const patterns = softWraps.getByRole("textbox", { name: "File patterns" });
const scrolling = settings.getByRole("region", { name: "Scrolling", exact: true });
const virtualSpace = settings.getByRole("region", { name: "Virtual Space", exact: true });
const caretPrompt = scrolling.getByText("When caret is moved", { exact: true });
const center = scrolling.getByRole("radio", { name: /keep caret line centered/ });
const minimize = scrolling.getByRole("radio", { name: /minimize editor scrolling/ });
await expect(patterns).toBeVisible();
const toggle = (await wrap.boundingBox())!;
const field = (await patterns.boundingBox())!;
expect(toggle.y).toBeGreaterThan(field.y);
expect(toggle.y + toggle.height).toBeLessThan(field.y + field.height);
expect(field.x).toBeGreaterThan(toggle.x + toggle.width);
expect(await patterns.getAttribute("aria-describedby")).toBeTruthy();
for (const width of [1120, 520]) {
await page.setViewportSize({ width, height: 850 });
await patterns.scrollIntoViewIfNeeded();
await expect(patterns).toBeInViewport({ ratio: 0.99 });
const fieldBox = (await patterns.boundingBox())!;
const indent = softWraps.getByRole("checkbox", { name: "Use original line's indent for wrapped parts" });
expect((await indent.boundingBox())!.y).toBeGreaterThan(fieldBox.y + fieldBox.height);
expect(await scrolling.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
expect((await scrolling.boundingBox())!.y).toBeGreaterThan((await virtualSpace.boundingBox())!.y);
const first = (await center.boundingBox())!;
const second = (await minimize.boundingBox())!;
expect(first.x).toBeGreaterThan((await caretPrompt.boundingBox())!.x);
expect(second.y).toBeGreaterThan(first.y + first.height);
expect(Math.abs(first.x - second.x)).toBeLessThan(1);
}
});
test("Editor General keeps wheel and wrap dependencies and saves the selected values", async ({ workbench: page }) => {
const settings = await openGeneral(page);
const zoom = settings.getByRole("checkbox", { name: "Change font size with Ctrl/Command+Mouse Wheel" });
const active = settings.getByRole("radio", { name: "Active editor", exact: true });
const all = settings.getByRole("radio", { name: "All editors", exact: true });
const wrap = settings.getByRole("checkbox", { name: "Soft-wrap files", exact: true });
const patterns = settings.getByRole("textbox", { name: "File patterns", exact: true });
const indent = settings.getByRole("checkbox", { name: "Use original line's indent for wrapped parts" });
const apply = settings.getByRole("button", { name: "Apply", exact: true });
const cancel = settings.getByRole("button", { name: "Cancel", exact: true });
await zoom.uncheck();
await expect(active).toBeDisabled();
await expect(all).toBeDisabled();
await zoom.check();
await expect(active).toBeChecked();
await active.focus();
await page.keyboard.press("ArrowDown");
await expect(all).toBeChecked();
await wrap.uncheck();
await expect(patterns).toBeDisabled();
await expect(indent).toBeDisabled();
await wrap.check();
await expect(indent).toBeEnabled();
await patterns.fill("*.md; *.notes");
await apply.click();
await expect(apply).toBeDisabled();
await cancel.click();
await openGeneral(page);
await expect(zoom).toBeChecked();
await expect(all).toBeChecked();
await expect(wrap).toBeChecked();
await expect(patterns).toHaveValue("*.md; *.notes");
});
+88
View File
@@ -0,0 +1,88 @@
import type { Page } from "@playwright/test";
import { expect, test } from "./fixtures";
async function openFileColors(page: Page) {
await page.keyboard.press("Meta+,");
const settings = page.getByRole("dialog", { name: "Settings", exact: true });
const search = settings.getByRole("textbox", { name: "Search settings" });
await search.fill("Use in project view");
await settings.getByRole("treeitem", { name: "File Colors", exact: true }).click();
await search.clear();
return settings;
}
test("File Colors fits its switches and keeps the toolbar and table headings in view", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1120, height: 760 });
const settings = await openFileColors(page);
const table = settings.getByRole("table", { name: "File colors", exact: true });
const scope = table.getByRole("columnheader", { name: "Scope", exact: true });
const color = table.getByRole("columnheader", { name: "Color", exact: true });
const toolbar = settings.getByRole("toolbar", { name: "File colors actions", exact: true });
const master = settings.getByRole("checkbox", { name: "Enable file colors", exact: true });
const project = settings.getByRole("checkbox", { name: "Use in project view", exact: true });
const hex = settings.getByRole("textbox", { name: "Custom colour hex", exact: true });
await expect(scope).toBeVisible();
expect(Math.abs((await master.boundingBox())!.y - (await project.boundingBox())!.y)).toBeLessThan(1);
for (const width of [1120, 520]) {
await page.setViewportSize({ width, height: 760 });
await expect(project).toBeInViewport({ ratio: 1 });
await expect(color).toBeInViewport({ ratio: 1 });
await expect(hex).toBeInViewport({ ratio: 1 });
expect((await hex.boundingBox())!.width).toBeGreaterThan(70);
expect((await color.boundingBox())!.width).toBeGreaterThan(80);
const cell = table.getByRole("cell", { name: "Green", exact: true });
expect(Math.abs((await color.boundingBox())!.x - (await cell.boundingBox())!.x)).toBeLessThan(1);
}
const add = toolbar.getByRole("button", { name: "Add", exact: true });
for (let i = 0; i < 10; i++) await add.click();
const last = table.getByRole("row").last();
await expect(last.getByRole("button")).toHaveAttribute("aria-pressed", "true");
await expect(last).toBeInViewport({ ratio: 1 });
await expect(scope).toBeInViewport({ ratio: 1 });
await expect(toolbar).toBeInViewport({ ratio: 1 });
});
test("File Colors preserves ordered rules and placement settings across Apply and Cancel", async ({
workbench: page,
}) => {
const settings = await openFileColors(page);
const table = settings.getByRole("table", { name: "File colors", exact: true });
const tests = table.getByRole("button", { name: "Tests", exact: true });
const firstRule = table.getByRole("row").nth(1);
const toolbar = settings.getByRole("toolbar", { name: "File colors actions", exact: true });
const tabs = settings.getByRole("checkbox", { name: "Use in editor tabs", exact: true });
const master = settings.getByRole("checkbox", { name: "Enable file colors", exact: true });
const apply = settings.getByRole("button", { name: "Apply", exact: true });
const cancel = settings.getByRole("button", { name: "Cancel", exact: true });
await tabs.uncheck();
await master.uncheck();
await expect(tabs).toBeDisabled();
await master.check();
await expect(tabs).not.toBeChecked();
await expect(tabs).toBeEnabled();
await tests.press("Enter");
await expect(tests).toHaveAttribute("aria-pressed", "true");
await settings.getByRole("textbox", { name: "Custom colour hex", exact: true }).fill("#1258a5");
await toolbar.getByRole("button", { name: "Move Up", exact: true }).click();
await expect(firstRule.getByRole("button", { name: "Tests", exact: true })).toBeVisible();
await expect(firstRule.getByRole("cell", { name: "#1258a5", exact: true })).toBeVisible();
await apply.click();
await expect(apply).toBeDisabled();
await cancel.click();
await openFileColors(page);
await expect(tabs).not.toBeChecked();
await expect(firstRule.getByRole("cell", { name: "#1258a5", exact: true })).toBeVisible();
const remove = toolbar.getByRole("button", { name: "Remove", exact: true });
await remove.click();
await remove.click();
await expect(table.getByText("No file colors. Click + to add one.", { exact: true })).toBeVisible();
await expect(remove).toBeDisabled();
await cancel.click();
await openFileColors(page);
await expect(firstRule.getByRole("cell", { name: "#1258a5", exact: true })).toBeVisible();
});
+80
View File
@@ -0,0 +1,80 @@
import type { Page } from "@playwright/test";
import { expect, test } from "./fixtures";
async function openPostfixSettings(page: Page) {
await page.keyboard.press("Meta+,");
const settings = page.getByRole("dialog", { name: "Settings", exact: true });
const search = settings.getByRole("textbox", { name: "Search settings" });
await search.fill("Postfix Completion");
await settings.getByRole("treeitem", { name: "Postfix Completion", exact: true }).click();
await search.clear();
return settings;
}
test("Postfix Completion pairs the template list with a responsive code preview", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1120, height: 760 });
const settings = await openPostfixSettings(page);
const list = settings.getByRole("list", { name: "Postfix templates", exact: true });
const preview = settings.getByRole("region", { name: "Template preview", exact: true });
const before = preview.locator("pre").first();
const after = preview.locator("pre").last();
await expect(before).toHaveText("expr.if");
await expect(after).toContainText("if (expr)");
const listBounds = (await list.boundingBox())!;
const widePreview = (await preview.boundingBox())!;
expect(widePreview.x).toBeGreaterThanOrEqual(listBounds.x + listBounds.width);
expect(widePreview.y).toBeLessThan(listBounds.y);
await list.getByRole("button", { name: ".if", exact: true }).press("ArrowDown");
const elseTemplate = list.getByRole("button", { name: ".else", exact: true });
await expect(elseTemplate).toBeFocused();
await expect(elseTemplate).toHaveAttribute("aria-pressed", "true");
await expect(before).toHaveText("expr.else");
await expect(after).toContainText("if (!expr)");
await page.setViewportSize({ width: 520, height: 760 });
await settings.getByRole("tab", { name: "Python", exact: true }).click();
await expect(before).toHaveText("expr.if");
await expect(after).toContainText("if expr:");
await after.scrollIntoViewIfNeeded();
await expect(after).toBeInViewport({ ratio: 0.99 });
const narrowList = (await list.boundingBox())!;
const narrowPreview = (await preview.boundingBox())!;
expect(narrowPreview.y).toBeGreaterThanOrEqual(narrowList.y + narrowList.height);
expect(Math.abs(narrowList.x - narrowPreview.x)).toBeLessThan(2);
expect(await preview.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await settings.getByRole("tab", { name: "JavaScript / TypeScript", exact: true }).click();
await expect(elseTemplate).toHaveAttribute("aria-pressed", "true");
await expect(before).toHaveText("expr.else");
await settings.getByRole("tab", { name: "Java", exact: true }).click();
await list.getByRole("button", { name: ".var", exact: true }).click();
await expect(preview.getByText("Fallback expansion", { exact: true })).toBeVisible();
await expect(after).toContainText("var value = expr;");
});
test("Postfix Completion keeps template selection separate from enabled preferences", async ({ workbench: page }) => {
const settings = await openPostfixSettings(page);
const master = settings.getByRole("checkbox", { name: "Enable postfix completion", exact: true });
const expand = settings.getByRole("checkbox", { name: "Expand templates with Tab", exact: true });
const ifEnabled = settings.getByRole("checkbox", { name: "Enable .if", exact: true });
const preview = settings.getByRole("region", { name: "Template preview", exact: true });
const before = preview.locator("pre").first();
await settings.getByRole("button", { name: ".else", exact: true }).click();
await expect(ifEnabled).toBeChecked();
await ifEnabled.uncheck();
await expect(before).toHaveText("expr.if");
await master.uncheck();
await expect(expand).toBeDisabled();
await expect(ifEnabled).toBeDisabled();
await settings.getByRole("button", { name: ".else", exact: true }).click();
await expect(before).toHaveText("expr.else");
await master.check();
await expect(ifEnabled).not.toBeChecked();
await settings.getByRole("button", { name: "OK", exact: true }).click();
await openPostfixSettings(page);
await expect(ifEnabled).not.toBeChecked();
await expect(master).toBeChecked();
});
+2 -2
View File
@@ -82,7 +82,7 @@ test("Quick Evaluate opens an object tree that fits the editor and returns focus
await expect(hint.getByRole("tree")).toHaveCount(0);
await expect(hint).toHaveText(/subtotal\s*=\s*42/);
expect(await ipcCalls(page, "debug_evaluate_in")).toEqual([
{ session: 91, frameId: 11, expression: "summary", context: "hover" },
{ session: 91, frameId: 11, expression: "subtotal", context: "hover" },
{ session: 91, frameId: 11, expression: "summary", context: "watch" },
{ session: 91, frameId: 11, expression: "subtotal", context: "watch" },
]);
});
+4 -3
View File
@@ -184,6 +184,7 @@ test("Language Servers page installs a tool with progress (in-memory installer)"
test("font picker supports manual families and CJK fallback in browser development", async ({ workbench: page }) => {
await page.keyboard.press("Meta+,");
const dialog = page.getByRole("dialog", { name: "Settings" });
const preview = dialog.getByRole("textbox", { name: "Font preview", exact: true });
await dialog.getByRole("textbox", { name: "Search settings" }).fill("Typography Settings");
await dialog.getByRole("treeitem", { name: "Font", exact: true }).click();
const family = dialog.getByRole("combobox", { name: "Font", exact: true });
@@ -201,16 +202,16 @@ test("font picker supports manual families and CJK fallback in browser developme
await family.fill("Inter");
await family.press("Enter");
// Computed styles drop redundant quotes around single-token families ("Inter" -> Inter).
await expect(dialog.getByLabel("Font preview")).toHaveCSS("font-family", /^Inter, "Inter Variable",/);
await expect(preview).toHaveCSS("font-family", /^Inter, "Inter Variable",/);
const fallback = dialog.getByRole("combobox", { name: "Fallback font", exact: true });
await family.fill("Maple Mono NF");
await family.press("Enter");
await fallback.fill("Inter");
await fallback.press("Enter");
await expect(dialog.getByLabel("Font preview")).toHaveCSS("font-family", /Maple Mono NF.*Inter Variable/);
await expect(preview).toHaveCSS("font-family", /Maple Mono NF.*Inter Variable/);
await fallback.fill("思源宋体");
await fallback.press("Enter");
await expect(dialog.getByLabel("Font preview")).toHaveCSS("font-family", /思源宋体/);
await expect(preview).toHaveCSS("font-family", /思源宋体/);
await dialog.getByRole("button", { name: "Cancel", exact: true }).click();
await expect(dialog).toBeHidden();
});
+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 });
+67
View File
@@ -0,0 +1,67 @@
import type { Page } from "@playwright/test";
import { expect, test } from "./fixtures";
async function openSmartKeys(page: Page) {
await page.keyboard.press("Meta+,");
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
await dialog.getByRole("textbox", { name: "Search settings" }).fill("Smart Keys");
await dialog.getByRole("treeitem", { name: "Smart Keys", exact: true }).click();
return dialog;
}
test("backspace and paste controls align below Enter options in Smart Keys", async ({ workbench: page }) => {
const dialog = await openSmartKeys(page);
const enter = dialog.getByRole("region", { name: "Enter", exact: true });
const unindent = dialog.getByRole("button", { name: /^Unindent(?: on Backspace)?$/ });
const paste = dialog.getByRole("button", { name: "Reformat on paste", exact: true });
const escape = dialog.getByRole("checkbox", { name: "Escape text on paste in string literals", exact: true });
for (const width of [1120, 520]) {
await page.setViewportSize({ width, height: 760 });
await expect(unindent).toBeInViewport({ ratio: 0.98 });
await expect(paste).toBeInViewport({ ratio: 0.98 });
const enterBox = (await enter.boundingBox())!;
const unindentBox = (await unindent.boundingBox())!;
const pasteBox = (await paste.boundingBox())!;
expect(unindentBox.y).toBeGreaterThan(enterBox.y + enterBox.height);
expect(pasteBox.y).toBeGreaterThanOrEqual(unindentBox.y + unindentBox.height);
expect(Math.abs(pasteBox.x - unindentBox.x)).toBeLessThan(1);
expect((await escape.boundingBox())!.y).toBeGreaterThanOrEqual(pasteBox.y + pasteBox.height);
}
await paste.click();
await expect(page.getByRole("option", { name: "Indent Each Line", exact: true })).toBeInViewport();
});
test("Smart Keys keeps backspace and paste preferences independent across Apply and Cancel", async ({
workbench: page,
}) => {
const setOption = async (label: string, option: string) => {
await page
.getByRole("dialog", { name: "Settings", exact: true })
.getByRole("button", { name: label, exact: true })
.click();
await page.getByRole("option", { name: option, exact: true }).click();
};
const dialog = await openSmartKeys(page);
await setOption("Unindent on Backspace", "To nearest indent position");
await setOption("Reformat on paste", "Indent Block");
await dialog.getByRole("button", { name: "Apply", exact: true }).click();
await expect(dialog.getByRole("button", { name: "Apply", exact: true })).toBeDisabled();
await dialog.getByRole("button", { name: "Cancel", exact: true }).click();
const reopened = await openSmartKeys(page);
await expect(reopened.getByRole("button", { name: "Unindent on Backspace", exact: true })).toHaveText(
"To nearest indent position",
);
await expect(reopened.getByRole("button", { name: "Reformat on paste", exact: true })).toHaveText("Indent Block");
await setOption("Reformat on paste", "None");
await reopened.getByRole("button", { name: "Cancel", exact: true }).click();
const final = await openSmartKeys(page);
await expect(final.getByRole("button", { name: "Unindent on Backspace", exact: true })).toHaveText(
"To nearest indent position",
);
await expect(final.getByRole("button", { name: "Reformat on paste", exact: true })).toHaveText("Indent Block");
});
+1 -1
View File
@@ -2,7 +2,7 @@ Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: OpenIDEA JVM inspect
Bundle-SymbolicName: ai.openidea.jvminspect;singleton:=true
Bundle-Version: 1.1.0
Bundle-Version: 1.1.1
Bundle-RequiredExecutionEnvironment: JavaSE-21
Require-Bundle: org.eclipse.jdt.ls.core,org.eclipse.core.runtime,
org.eclipse.equinox.common,org.eclipse.jdt.debug,org.eclipse.core.resources
+8 -1
View File
@@ -123,6 +123,13 @@ ordinary `executeCommand` error.
invoke go on (ide-dap does that unseen while the trace runs).
The outcome is forced into the frame before it is pinned, so the pending return keeps it reachable;
should it be collected before that, the program gets the cancel exception and the trace fails.
- An exception the terminal threw (the cancel exception of `abort` included) ends the client's
`stepOut` in the program's catch. Nothing catching it, the thread would die with no stop left to
`collect` in, so before parking the bundle adds an uncaught-exception request on the thread,
suspending it: the step-out ends at that throw instead, as a java-debug `exception` stop, and a
resume lets the exception end the thread as it would have. Skipped when an enabled request of
java-debug's already reports uncaught throws of that type (one stop, not two). `collect` deletes it;
after `collect` a release no longer resumes the parked event, since that stop keeps the parked frames.
- `wait` returns as soon as the trace leaves `running`, or after `ms`, at most 30 000. While the
terminal runs it also checks every 500 ms whether the VM began to shut down
(`jdk.internal.misc.VM.initLevel`): `System.exit` in a lambda makes the VM wait forever to report
@@ -204,7 +211,7 @@ Java 21. The recorder is compiled by the `javac` on `PATH` with `--release 8`, s
run Java 8. Build twice and compare: two builds of the checked-in jar gave
```
22980a16bd8e303d67ed2e04d76d8974f2d3981120c26e6d9afa47ba361b1503 openidea-jvm-inspect.jar
4ab30723afe1254b991d9457ea66271109f397a17b238870572283aad73338ad openidea-jvm-inspect.jar
```
Change `Bundle-Version` whenever the jar changes: OSGi caches bundles by version.
Binary file not shown.
@@ -31,6 +31,8 @@ import com.sun.jdi.event.MethodExitEvent;
import com.sun.jdi.event.VMDeathEvent;
import com.sun.jdi.event.VMDisconnectEvent;
import com.sun.jdi.request.EventRequest;
import com.sun.jdi.request.EventRequestManager;
import com.sun.jdi.request.ExceptionRequest;
import com.sun.jdi.request.MethodEntryRequest;
import com.sun.jdi.request.MethodExitRequest;
import com.sun.jdi.request.StepRequest;
@@ -170,6 +172,10 @@ final class RealRunTrace {
private Value echoValue;
private EventSet parked;
private Method terminalMethod;
/** Stops the thread at a throw of the terminal's that nothing catches; see {@link #watchUncaught}. */
private volatile EventRequest uncaught;
/** {@code collect} ran, so the client's step-out ended in a stop of its own; see {@link #dispose}. */
private volatile boolean steppedOut;
private RealRunTrace(long id, VirtualMachine vm, ThreadReference thread, RealRunPlan plan, int budget, long generation) {
this.id = id;
@@ -514,6 +520,8 @@ final class RealRunTrace {
}
if (outcome instanceof ObjectReference object) keep(pinned(object));
restoreSilencers();
// Before the state moves: the client steps out as soon as it sees the trace parked.
if (kind.equals("threw")) watchUncaught((ObjectReference) outcome);
boolean hold;
synchronized (stateLock) {
terminalKind = kind;
@@ -532,10 +540,61 @@ final class RealRunTrace {
if (hold) {
parked = set;
terminalMethod = method;
} else {
deleteUncaught();
}
return hold;
}
/**
* Worker, before the trace parks on a terminal that threw. The client's step-out ends in the
* program's catch, but an exception nothing catches ends the thread, with no stop left to read the
* records in. This request stops the thread at that throw instead: java-debug reports every
* exception event as a stop. Not when an enabled request of java-debug's already stops there,
* since the throw would then be reported twice.
*/
private void watchUncaught(ObjectReference exception) {
try {
EventRequestManager manager = vm.eventRequestManager();
ReferenceType type = exception.referenceType();
for (ExceptionRequest r : manager.exceptionRequests()) {
if (r.isEnabled() && r.notifyUncaught() && r.getProperty(Silencer.OWN_PROPERTY) == null && covers(r.exception(), type)) {
return;
}
}
ExceptionRequest r = manager.createExceptionRequest(null, false, true);
r.addThreadFilter(thread);
r.setSuspendPolicy(EventRequest.SUSPEND_EVENT_THREAD);
r.putProperty(Silencer.OWN_PROPERTY, id);
r.enable();
uncaught = r;
} catch (VMDisconnectedException e) {
// nothing left to stop
} catch (RuntimeException e) {
errors.add("watching for an uncaught throw: " + e);
}
}
private static boolean covers(ReferenceType declared, ReferenceType type) {
for (ReferenceType t = type; t != null; t = t instanceof ClassType c ? c.superclass() : null) {
if (declared == null || t.equals(declared)) return true;
}
return false;
}
private void deleteUncaught() {
EventRequest r = uncaught;
if (r == null) return;
uncaught = null;
try {
vm.eventRequestManager().deleteEventRequest(r);
} catch (VMDisconnectedException e) {
// it went with the VM
} catch (RuntimeException e) {
errors.add("deleting the uncaught-throw request: " + e);
}
}
/**
* Worker, right before the terminal's invoke. JDWP holds an interrupt or stop of a thread that is
* handling an event until that event's handler exits, and an invoke runs inside the handler of the
@@ -758,9 +817,11 @@ final class RealRunTrace {
/** Worker: everything the trace holds, a parked thread the client never stepped out included. */
private void dispose() {
if (parked != null) {
if (stillParked()) resume(parked);
// A stop at an uncaught throw of the terminal's keeps the parked frames: resuming would end it behind java-debug.
if (!steppedOut && stillParked()) resume(parked);
parked = null;
}
deleteUncaught();
teardown();
for (ObjectReference o : pinned) {
try {
@@ -996,6 +1057,8 @@ final class RealRunTrace {
if (generation <= this.generation) {
throw new Failure("stale", "collect needs a stop after the trace's, not generation " + generation);
}
steppedOut = true;
deleteUncaught();
handles.begin(generation);
ToLongFunction<ObjectReference> handle = o -> {
long objectId = o.uniqueID();
+91
View File
@@ -100,6 +100,9 @@ public class Real {
case "inl": inLambda(); break;
case "abort": abort(); break;
case "twice": abortAfterTrace(); break;
case "U": uncaught(true); break;
case "Ux": uncaught(false); break;
case "Ua": abortUncaught(); break;
case "exit": exit(); break;
case "mid": mid(); break;
case "fn": functionAndData(); break;
@@ -244,6 +247,23 @@ public class Real {
}
}
/** Keeps the VM alive once main has died of an exception. */
static void keeper() {
new Thread(() -> LockSupport.parkNanos(60_000_000_000L), "keeper").start();
}
static void uncaught(boolean keep) {
if (keep) keeper();
List<Integer> u = nums.stream().map(x -> 10 / (x - 4)).collect(Collectors.toList()); // @U
System.out.println("U " + u);
}
static void abortUncaught() {
keeper();
long never = Stream.iterate(1L, x -> x + 1).filter(x -> x < 0).count(); // @Ua
System.out.println("UA none " + never);
}
static void exit() {
List<Integer> e = nums.stream().filter(x -> { // @exit
if (x == 8) System.exit(3);
@@ -1025,6 +1045,77 @@ def real_run_abort_after_a_trace():
dbg.end()
def uncaught_stop(dbg, name, trace, exception):
"""After a terminal that threw what the program does not catch: the step-out ends in one stop at that
throw, the records can be read there, and Resume lets the exception end the thread. False when no
stop came."""
try:
stop = step_out(dbg, 15)
except (TimeoutError, AssertionError) as e:
check(f'{name}: the uncaught throw stops the traced thread', False, repr(e))
return False
check(f'{name}: the uncaught throw stops the traced thread', stop.get('reason') == 'exception', stop)
check(f'{name}: one stop for the throw', no_stop(dbg, 2))
c = ok(stream('collect', dbg, traceId=trace))
t = c['terminal']
check(f'{name}: the terminal threw {exception}', t['kind'] == 'threw' and t['exception'].get('typeName') == exception, t)
check(f'{name}: release keeps the stop', 'ok' in stream('release', dbg, traceId=trace) and top(dbg) is not None)
resume(dbg)
out = output_line(dbg, 'Exception in thread "main" ' + exception)
check(f'{name}: the exception ends the thread as without the trace', out is not None, ''.join(dbg.dap.output)[-300:])
check(f'{name}: no stop after Resume', no_stop(dbg, 2))
return c
@case
def real_run_uncaught_throw():
# `U` keeps the VM alive with another thread; `Ux` exits with main.
for name in ('U', 'Ux'):
dbg = real(name, 'U')
try:
trace, state, _ = run_until_parked(dbg, 'U', steps=(spec('map', 1),), step_kinds=('sync',))
check(f'{name}: parked after the lambda threw', state['state'] == 'parked', state)
c = uncaught_stop(dbg, name, trace, 'java.lang.ArithmeticException')
if c:
collected_ok(name, c, records=['0=5', '1=10', '0=3', '1=-10', '0=8', '1=2', '0=1', '1=-3', '0=4'])
finally:
dbg.end()
@case
def real_run_uncaught_throw_user_filter():
# java-debug's own uncaught-exception request is on: the throw must stop once, not once per request.
dbg = real('U')
try:
dbg.dap.request('setExceptionBreakpoints', {'filters': ['uncaught']})
trace, state, _ = run_until_parked(dbg, 'U', steps=(spec('map', 1),), step_kinds=('sync',))
check('U-filter: parked after the lambda threw', state['state'] == 'parked', state)
uncaught_stop(dbg, 'U-filter', trace, 'java.lang.ArithmeticException')
finally:
dbg.end()
@case
def real_run_uncaught_abort():
dbg = real('Ua')
try:
trace = ok(arm(dbg, at='Ua', root=spec('iterate', 2), steps=(spec('filter', 1),), terminal=spec('count'),
class_filters=('java.util.stream.*',), step_kinds=('sync',)))['traceId']
resume(dbg)
first = ok(stream('wait', dbg, traceId=trace, ms=500))
check('Ua: the endless terminal is running', first['state'] == 'running', first)
r = ok(stream('abort', dbg, traceId=trace, timeout=30))
check('Ua: interrupted or stopped', r.get('state') in ('interrupted', 'stopped'), r)
state = wait_until_done(dbg, trace, 20)
check('Ua: parked after the cancel', state['state'] == 'parked', state)
if state['state'] == 'parked':
c = uncaught_stop(dbg, 'Ua', trace, 'java.lang.RuntimeException')
if c:
check('Ua: the records up to the abort', len(c['records']) > 0, len(c['records']))
finally:
dbg.end()
def next_breakpoint_stops(dbg, name, what):
"""After a trace that ended without parking: the user's breakpoints are back on."""
try:
+2
View File
@@ -26,6 +26,8 @@ adapter = "java-debug"
command = "com.microsoft.java.debug.plugin.jar"
transport = "tcp"
install-hint = "Install Microsoft java-debug (Settings › Languages & Frameworks › Language Servers › Java Debugger)"
# Its lazy values are toString() of objects whose class overrides it.
resolve-lazy-variables = true
[[language-servers]]
name = "jdtls"
+4
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
@@ -173,6 +176,7 @@ debug_jvm_memory_referrers trusted project_host bin
debug_listen_for_jvm trusted project_host bindings async
debug_pause trusted project_host bindings async
debug_redefine_classes trusted project_host bindings async
debug_resolve_variable trusted project_host bindings async
debug_restart_frame trusted project_host bindings async
debug_resume trusted project_host bindings async
debug_run_to trusted project_host bindings async
+141 -7
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 })),
/**
@@ -373,9 +385,9 @@ export const commands = {
/** Completions for an expression typed in Evaluate (`line` / `column` 0-based, UTF-16). */
debugCompletions: (session: DebugSessionId, frameId: number | null, text: string, line: number, column: number) => typedError<DebugCompletion[], IdeError>(__TAURI_INVOKE("debug_completions", { session, frameId, text, line, column })),
debugDataBreakpointInfo: (session: DebugSessionId, container: number, name: string, frameId: number | null) => typedError<DataBreakpointInfo, IdeError>(__TAURI_INVOKE("debug_data_breakpoint_info", { session, container, name, frameId })),
debugEvaluate: (session: DebugSessionId, frameId: number | null, expression: string) => typedError<Variable, IdeError>(__TAURI_INVOKE("debug_evaluate", { session, frameId, expression })),
debugEvaluate: (session: DebugSessionId, frameId: number | null, expression: string) => typedError<Variable_Serialize, IdeError>(__TAURI_INVOKE("debug_evaluate", { session, frameId, expression })),
/** Evaluate with an explicit DAP context: `repl`, `watch`, `hover` or `clipboard`. */
debugEvaluateIn: (session: DebugSessionId, frameId: number | null, expression: string, context: string | null) => typedError<Variable, IdeError>(__TAURI_INVOKE("debug_evaluate_in", { session, frameId, expression, context })),
debugEvaluateIn: (session: DebugSessionId, frameId: number | null, expression: string, context: string | null) => typedError<Variable_Serialize, IdeError>(__TAURI_INVOKE("debug_evaluate_in", { session, frameId, expression, context })),
debugExceptionFilters: () => typedError<SessionExceptionFilters[], IdeError>(__TAURI_INVOKE("debug_exception_filters")),
/** Force Step Over: step over with every breakpoint suspended until the step ends. */
debugForceStepOver: (session: DebugSessionId, threadId: number) => typedError<null, IdeError>(__TAURI_INVOKE("debug_force_step_over", { session, threadId })),
@@ -430,6 +442,7 @@ export const commands = {
debugPause: (session: DebugSessionId, threadId: number) => typedError<null, IdeError>(__TAURI_INVOKE("debug_pause", { session, threadId })),
/** HotSwap (Reload Changed Classes) in a java-debug session. */
debugRedefineClasses: (session: DebugSessionId) => typedError<HotSwapResult, IdeError>(__TAURI_INVOKE("debug_redefine_classes", { session })),
debugResolveVariable: (session: DebugSessionId, variable: Variable_Deserialize) => typedError<Variable_Serialize, IdeError>(__TAURI_INVOKE("debug_resolve_variable", { session, variable })),
/** Reset Frame (Drop Frame). */
debugRestartFrame: (session: DebugSessionId, frameId: number) => typedError<null, IdeError>(__TAURI_INVOKE("debug_restart_frame", { session, frameId })),
debugResume: (session: DebugSessionId, threadId: number) => typedError<null, IdeError>(__TAURI_INVOKE("debug_resume", { session, threadId })),
@@ -445,7 +458,7 @@ export const commands = {
debugSetExceptionBreakpoints: (choices: { [key in string]: boolean }) => typedError<null, IdeError>(__TAURI_INVOKE("debug_set_exception_breakpoints", { choices })),
/** Method breakpoints (all files); states aligned with `breakpoints`. */
debugSetFunctionBreakpoints: (breakpoints: FunctionBreakpoint[]) => typedError<BreakpointState[], IdeError>(__TAURI_INVOKE("debug_set_function_breakpoints", { breakpoints })),
debugSetVariable: (session: DebugSessionId, container: number, name: string, evaluateName: string | null, frameId: number | null, value: string) => typedError<Variable, IdeError>(__TAURI_INVOKE("debug_set_variable", { session, container, name, evaluateName, frameId, value })),
debugSetVariable: (session: DebugSessionId, container: number, name: string, evaluateName: string | null, frameId: number | null, value: string) => typedError<Variable_Serialize, IdeError>(__TAURI_INVOKE("debug_set_variable", { session, container, name, evaluateName, frameId, value })),
debugStackTrace: (session: DebugSessionId, threadId: number) => typedError<StackFrame[], IdeError>(__TAURI_INVOKE("debug_stack_trace", { session, threadId })),
/** Starts a session owned by this window: its events (and those of child sessions) go here only. */
debugStart: (config: LaunchConfig) => typedError<DebugSessionId, IdeError>(__TAURI_INVOKE("debug_start", { config })),
@@ -471,7 +484,7 @@ export const commands = {
{ kind: "finished" } | null, IdeError>(__TAURI_INVOKE("debug_stream_trace_abort", { session })),
debugThreads: (session: DebugSessionId) => typedError<ThreadInfo[], IdeError>(__TAURI_INVOKE("debug_threads", { session })),
debugUnityProcesses: () => typedError<AttachableProcess[], IdeError>(__TAURI_INVOKE("debug_unity_processes")),
debugVariables: (session: DebugSessionId, reference: number) => typedError<Variable[], IdeError>(__TAURI_INVOKE("debug_variables", { session, reference })),
debugVariables: (session: DebugSessionId, reference: number) => typedError<Variable_Serialize[], IdeError>(__TAURI_INVOKE("debug_variables", { session, reference })),
dependencyVersions: (doc: DocId, offset: number | null, request: RequestId) => typedError<DependencyVersions[], IdeError>(__TAURI_INVOKE("dependency_versions", { doc, offset, request })),
deployCompare: (path: IpcPath, server: string | null, request: RequestId) => typedError<SyncEntry[], IdeError>(__TAURI_INVOKE("deploy_compare", { path, server, request })),
deployCoverage: (paths: IpcPath[]) => typedError<DeploymentCoverage[], IdeError>(__TAURI_INVOKE("deploy_coverage", { paths })),
@@ -537,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.
*/
@@ -2687,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. */
@@ -2727,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. */
@@ -2801,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,
};
@@ -2851,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,
};
@@ -3801,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,
@@ -7125,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.
@@ -8160,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])[],
@@ -9013,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.
@@ -12383,13 +12496,34 @@ export type UpdateStatus = {
checking: boolean,
};
export type Variable = {
export type Variable = Variable_Serialize | Variable_Deserialize;
export type Variable_Deserialize = {
name: string,
value: string,
typeName: string | null,
/** > 0 when expandable. */
variablesReference: number,
evaluateName: string | null,
/**
* `value` is not computed yet (DAP `presentationHint.lazy`): the single variable that
* `variables` returns for `variables_reference` holds the value and its children.
*/
lazy?: boolean,
};
export type Variable_Serialize = {
name: string,
value: string,
typeName: string | null,
/** > 0 when expandable. */
variablesReference: number,
evaluateName: string | null,
/**
* `value` is not computed yet (DAP `presentationHint.lazy`): the single variable that
* `variables` returns for `variables_reference` holds the value and its children.
*/
lazy?: boolean,
};
/** Version Control › Confirmation. */
+2 -12
View File
@@ -68,6 +68,7 @@ import { cloneCaretAbove, cloneCaretBelow } from "./cm/verticalMotion";
import { pasteAsPlainText, pasteFromHistory, unwrapAtCaret } from "./extras";
import { cyclicExpandWord } from "./wordCompletion";
import { copyReferenceToClipboard, declaredName, qualifiedReference, referenceOffset } from "./copyReference";
import { selectedLineContext, selectedLines } from "./selectedLines";
import { declarationChain } from "./view/outline";
import { recordClipboard } from "./clipboardHistory";
import { useDocMeta, useOutline } from "./model/document";
@@ -589,15 +590,6 @@ function copyReference(reference: Promise<string>) {
}
}
/** The selected lines (1-based), leaving out the one a selection ends at the start of. */
function selectedLines(state: EditorState): { first: number; last: number } {
const { doc, selection } = state;
const { from, to } = selection.main;
const first = doc.lineAt(from).number;
const last = Math.max(first, doc.lineAt(to).number - (to > from && doc.lineAt(to).from === to ? 1 : 0));
return { first, last };
}
/** `path:12`, or `path:12-18` for a selection over several lines. */
function pathWithLines(state: EditorState, path: string): string {
const { first, last } = selectedLines(state);
@@ -606,11 +598,9 @@ function pathWithLines(state: EditorState, path: string): string {
function copyPathReferencePopup(view: EditorView, slot: EditorSlot) {
const path = slot.model.path;
const { first, last } = selectedLines(view.state);
const contributed = menuGroupItems("copyPath", {
paths: [path],
line: first - 1,
endLine: last > first ? last - 1 : undefined,
...selectedLineContext(view.state),
}).flatMap((item) =>
(item.kind ?? "item") === "item" && "run" in item && item.id && item.run && item.preview
? [
+4 -3
View File
@@ -115,6 +115,7 @@ import { isClassFile } from "@/platform/classFiles";
import { isVirtualUri, virtualDocument } from "@/platform/virtualDocs";
import type { VirtualDocument } from "@/platform/ipc";
import type { Scheduler } from "./sync/DocSync";
import { selectedLineContext } from "./selectedLines";
export const fileKey = (path: string) => `file:${path}`;
export const fileInput = (path: string): EditorInput => ({ kind: "file", key: fileKey(path), path });
@@ -994,7 +995,7 @@ export class EditorController implements SlotHost {
] as MenuItem[])
: ([
{ kind: "separator" },
openInMenu(slot.model.path, view.state.doc.lineAt(view.state.selection.main.head).number - 1),
openInMenu(slot.model.path, selectedLineContext(view.state)),
{ kind: "separator" },
localHistoryMenu(slot.model.path),
gitMenu(slot.model.path),
@@ -2352,7 +2353,7 @@ export class EditorController implements SlotHost {
}
/** Open In › for a file: Project View, Finder / Explorer / Files, associated app, Terminal. */
function openInMenu(path: string, line?: number): MenuItem {
function openInMenu(path: string, lines?: { line: number; endLine?: number }): MenuItem {
return {
label: "Open In",
submenu: [
@@ -2372,7 +2373,7 @@ function openInMenu(path: string, line?: number): MenuItem {
: []),
{ kind: "action", action: "project.openInTerminal", arg: path, label: "Terminal" },
{ kind: "separator" },
...menuGroupItems("openIn", { paths: [path], line }),
...menuGroupItems("openIn", { paths: [path], ...lines }),
],
};
}
+30
View File
@@ -239,6 +239,36 @@ describe("editor Copy Path/Reference chooser", () => {
]);
});
it("gives Open In contributions the selected lines", () => {
const contexts: MenuGroupContext[] = [];
disposers.push(
registerMenuGroup({
id: "test.openIn",
menus: ["openIn"],
items: (_menu, ctx) => {
contexts.push(ctx);
return [];
},
}),
);
const view = ctrl.activeSlot!.view!;
vi.spyOn(view, "posAtCoords").mockReturnValue(null);
// The caret; a selection from the second line back into the first; one ending at the start of the second.
for (const selection of [
{ anchor: documentText.indexOf("A {}") },
{ anchor: documentText.indexOf("A {}"), head: 0 },
{ anchor: 0, head: documentText.indexOf("class") },
]) {
view.dispatch({ selection });
ctrl.onContextMenu(ctrl.activeSlot!, new MouseEvent("contextmenu"));
}
expect(contexts.map(({ paths, line, endLine }) => [paths, line, endLine])).toEqual([
[[path], 1, undefined],
[[path], 0, 1],
[[path], 0, undefined],
]);
});
it("adds the chooser to Copy / Paste Special", () => {
vi.spyOn(ctrl.activeSlot!.view!, "posAtCoords").mockReturnValue(null);
ctrl.onContextMenu(ctrl.activeSlot!, new MouseEvent("contextmenu"));
+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.
+16
View File
@@ -0,0 +1,16 @@
import type { EditorState } from "@codemirror/state";
/** The main selection's lines (1-based), leaving out the one a selection ends at the start of, as IDEA. */
export function selectedLines(state: EditorState): { first: number; last: number } {
const { doc, selection } = state;
const { from, to } = selection.main;
const first = doc.lineAt(from).number;
const last = Math.max(first, doc.lineAt(to).number - (to > from && doc.lineAt(to).from === to ? 1 : 0));
return { first, last };
}
/** The selected lines as a menu group's 0-based `line` / `endLine` (absent for a single line). */
export function selectedLineContext(state: EditorState): { line: number; endLine?: number } {
const { first, last } = selectedLines(state);
return { line: first - 1, endLine: last > first ? last - 1 : undefined };
}
+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.")) {
+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",
Loaded 100 of 183 files, more files were not shown because too many files have changed in this diff. Show more