Compare commits

...
Author SHA1 Message Date
l0ng-ai 56ca3d42c9 fix(agents): record a task's turns across nested repositories
A local task in a project with nested git repositories recorded no turns, so the
Changes pane's last-turn scope stayed empty there and the whole-task list no longer
kept to the files the task touched. A turn now records each repository's HEAD as it
starts; the files a turn changed, their text when it began and its rollback come
from the repository holding each file, including commits made in a nested one.
2026-11-21 06:37:54 +08:00
Paweł SzymańskiandPawelSzymanski89 c3f420374c fix(agents): list task changes per repository, including nested repos (#4543)
A local agent task in a project that holds nested git repositories (an own .git below the project root, not a submodule) only saw the changes of the repository at its root. Its changes are now read from every repository under the root, each against its own HEAD; the Changes pane groups them under a row per repository when there are several, and a rollback reads each file from its own repository.

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

Co-authored-by: PawelSzymanski89 <[email protected]>
2026-11-21 06:32:34 +08:00
faysouandfaysou 6bf7bc8c2b fix(vcs): apply Directory Mappings changes to all selected roots (#4908)
Directory Mappings now supports multi-row selection with Cmd/Ctrl and Shift. Minus moves the selected Git roots to an Unregistered roots section instead of only removing manually added ones, and plus registers the selected unregistered roots again in one step. Applying a removal refreshes Git status and branches: removing the selected repository switches to the remaining one, and removing the last repository clears the previous Git state and decorations.

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

Co-authored-by: faysou <[email protected]>
2026-11-21 06:18:36 +08:00
faysouandfaysou 34dfc166db fix(vcs): keep Git Log paths and branches in sync (#4907)
The Paths filter of the Git Log now holds the repository checkboxes, path entry, the file and folder tree and recent paths. Selecting paths replaces the repository selection, so a path in another repository no longer leaves the log empty, and the commit log and the Branches panel are scoped to the repositories the paths belong to.

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

Co-authored-by: faysou <[email protected]>
2026-11-21 06:15:44 +08:00
Chris Schofield 64632dc4d7 feat(editor): JSX/TSX tag editing — linked tag rename, prop values, Emmet (#4905)
JSX/TSX editing like the HTML modes: editing an opening or closing tag's name renames its partner (Simultaneous <tag></tag> editing), Enter between a tag pair puts the caret on an indented line with the closing tag below, and JSX tag pairs are matched. Typing = after a value-less prop inserts "" for string-typed props and {} otherwise (type from the server's hover, {} after 500 ms), following Pair quotes / Pair brackets. Emmet expands with Tab among an element's children and after return / => (className, self-closing void elements). Under TypeScript 7 the native server is asked for jsxAttributeCompletionStyle auto, so prop completion inserts the value delimiters as vtsls does.

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

Co-authored-by: ChildishForces <[email protected]>
2026-11-21 05:45:10 +08:00
Mr0Bread f484fd6802 fix(agents): let chats select any model their agent's catalog lists (#4901)
An existing agent chat listed models from the agent's catalog but refused to switch to them unless the catalog was under 15 minutes old and matched the launch fingerprint. A model the picker lists is now always selectable. The chat's picker offers the agent's current catalog plus the model the chat runs, and falls back to the session's own list when there is no catalog. The per-task copy of models and effort levels is removed, so the project catalog is the only source of available models and efforts.

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

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

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

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

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

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

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

A failed save only showed its message in the Could not save notification, and a failed autosave of a closed tab went to the console. Both are now written to the log file with their stack, so a report's log shows where the save failed.
2026-11-21 02:49:14 +08:00
Emir 51bab9a25b feat(i18n): add Turkish localization (#4881)
Turkish joins the UI languages (Settings > Appearance > Language), with the key catalog and the source-text catalog; tr / tr-TR system locales resolve to it.

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

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

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

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

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

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

The dirty-scope status refresh (and the full one when gitoxide can't read the tree) ran git status, which writes refreshed stat data back to .git/index. The watcher can't tell that write from an external one, so it scheduled another refresh that could run git again. git status now runs with GIT_OPTIONAL_LOCKS=0 and leaves the index alone; our own gitoxide write-back is unchanged.
2026-11-21 01:45:09 +08:00
Ernstjan FreriksandEjaYF 745038b4e2 fix(markdown): zoom preview images with ⌘/Ctrl+wheel like Mermaid diagrams (#4729)
Images in the Markdown preview get the pan/zoom Mermaid diagrams already have: Cmd/Ctrl+wheel zooms the image at the cursor, drag pans once zoomed, double-click resets; the image keeps its place and size in the page and font zoom still scales it.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

No files matched your search

+18 -48
View File
@@ -194,14 +194,14 @@ impl AgentCatalogs {
(shared.paths.models_file.clone(), shared.paths.project_root.clone(), provider.to_owned())
}
fn fallback(shared: &Shared, provider: &str) -> CatalogData {
/// The catalog saved for this project, for before this run looked anything up.
fn saved(shared: &Shared, provider: &str) -> CatalogData {
let cache = shared.known.lock();
let Some(known) = cache.get(provider) else { return CatalogData::default() };
known.catalogs.get(&shared.root_key()).map(|saved| saved.catalog.clone()).unwrap_or_else(|| CatalogData {
config: known.config.clone(),
thought_levels: known.thought_levels.clone(),
refreshed_at_ms: None,
})
cache
.get(provider)
.and_then(|known| known.catalogs.get(&shared.root_key()))
.map(|saved| saved.catalog.clone())
.unwrap_or_default()
}
pub(crate) fn cached(&self, shared: &Shared, provider: &str) -> CatalogData {
@@ -210,32 +210,14 @@ impl AgentCatalogs {
.entries
.get(&Self::key(shared, provider))
.and_then(|e| e.catalog.clone())
.unwrap_or_else(|| Self::fallback(shared, provider))
.unwrap_or_else(|| Self::saved(shared, provider))
}
/// Availability for an explicit session switch must come from a recent discovery for this
/// launch, not from the display fallback or a different project's session report.
pub(super) fn fresh_model(
&self,
shared: &Shared,
spec: &provider::ProviderSpec,
model: &str,
) -> Option<crate::AgentConfigValue> {
let context = LaunchContext::new(spec.clone(), &shared.paths.project_root);
let select = |catalog: &CatalogData| {
let age = self.epoch_ms() - catalog.refreshed_at_ms?;
if !(0.0..FRESH_FOR.as_millis() as f64).contains(&age) {
return None;
}
catalog.model_option()?.values.iter().find(|value| value.value == model).cloned()
};
let state = self.state.lock();
if let Some(entry) = state.entries.get(&Self::key(shared, &spec.id)) {
return select(entry.catalog.as_ref().filter(|_| entry.context == context)?);
}
let cache = shared.known.lock();
let saved = cache.get(&spec.id)?.catalogs.get(&shared.root_key())?;
(saved.fingerprint == context.fingerprint()).then(|| select(&saved.catalog)).flatten()
/// The entry a chat may switch to: exactly what the picker offers from the cached catalog,
/// however long ago it was read. Refreshing keeps that catalog current; a listed model is
/// never refused because the catalog aged.
pub(super) fn listed_model(&self, shared: &Shared, provider: &str, model: &str) -> Option<crate::AgentConfigValue> {
self.cached(shared, provider).model_option()?.values.iter().find(|value| value.value == model).cloned()
}
pub(crate) fn levels(&self, shared: &Shared, provider: &str, model: &str) -> Option<Vec<AgentConfigOption>> {
@@ -246,14 +228,7 @@ impl AgentCatalogs {
}
drop(state);
let cache = shared.known.lock();
let known = cache.get(provider)?;
known
.catalogs
.get(&shared.root_key())
.map(|saved| &saved.catalog.thought_levels)
.unwrap_or(&known.thought_levels)
.get(model)
.cloned()
cache.get(provider)?.catalogs.get(&shared.root_key())?.catalog.thought_levels.get(model).cloned()
}
pub(super) async fn load_levels(
@@ -297,7 +272,7 @@ impl AgentCatalogs {
}
fn snapshot(&self, shared: &Shared, provider: &str, entry: &Entry) -> AgentModelCatalog {
let catalog = entry.catalog.clone().unwrap_or_else(|| Self::fallback(shared, provider));
let catalog = entry.catalog.clone().unwrap_or_default();
let model_failure = entry.requested_model.as_ref().and_then(|model| entry.model_failures.get(model));
let unknown_model = entry
.requested_model
@@ -382,12 +357,11 @@ impl AgentCatalogs {
},
);
}
let fallback =
state.entries.get(&key).filter(|entry| entry.catalog.is_none()).map(|_| Self::fallback(shared, &spec.id));
state.generation += 1;
let generation = state.generation;
let entry = state.entries.get_mut(&key).expect("catalog entry");
let catalog = entry.catalog.as_ref().or(fallback.as_ref()).expect("cached catalog");
let empty = CatalogData::default();
let catalog = entry.catalog.as_ref().unwrap_or(&empty);
let fresh = entry.successful.is_some_and(|at| now.duration_since(at) < FRESH_FOR);
let target = model
.filter(|model| {
@@ -496,7 +470,7 @@ impl AgentCatalogs {
entry.flight_model = None;
let success = match result {
Ok(found) => {
let previous = entry.catalog.take().unwrap_or_else(|| Self::fallback(shared, &key.2));
let previous = entry.catalog.take().unwrap_or_default();
let mut cache = shared.known.lock();
let known = cache.entry(key.2.clone()).or_default();
let mut catalog = CatalogData {
@@ -510,13 +484,9 @@ impl AgentCatalogs {
catalog.thought_levels.insert(model, levels);
}
}
known.config = catalog.config.clone();
known.thought_levels = catalog.thought_levels.clone();
if let Some(commands) = found.commands {
known.commands.insert(shared.root_key(), commands);
}
known.authoritative = true;
known.refreshed_at_ms = catalog.refreshed_at_ms;
known.catalogs.insert(
shared.root_key(),
SavedCatalog { fingerprint: entry.context.fingerprint(), catalog: catalog.clone() },
+23 -12
View File
@@ -230,11 +230,9 @@ async fn successful_refresh_replaces_models_and_efforts_and_old_sessions_cannot_
let manager = make_manager(tmp.path(), catalogs.clone(), &harness);
let mut events = events(&manager);
let old = config::options_of(&response(&["old", "retained"], &["low", "high"]));
manager.shared.remember(PROVIDER, Some(&old), None, Some("old"));
let cached = manager.refresh_models(PROVIDER, false, None).unwrap();
assert!(cached.refreshing);
assert_eq!(model_values(&cached), ["old", "retained"]);
assert!(cached.refreshed_at_ms.is_none(), "session reports are not fresh discovery");
assert!(model_values(&cached).is_empty(), "nothing is offered before the first discovery");
let pending = harness.next().await;
assert_eq!(pending.params["mcpServers"], json!([]));
pending.reply.send(Ok(response(&["retained", "new"], &["medium"]))).unwrap();
@@ -258,7 +256,10 @@ async fn successful_refresh_replaces_models_and_efforts_and_old_sessions_cannot_
assert_eq!(provider.config, fresh.config);
restored.shared.remember(PROVIDER, Some(&old), None, Some("old"));
assert_eq!(restored.shared.known_config(PROVIDER), fresh.config);
assert_eq!(restored.shared.known.lock()[PROVIDER].refreshed_at_ms, fresh.refreshed_at_ms);
assert_eq!(
restored.shared.paths.catalogs.cached(&restored.shared, PROVIDER).refreshed_at_ms,
fresh.refreshed_at_ms
);
assert!(!tmp.path().join("store").exists(), "refresh never creates tasks");
}
@@ -308,6 +309,11 @@ async fn discovered_model_reloads_the_same_session_on_the_next_message() {
switch_chat_model(ChatSwitch::Resume).await;
}
#[tokio::test]
async fn discovered_model_from_an_aged_catalog_can_still_be_selected() {
switch_chat_model(ChatSwitch::Aged).await;
}
#[tokio::test]
async fn discovered_model_leaves_the_original_session_intact_after_resume_failure() {
switch_chat_model(ChatSwitch::ResumeFails).await;
@@ -356,6 +362,7 @@ async fn discovered_model_lookup_does_not_overwrite_a_newer_selection() {
#[derive(Clone, Copy)]
enum ChatSwitch {
Live,
Aged,
Resume,
ResumeFails,
Unavailable,
@@ -376,7 +383,8 @@ async fn switch_chat_model(scenario: ChatSwitch) {
let mut harness = Harness::with_initialize(json!({
"protocolVersion": 1, "agentCapabilities": { "loadSession": true }
}));
let mut manager = make_manager(tmp.path(), Arc::default(), &harness);
let catalogs = Arc::new(AgentCatalogs::default());
let mut manager = make_manager(tmp.path(), catalogs.clone(), &harness);
let task = manager
.create(NewAgentTask {
prompt: AgentPrompt { text: "first".into(), ..Default::default() },
@@ -443,7 +451,11 @@ async fn switch_chat_model(scenario: ChatSwitch) {
}
assert_eq!(manager.task(&task.id).unwrap().state.lock().task.config, before_config);
let live = matches!(scenario, ChatSwitch::Live);
let live = matches!(scenario, ChatSwitch::Live | ChatSwitch::Aged);
if matches!(scenario, ChatSwitch::Aged) {
// The catalog stays what the picker offers however long ago it was read.
advance(&catalogs, 20 * 60);
}
let resumed_launch = if missing_settings { 3 } else { 2 };
let load_fails = matches!(scenario, ChatSwitch::ResumeFails);
let unavailable = matches!(scenario, ChatSwitch::Unavailable);
@@ -684,7 +696,7 @@ async fn next_chat_request(
}
#[tokio::test]
async fn legacy_cache_loads_without_claiming_authoritative_freshness() {
async fn a_cache_from_before_project_catalogs_offers_nothing_until_discovery_succeeds() {
let tmp = tempfile::tempdir().unwrap();
configure(tmp.path(), "one");
let options = config::options_of(&response(&["legacy"], &["low"]));
@@ -700,12 +712,11 @@ async fn legacy_cache_loads_without_claiming_authoritative_freshness() {
let manager = make_manager(tmp.path(), Arc::default(), &harness);
let mut events = events(&manager);
let cached = manager.refresh_models(PROVIDER, false, None).unwrap();
assert_eq!(model_values(&cached), ["legacy"]);
assert!(model_values(&cached).is_empty());
assert!(cached.refreshing && cached.refreshed_at_ms.is_none());
harness.next().await.reply.send(Err("Sign in required".into())).unwrap();
let failed = completed(&mut events).await;
assert_eq!(failed.config, cached.config);
assert!(failed.error.as_deref().unwrap().contains("Sign in required"));
harness.next().await.reply.send(Ok(response(&["current"], &["low"]))).unwrap();
let found = completed(&mut events).await;
assert_eq!(model_values(&found), ["current"]);
}
#[tokio::test]
+193 -60
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,27 +169,18 @@ struct Shared {
idle_release_ms: AtomicU64,
mcp_servers_hook: RwLock<Option<Arc<McpServersFn>>>,
mcp_executable_hook: RwLock<Option<Arc<McpExecutableFn>>>,
skills_policy_hook: RwLock<Option<Arc<SkillsPolicyFn>>>,
/// Monotonic id for [`AgentEvent::Attention`] episodes.
attention_seq: AtomicU64,
}
/// What an agent offered in its last session, for the New Task page.
/// What an agent offered, for the New Task page.
#[derive(Clone, Default, Serialize, Deserialize)]
struct Known {
#[serde(default)]
config: Vec<AgentConfigOption>,
/// Thinking levels reported for each model value, including its last choice.
#[serde(default, rename = "thoughtLevels")]
thought_levels: BTreeMap<String, Vec<AgentConfigOption>>,
/// By project root: skills and custom commands differ per project.
#[serde(default, rename = "projectCommands")]
commands: HashMap<String, Vec<AgentCommand>>,
/// Successful discovery, unlike a session report, owns availability.
#[serde(default)]
authoritative: bool,
#[serde(default, rename = "refreshedAtMs")]
refreshed_at_ms: Option<f64>,
/// Authoritative availability and freshness are scoped to project and launch context.
/// Model catalogs by project root, valid for the launch context they were read with.
#[serde(default, rename = "projectCatalogs")]
catalogs: HashMap<String, catalogs::SavedCatalog>,
}
@@ -294,7 +298,8 @@ impl Shared {
self.paths.project_root.to_string_lossy().into_owned()
}
/// Cache levels only when `model` confirms which model the session reported them for.
/// Keeps the commands a session offered and the effort levels it reported for `model`, the
/// only model whose levels it describes.
fn remember(
&self,
provider: &str,
@@ -303,43 +308,22 @@ impl Shared {
model: Option<&str>,
) {
let acp = self.spec(provider).is_some_and(|spec| spec.driver == provider::Driver::Acp);
let mut cache = self.known.lock();
let known = cache.entry(provider.to_owned()).or_default();
let mut changed = false;
// Running tasks retain their own reported settings. Once discovery has
// succeeded, a session's older list/defaults cannot change New Task choices.
if !known.authoritative
&& let Some(config) = config.filter(|c| !c.is_empty())
{
if let Some(model) = model {
let levels: Vec<_> = config.iter().filter(|o| config::is_per_model_option(o)).cloned().collect();
if known.thought_levels.get(model) != Some(&levels) {
known.thought_levels.insert(model.to_owned(), levels);
changed = true;
}
}
if known.config != config {
known.config = config.to_vec();
if let Some(commands) = commands.filter(|c| !c.is_empty()) {
let mut cache = self.known.lock();
let known = cache.entry(provider.to_owned()).or_default();
if known.commands.get(&self.root_key()).map(Vec::as_slice) != Some(commands) {
known.commands.insert(self.root_key(), commands.to_vec());
self.persist_known(&cache);
changed = true;
}
}
// Discovery reads one model's options; a session on another model reports that model's.
let learned = model.filter(|_| acp && known.authoritative).zip(config).map(|(model, config)| {
if acp && let Some((model, config)) = model.zip(config) {
let levels: Vec<_> = config.iter().filter(|o| config::is_per_model_option(o)).cloned().collect();
(model, levels)
});
if let Some(commands) = commands.filter(|c| !c.is_empty())
&& known.commands.get(&self.root_key()).map(Vec::as_slice) != Some(commands)
{
known.commands.insert(self.root_key(), commands.to_vec());
changed = true;
}
if changed {
self.persist_known(&cache);
}
drop(cache);
if let Some((model, levels)) = learned.filter(|(_, levels)| !levels.is_empty()) {
self.paths.catalogs.learn_levels(self, provider, model, levels);
if !levels.is_empty() {
self.paths.catalogs.learn_levels(self, provider, model, levels);
}
}
if changed {
self.emit(AgentEvent::Providers);
@@ -528,6 +512,8 @@ struct Task {
idle_epoch: AtomicU64,
/// Turned on when per-session MCP overrides changed while a turn was busy; dropped once idle.
mcp_reload_pending: AtomicBool,
/// Turned on when per-session skill overrides changed while a turn was busy; dropped once idle.
skills_reload_pending: AtomicBool,
/// Settings already sent this session (`(option, value)`), so a refusal is not retried.
config_sent: Mutex<HashSet<(String, String)>>,
dirty: Mutex<BTreeSet<(Session, usize)>>,
@@ -575,6 +561,7 @@ impl AgentManager {
idle_release_ms: AtomicU64::new(IDLE_RELEASE.as_millis() as u64),
mcp_servers_hook: RwLock::new(None),
mcp_executable_hook: RwLock::new(None),
skills_policy_hook: RwLock::new(None),
attention_seq: AtomicU64::new(0),
});
shared.paths.catalogs.subscribe(&shared);
@@ -724,10 +711,15 @@ impl AgentManager {
*self.shared.mcp_executable_hook.write() = Some(Arc::from(hook));
}
/// Provides the user and workspace skill policies and the workspace's trust.
pub fn set_skills_policy_hook(&self, hook: Box<SkillsPolicyFn>) {
*self.shared.skills_policy_hook.write() = Some(Arc::from(hook));
}
/// The slash commands to complete for `provider`, in `task`'s directory or (without one)
/// in the project: what the agent offered last time there, unadvertised builtins,
/// and, for Claude Code, skills and custom commands on disk it has not listed (for Hermes,
/// its profile's skills).
/// for Claude Code the skills and custom commands on disk it has not listed (for
/// Hermes, its profile's skills), and the skills hub's active skills for every agent.
pub async fn commands(&self, provider: &str, task: Option<&str>) -> IdeResult<Vec<AgentCommand>> {
let (provider, offered, cwd) = match task {
Some(id) => {
@@ -770,11 +762,44 @@ impl AgentManager {
.await?;
return Ok(skills::merge(offered, found));
}
if provider != "claude" && provider != "claude-acp" {
return Ok(offered);
if provider == "claude" || provider == "claude-acp" {
let claude_cwd = cwd.clone();
let found = blocking(move || Ok(skills::discover(&claude_cwd, home.as_deref()))).await?;
offered = skills::merge(offered, found);
}
let found = blocking(move || Ok(skills::discover(&cwd, home.as_deref()))).await?;
Ok(skills::merge(offered, found))
// The hub's active skills complete on every agent; its `off` ones drop out here,
// which is all the enforcement an ACP agent gets.
let holder = self.task_for_commands(&provider, task);
let states = match holder {
Some(holder) => holder.skill_states().await,
None => {
let (policy, root) = {
let shared = &self.shared;
let policy = shared.skills_policy_hook.read().as_ref().map(|hook| hook()).unwrap_or_default();
(policy, shared.paths.project_root.clone())
};
let home = self.shared.paths.home_dir.clone();
blocking(move || {
Ok(skills::resolve(
skills::discover_skills(&root, home.as_deref()),
None,
&policy.workspace,
&policy.user,
policy.workspace_trusted,
))
})
.await
.unwrap_or_default()
}
};
Ok(skills::menu_commands(offered, &states))
}
/// The task to resolve skills for, when the commands are for one and its provider matches.
fn task_for_commands(&self, provider: &str, task: Option<&str>) -> Option<Arc<Task>> {
let task = self.task(task?).ok()?;
let matches = task.state.lock().task.provider == provider;
matches.then_some(task)
}
fn task(&self, id: &str) -> IdeResult<Arc<Task>> {
@@ -858,6 +883,7 @@ impl AgentManager {
retry: None,
background: Box::default(),
mcp_overrides: BTreeMap::new(),
skill_overrides: BTreeMap::new(),
stats: Box::default(),
};
let file = TaskFile {
@@ -976,6 +1002,7 @@ impl AgentManager {
retry: None,
background: Box::default(),
mcp_overrides: req.mcp_overrides,
skill_overrides: req.skill_overrides,
stats: Box::default(),
};
let file = TaskFile {
@@ -1319,13 +1346,14 @@ impl AgentManager {
(s.task.cwd.0.clone(), s.task.provider.clone(), s.task.mcp_overrides.clone())
};
let mcp_servers = source.shared.mcp_servers_for_session(&provider_id, &live.init, &mcp_overrides);
let skills_delivery = source.stage_skills(stage_key(live.driver), &cwd).await;
let cwd_s = dunce::canonicalize(&cwd).unwrap_or(cwd).to_string_lossy().into_owned();
let reply: Value = live
.peer
.request(
"session/fork",
{
let mut params = session_params(&cwd_s, &mcp_servers);
let mut params = session_params(&cwd_s, &mcp_servers, skills_delivery.as_ref());
params["sessionId"] = json!(live.session);
params
},
@@ -1726,6 +1754,7 @@ impl AgentManager {
*task.deleted.lock() = true;
let _ = std::fs::remove_file(self.shared.paths.store_dir.join(format!("{id}.json")));
let _ = std::fs::remove_dir_all(task.turn_dir());
skills::remove_farm(&self.shared.paths.store_dir, id);
let saved = task.state.lock().saved.clone();
if let Some(saved) = saved
&& !self.tasks.read().values().any(|t| t.state.lock().saved.as_ref() == Some(&saved))
@@ -1987,6 +2016,38 @@ impl AgentManager {
Ok(out)
}
/// Sets the session's skill modes; like MCP overrides, a change reaches the agent when
/// its idle session is recycled and the next turn starts fresh.
pub fn set_skill_overrides(&self, id: &str, overrides: BTreeMap<String, AgentSkillMode>) -> IdeResult<AgentTask> {
let task = self.task(id)?;
let cleaned: BTreeMap<String, AgentSkillMode> = overrides
.into_iter()
.filter_map(|(k, v)| (!k.trim().is_empty()).then(|| (k.trim().to_owned(), v)))
.collect();
let (changed, busy, has_bg, out) = {
let mut s = task.state.lock();
if s.task.status == AgentStatus::Archived {
return Err(IdeError::invalid("the task is archived"));
}
let changed = s.task.skill_overrides != cleaned;
if changed {
s.task.skill_overrides = cleaned;
s.task.updated_ms = now_ms();
}
(changed, s.busy, !s.background_tasks.is_empty(), s.task.clone())
};
if changed {
task.persist();
task.emit_task();
if busy || has_bg || !task.permissions.lock().is_empty() {
task.skills_reload_pending.store(true, Ordering::Release);
} else {
task.recycle_resumable_session();
}
}
Ok(out)
}
/// Recycles idle resumable live sessions (or schedules reload after the running turn) when
/// global, workspace, or built-in IDE MCP server settings change.
pub fn notify_mcp_servers_changed(&self) {
@@ -2019,6 +2080,55 @@ impl AgentManager {
}
impl Task {
/// The skills offered in this project: every discovery resolved against the policies
/// and the task's overrides.
async fn skill_states(&self) -> Vec<AgentSkillState> {
let (policy, overrides, home, root) = {
let shared = &self.shared;
let policy = shared.skills_policy_hook.read().as_ref().map(|hook| hook()).unwrap_or_default();
let overrides = self.state.lock().task.skill_overrides.clone();
(policy, overrides, shared.paths.home_dir.clone(), shared.paths.project_root.clone())
};
blocking(move || {
Ok(skills::resolve(
skills::discover_skills(&root, home.as_deref()),
Some(&overrides),
&policy.workspace,
&policy.user,
policy.workspace_trusted,
))
})
.await
.unwrap_or_default()
}
/// Stages the session's skills into the task's farm and reports what its CLI takes.
/// Nothing staged for an ACP agent (its `/` menu is filtered instead), and a failed
/// stage (locked files, full disk) runs the session without the farm.
async fn stage_skills(&self, provider: &str, cwd: &Path) -> Option<skills::Delivery> {
let states = self.skill_states().await;
let (farm, home, out_cwd) = {
(
skills::farm_dir(&self.shared.paths.store_dir, &self.id),
self.shared.paths.home_dir.clone(),
cwd.to_path_buf(),
)
};
let provider = provider.to_owned();
match blocking(move || {
skills::stage(&farm, &provider, &states, &out_cwd, home.as_deref())
.map_err(|e| IdeError::internal(e.to_string()))
})
.await
{
Ok(delivery) => Some(delivery),
Err(e) => {
tracing::warn!("agent task {}: staging its skills failed: {e}", self.id);
None
}
}
}
fn restore(file: TaskFile, shared: Arc<Shared>) -> Arc<Self> {
let mut task = file.task;
config::add_client_options(&task.provider, &mut task.config);
@@ -2075,6 +2185,7 @@ impl Task {
turns: AtomicU64::new(0),
idle_epoch: AtomicU64::new(0),
mcp_reload_pending: AtomicBool::new(false),
skills_reload_pending: AtomicBool::new(false),
config_sent: Mutex::new(HashSet::new()),
dirty: Mutex::new(BTreeSet::new()),
streamed: Mutex::new(HashMap::new()),
@@ -2366,7 +2477,8 @@ impl Task {
if stop != "cancelled" {
self.emit_attention(AgentAttentionReason::Finished);
}
if self.mcp_reload_pending.swap(false, Ordering::AcqRel)
if (self.mcp_reload_pending.swap(false, Ordering::AcqRel)
|| self.skills_reload_pending.swap(false, Ordering::AcqRel))
&& self.state.lock().background_tasks.is_empty()
{
self.recycle_resumable_session();
@@ -2395,8 +2507,7 @@ impl Task {
async fn switch_discovered_model(&self, target: AgentConfigOption, value: String) -> IdeResult<()> {
let provider = self.state.lock().task.provider.clone();
let spec = self.shared.spec(&provider).ok_or_else(|| IdeError::not_found("no such agent"))?;
let candidate = self.shared.paths.catalogs.fresh_model(&self.shared, &spec, &value).ok_or_else(|| {
let candidate = self.shared.paths.catalogs.listed_model(&self.shared, &provider, &value).ok_or_else(|| {
IdeError::invalid(format!("{} has no value {value} in the current model catalog", target.name))
})?;
let selection = {
@@ -2884,6 +2995,7 @@ impl Task {
let (capabilities, embedded) = capabilities_of(&init);
let mcp_overrides = self.state.lock().task.mcp_overrides.clone();
let mcp_servers = self.shared.mcp_servers_for_session(provider_id, &init, &mcp_overrides);
let skills_delivery = self.stage_skills(stage_key(spec.driver), cwd).await;
// Agents that compare canonical paths fail in a symlinked directory (macOS `/tmp`).
let cwd_s = dunce::canonicalize(cwd).unwrap_or_else(|_| cwd.to_path_buf()).to_string_lossy().into_owned();
@@ -2898,7 +3010,7 @@ impl Task {
}
if let (Some(id), true, false) = (saved, can_load, start_fresh) {
self.replaying.store(true, Ordering::Release);
let mut params = session_params(&cwd_s, &mcp_servers);
let mut params = session_params(&cwd_s, &mcp_servers, skills_delivery.as_ref());
params["sessionId"] = json!(&id);
let loaded = self.request_with_auth(&peer, &init, &mut tried_auth, "session/load", params).await;
tokio::time::sleep(REPLAY_GRACE).await;
@@ -2938,7 +3050,7 @@ impl Task {
let (session_id, result) = match session {
Some(s) => s,
None => {
let params = session_params(&cwd_s, &mcp_servers);
let params = session_params(&cwd_s, &mcp_servers, skills_delivery.as_ref());
let v = self.request_with_auth(&peer, &init, &mut tried_auth, "session/new", params).await.map_err(
|e| match self.sign_in_error(&e, Some(&sign_in_message)) {
Some(msg) => SessionOpenError { message: msg, allow_acp_fallback: false },
@@ -3914,13 +4026,34 @@ struct McpForSession {
off: Vec<String>,
}
/// The driver a session's staged skills are staged for (`skills::stage` matches on it):
/// the native CLIs take the farm, everything else (an ACP agent) gets the `/` menu filter.
fn stage_key(driver: provider::Driver) -> &'static str {
match driver {
provider::Driver::Claude => "claude",
provider::Driver::Codex => "codex",
provider::Driver::Copilot => "copilot",
provider::Driver::Acp => "acp",
}
}
/// The session parameters `session/new`, `session/load` and `session/fork` share: the MCP
/// servers, and the ones off for this session, so an agent that also loads its own
/// configuration (Claude Code) can keep a same-named server of it off too.
fn session_params(cwd: &str, mcp: &McpForSession) -> Value {
/// configuration (Claude Code) can keep a same-named server of it off too — plus the
/// session's staged skills for the drivers that take them.
fn session_params(cwd: &str, mcp: &McpForSession, skills: Option<&skills::Delivery>) -> Value {
let mut params = json!({ "cwd": cwd, "mcpServers": mcp.servers });
let mut meta = json!({});
if !mcp.off.is_empty() {
params["_meta"] = json!({ "openidea": { "mcpServersOff": mcp.off } });
meta["mcpServersOff"] = json!(mcp.off);
}
if let Some(skills) = skills
&& let Ok(v) = serde_json::to_value(skills)
{
meta["skills"] = v;
}
if !meta.is_null() && meta.as_object().is_some_and(|m| !m.is_empty()) {
params["_meta"] = json!({ "openidea": meta });
}
params
}
+86
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)]
@@ -705,6 +711,8 @@ pub struct AgentChange {
pub removed: u32,
/// Path before a rename; the left side of its diff reads this path.
pub old_path: Option<String>,
/// The repository the file is in, when the task's project holds nested repositories.
pub repo: Option<IpcPath>,
}
/// A commit made while the task ran, with the files it changed against its first parent.
@@ -879,6 +887,84 @@ fn default_true() -> bool {
true
}
pub use ide_core::settings::{AgentSkillMode, AgentSkillPolicy};
/// Which CLI's own folders a skill was discovered in (Settings › Agents › Skills groups by it).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentSkillSource {
/// The project's `.agents/skills` and `.openidea/skills`.
#[default]
Workspace,
/// The user's `~/.agents/skills` (what `npx skills add` fills).
User,
/// The project's `.claude/skills`.
ClaudeWorkspace,
/// `~/.claude/skills`.
ClaudeUser,
/// The project's `.github/skills` (Copilot's repository skills).
GithubWorkspace,
/// `~/.copilot/skills` and `~/.copilot/installed-plugins/*`.
CopilotUser,
/// The project's `.codex/skills`.
CodexWorkspace,
/// `~/.codex/skills`.
CodexUser,
/// The project's `.cursor/skills`.
CursorWorkspace,
/// `~/.cursor/skills`.
CursorUser,
}
impl AgentSkillSource {
/// Whether skills of this source are only read, never delivered by OpenIDEA: the CLI
/// discovers them itself, so "off" holds only where the CLI supports a native disable.
pub fn discovered(&self) -> bool {
!matches!(self, Self::Workspace | Self::User)
}
}
/// One discovered skill: a folder with a `SKILL.md`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentSkill {
/// The frontmatter `name`, else the folder's name.
pub name: String,
pub description: String,
/// Canonical folder holding `SKILL.md` (symlinks resolved, so duplicates collapse).
pub path: IpcPath,
pub source: AgentSkillSource,
/// The `SKILL.md` passes validation (`name` matches its folder, `description` present).
pub valid: bool,
/// What validation found (`name` mismatch, missing or over-long description…).
pub warnings: Vec<String>,
}
/// A skill as Settings › Agents › Skills shows it: discovery plus the effective mode and
/// which layer decided it.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentSkillState {
pub skill: AgentSkill,
pub mode: AgentSkillMode,
/// What set `mode`: a session override, the workspace, the user's settings, workspace
/// trust, or nothing (the default `auto`).
pub origin: AgentSkillOrigin,
}
/// Which layer decided a skill's [`AgentSkillState::mode`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentSkillOrigin {
#[default]
None,
Session,
Workspace,
User,
/// An untrusted workspace's skills and policies may only turn skills off.
Trust,
}
/// An external MCP configuration file discovered on disk (user CLI config or workspace file).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
+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);
}
}
+125 -239
View File
@@ -1010,7 +1010,6 @@ async fn commands_are_remembered_per_project_and_merged_with_skills_on_disk() {
// Another project shares the settings but not the commands.
let mgr_b = manager_at(&b, &models, Arc::new(FakeAgent::default()));
let claude = mgr_b.providers().into_iter().find(|p| p.id == "claude").unwrap();
assert_eq!(claude.config.len(), 2);
assert!(claude.commands.is_empty());
assert!(mgr_b.commands("claude", None).await.unwrap().is_empty());
let mgr_a = manager_at(&a, &models, Arc::new(FakeAgent::default()));
@@ -1197,7 +1196,6 @@ async fn a_task_runs_asks_for_permission_and_survives_a_restart() {
}
let providers = mgr.providers();
let claude = providers.iter().find(|p| p.id == "claude").unwrap();
assert_eq!(claude.config.iter().map(|o| o.id.as_str()).collect::<Vec<_>>(), ["model", "mode"]);
assert_eq!(claude.commands.len(), 1);
// A new manager (IDE restart) finds the task and resumes its session without duplicating history.
@@ -1206,7 +1204,6 @@ async fn a_task_runs_asks_for_permission_and_survives_a_restart() {
let mgr2 = manager(tmp.path(), agent2.clone());
assert_eq!(mgr2.entries(&task.id, None).unwrap().len(), 5);
assert_eq!(mgr2.task(&task.id).unwrap().state.lock().task.title, "Lexer fix");
assert_eq!(mgr2.providers().iter().find(|p| p.id == "claude").unwrap().config.len(), 2);
mgr2.prompt(&task.id, text("again"), false).await.unwrap();
tokio::time::sleep(Duration::from_millis(50)).await;
wait_for(&mgr2, &task.id, AgentStatus::Ready).await;
@@ -2167,52 +2164,6 @@ async fn usage_limits_and_late_settings() {
assert!(agent.calls.lock().iter().any(|c| c == "session/set_config_option \"high\""));
let config = mgr.task(&task.id).unwrap().state.lock().task.config.clone();
assert_eq!(config.iter().find(|o| o.id == "effort").unwrap().current.as_deref(), Some("high"));
for _ in 0..100 {
if mgr
.shared
.known
.lock()
.get("claude")
.and_then(|k| k.thought_levels.get("big"))
.and_then(|levels| levels.first())
.and_then(|o| o.current.as_deref())
== Some("high")
{
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
assert_eq!(mgr.shared.known.lock()["claude"].thought_levels["big"][0].current.as_deref(), Some("high"));
}
#[tokio::test(flavor = "multi_thread")]
async fn remembered_settings_drop_per_model_choices_for_the_next_task() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
// The effort list depends on the model: what the last session ran means nothing once
// the user picks another model, so provider-wide defaults never include it.
*agent.extra_options.lock() = vec![json!({"id": "effort", "category": "thought_level",
"type": "select", "currentValue": "high",
"options": [{"value": "low", "name": "Low"}, {"value": "high", "name": "High"}]})];
let mgr = manager(tmp.path(), agent.clone());
let task = mgr
.create(NewAgentTask {
project_root: None,
prompt: text("again"),
provider: "claude".into(),
config: vec![],
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let provider = mgr.providers().into_iter().find(|p| p.id == "claude").unwrap();
assert!(provider.config.iter().all(|o| o.id != "effort"), "a per-model option isn't offered stale");
let model = provider.config.iter().find(|o| o.id == "model").unwrap();
assert_eq!(model.current.as_deref(), Some("big"), "the model choice survives");
}
fn effort_options(levels: &[&str], current: &str) -> Vec<Value> {
@@ -2220,51 +2171,6 @@ fn effort_options(levels: &[&str], current: &str) -> Vec<Value> {
"options": levels.iter().map(|v| json!({"value": v, "name": v})).collect::<Vec<_>>()})]
}
#[tokio::test(flavor = "multi_thread")]
async fn thinking_levels_are_remembered_per_provider_and_model() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
*agent.model_options.lock() = HashMap::from([
("big".into(), effort_options(&["low", "high"], "high")),
("small".into(), effort_options(&["minimal", "medium"], "minimal")),
("plain".into(), vec![]),
]);
let mgr = manager(tmp.path(), agent.clone());
let task = mgr
.create(NewAgentTask {
project_root: None,
prompt: text("again"),
provider: "claude".into(),
config: vec![],
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
mgr.set_config(&task.id, "model", "small".into()).await.unwrap();
mgr.set_config(&task.id, "effort", "medium".into()).await.unwrap();
mgr.set_config(&task.id, "model", "plain".into()).await.unwrap();
let p = mgr.providers().into_iter().find(|p| p.id == "claude").unwrap();
let big = &p.thought_levels["big"][0];
assert_eq!(big.current.as_deref(), Some("high"));
assert_eq!(big.values.iter().map(|v| v.value.as_str()).collect::<Vec<_>>(), ["low", "high"]);
let small = &p.thought_levels["small"][0];
assert_eq!(small.current.as_deref(), Some("medium"));
assert_eq!(small.values.iter().map(|v| v.value.as_str()).collect::<Vec<_>>(), ["minimal", "medium"]);
assert!(p.thought_levels["plain"].is_empty());
assert!(!p.thought_levels.contains_key("unknown"));
assert!(mgr.providers().iter().find(|p| p.id == "codex").unwrap().thought_levels.is_empty());
let saved: HashMap<String, Known> =
serde_json::from_slice(&std::fs::read(&mgr.shared.paths.models_file).unwrap()).unwrap();
assert_eq!(saved["claude"].thought_levels, p.thought_levels);
mgr.shutdown();
let restored = manager(tmp.path(), agent);
assert_eq!(restored.providers().into_iter().find(|p| p.id == "claude").unwrap().thought_levels, p.thought_levels);
restored.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn changing_an_idle_tasks_settings_keeps_its_models_effort_levels() {
// Idle selections use cached model controls or discover them before the next prompt.
@@ -2303,12 +2209,9 @@ async fn changing_an_idle_tasks_settings_keeps_its_models_effort_levels() {
}
restored.set_config(&task.id, "model", "big".into()).await.unwrap();
restored.set_config(&task.id, option, value.into()).await.unwrap();
let p = restored.providers().into_iter().find(|p| p.id == "claude-acp").unwrap();
let big = p.thought_levels.get("big").and_then(|levels| levels.first());
assert_eq!(big.map(|o| o.values.len()), Some(2), "{option}: {:?}", p.thought_levels);
let saved: HashMap<String, Known> =
serde_json::from_slice(&std::fs::read(&restored.shared.paths.models_file).unwrap()).unwrap();
assert_eq!(saved["claude-acp"].thought_levels, p.thought_levels, "{option}");
let levels = restored.shared.paths.catalogs.cached(&restored.shared, "claude-acp").thought_levels;
let big = levels.get("big").and_then(|levels| levels.first());
assert_eq!(big.map(|o| o.values.len()), Some(2), "{option}: {levels:?}");
restored.shutdown();
}
}
@@ -2541,100 +2444,6 @@ async fn upfront_effort_is_validated_after_changing_model_before_the_prompt() {
}
}
#[tokio::test(flavor = "multi_thread")]
async fn unreported_model_switch_does_not_cache_the_previous_models_levels() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
*agent.extra_options.lock() = effort_options(&["low", "high"], "high");
let mgr = manager(tmp.path(), agent);
let task = mgr
.create(NewAgentTask {
project_root: None,
prompt: text("again"),
provider: "claude".into(),
config: vec![],
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
mgr.set_config(&task.id, "model", "small".into()).await.unwrap();
let p = mgr.providers().into_iter().find(|p| p.id == "claude").unwrap();
assert!(!p.thought_levels.contains_key("small"));
assert_eq!(p.thought_levels["big"][0].current.as_deref(), Some("high"));
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn cached_effort_is_not_sent_without_real_session_options() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
*agent.extra_options.lock() = effort_options(&["low", "high"], "low");
let mgr = manager(tmp.path(), agent.clone());
let new = |config| NewAgentTask {
project_root: None,
prompt: text("again"),
provider: "claude".into(),
config,
isolation: Isolation::Local,
base: None,
..Default::default()
};
let warm = mgr.create(new(vec![])).await.unwrap();
wait_for(&mgr, &warm.id, AgentStatus::Ready).await;
agent.calls.lock().clear();
agent.empty_config.store(true, Ordering::Release);
let task = mgr
.create(new(vec![
AgentConfigChoice { id: "model".into(), value: "big".into() },
AgentConfigChoice { id: "effort".into(), value: "high".into() },
]))
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
assert!(!agent.calls.lock().iter().any(|c| c == "session/set_config_option \"high\""));
assert!(
mgr.task(&task.id).unwrap().state.lock().task.config.iter().any(|o| o.id == "effort"),
"remembered session settings remain visible until the agent refreshes them"
);
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn reported_levels_refresh_even_without_a_model_option() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
*agent.extra_options.lock() = effort_options(&["low", "high"], "high");
let mgr = manager(tmp.path(), agent.clone());
let task = mgr
.create(NewAgentTask {
project_root: None,
prompt: text("again"),
provider: "claude".into(),
config: vec![],
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
for levels in [effort_options(&["minimal", "medium"], "medium"), vec![]] {
agent.update("s1", json!({"sessionUpdate": "config_option_update", "configOptions": levels}));
let expected = config::parse_options(&json!(levels));
for _ in 0..100 {
if mgr.shared.known.lock()["claude"].thought_levels["big"] == expected {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
assert_eq!(mgr.shared.known.lock()["claude"].thought_levels["big"], expected);
}
mgr.shutdown();
}
#[test]
fn retry_updates_become_a_countdown() {
let update =
@@ -3192,49 +3001,6 @@ async fn a_failed_probe_is_retried_instead_of_remembered() {
assert!(!mgr.shared.probes.lock().contains_key("claude"));
}
/// A session report that changes the cached provider config notifies subscribers,
/// so the composer re-lists models without waiting for the next task (#1490).
/// Reports that change nothing stay silent.
#[tokio::test(flavor = "multi_thread")]
async fn remembered_config_changes_notify_subscribers_once() {
let tmp = tempfile::tempdir().unwrap();
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let events = Arc::new(Mutex::new(Vec::new()));
let sink = events.clone();
mgr.subscribe(Arc::new(move |e| sink.lock().push(e)));
events.lock().clear();
let reported = config::options_of(&json!({ "configOptions": [
{ "id": "model", "category": "model", "type": "select", "currentValue": "default",
"options": [{ "value": "default" }, { "value": "custom-opus" }] },
] }));
mgr.shared.remember("claude", Some(&reported), None, Some("default"));
assert!(
events.lock().iter().any(|ev| matches!(ev, AgentEvent::Providers)),
"a first report changing the cache notifies subscribers"
);
events.lock().clear();
// The same report again: the cache is unchanged, so subscribers hear nothing.
mgr.shared.remember("claude", Some(&reported), None, Some("default"));
assert!(events.lock().is_empty(), "an unchanged report must stay silent");
// A changed model list notifies again, and providers() serves the new list.
let updated = config::options_of(&json!({ "configOptions": [
{ "id": "model", "category": "model", "type": "select", "currentValue": "default",
"options": [{ "value": "default" }, { "value": "custom-opus" }, { "value": "custom-sonnet" }] },
] }));
mgr.shared.remember("claude", Some(&updated), None, Some("default"));
assert!(
events.lock().iter().any(|ev| matches!(ev, AgentEvent::Providers)),
"a changed model list notifies subscribers"
);
let claude = mgr.providers().into_iter().find(|p| p.id == "claude").unwrap();
let model = claude.config.iter().find(|o| o.category.as_deref() == Some("model")).unwrap();
let values: Vec<_> = model.values.iter().map(|v| v.value.as_str()).collect();
assert_eq!(values, ["default", "custom-opus", "custom-sonnet"]);
}
#[tokio::test(flavor = "multi_thread")]
async fn idle_agents_stop_and_resume_their_session_on_the_next_message() {
let new = || NewAgentTask {
@@ -3868,6 +3634,123 @@ async fn turn_changed(mgr: &AgentManager, id: &str) -> Vec<(String, ide_vcs::Cha
changes.into_iter().map(|c| (c.rel_path, c.kind, c.added, c.removed)).collect()
}
#[tokio::test(flavor = "multi_thread")]
async fn a_task_lists_what_it_changed_in_a_nested_repository() {
let tmp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(tmp.path()).unwrap();
let root = base.join("project");
for repo in [root.clone(), root.join("libs/validation")] {
std::fs::create_dir_all(&repo).unwrap();
std::fs::write(repo.join("a.txt"), "one\n").unwrap();
for args in [&["init", "-q", "-b", "main"][..], &["add", "a.txt"], &["commit", "-q", "-m", "init"]] {
let ok = std::process::Command::new("git")
.args(["-c", "user.name=t", "-c", "user.email=t@t", "-c", "commit.gpgsign=false"])
.args(args)
.current_dir(&repo)
.status()
.unwrap()
.success();
assert!(ok, "{args:?}");
}
}
let mgr = manager(&base.join("ide"), Arc::new(FakeAgent::default()));
let task = mgr
.create(NewAgentTask {
project_root: Some(IpcPath(root.clone())),
prompt: text("Hello"),
provider: "claude".into(),
isolation: Isolation::Local,
..Default::default()
})
.await
.unwrap();
one_turn(&mgr, &task.id, None, || {
std::fs::write(root.join("a.txt"), "two\n").unwrap();
std::fs::write(root.join("libs/validation/b.txt"), "new\n").unwrap();
})
.await;
let changed: Vec<(String, Option<IpcPath>)> =
mgr.changes(&task.id).await.unwrap().into_iter().map(|c| (c.rel_path, c.repo)).collect();
assert_eq!(
changed,
[
("a.txt".to_owned(), Some(IpcPath(root.clone()))),
("libs/validation/b.txt".to_owned(), Some(IpcPath(root.join("libs/validation")))),
]
);
mgr.rollback_changes(&task.id, None, AgentChangesView::SinceStart).await.unwrap();
assert_eq!(std::fs::read_to_string(root.join("a.txt")).unwrap(), "one\n");
assert!(!root.join("libs/validation/b.txt").exists());
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn the_last_turn_of_a_task_spans_nested_repositories() {
use ide_vcs::ChangeKind::{Added, Modified};
let tmp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(tmp.path()).unwrap();
let root = base.join("project");
let nested = root.join("libs/validation");
let git = |repo: &Path, args: &[&str]| {
let ok = std::process::Command::new("git")
.args(["-c", "user.name=t", "-c", "user.email=t@t", "-c", "commit.gpgsign=false"])
.args(args)
.current_dir(repo)
.status()
.unwrap()
.success();
assert!(ok, "{args:?}");
};
for repo in [&root, &nested] {
std::fs::create_dir_all(repo).unwrap();
std::fs::write(repo.join("a.txt"), "one\n").unwrap();
git(repo, &["init", "-q", "-b", "main"]);
git(repo, &["add", "a.txt"]);
git(repo, &["commit", "-q", "-m", "init"]);
}
let mgr = manager(&base.join("ide"), Arc::new(FakeAgent::default()));
let task = mgr
.create(NewAgentTask {
project_root: Some(IpcPath(root.clone())),
prompt: text("Hello"),
provider: "claude".into(),
isolation: Isolation::Local,
..Default::default()
})
.await
.unwrap();
one_turn(&mgr, &task.id, None, || std::fs::write(root.join("a.txt"), "two\n").unwrap()).await;
one_turn(&mgr, &task.id, Some("more"), || {
std::fs::write(nested.join("a.txt"), "two\n").unwrap();
std::fs::write(nested.join("b.txt"), "new\n").unwrap();
// Committed in the nested repository: still the turn's.
std::fs::write(nested.join("c.txt"), "committed\n").unwrap();
git(&nested, &["add", "c.txt"]);
git(&nested, &["commit", "-q", "-m", "c"]);
})
.await;
// Only the second turn's files, from the nested repository, named from the project.
assert_eq!(
turn_changed(&mgr, &task.id).await,
[
("libs/validation/a.txt".into(), Modified, 1, 1),
("libs/validation/b.txt".into(), Added, 1, 0),
("libs/validation/c.txt".into(), Added, 1, 0),
]
);
let repos: Vec<_> = mgr.turn_changes(&task.id).await.unwrap().into_iter().map(|c| c.repo).collect();
assert_eq!(repos, [Some(IpcPath(nested.clone())), Some(IpcPath(nested.clone())), Some(IpcPath(nested.clone()))]);
let then = mgr.base_text(&task.id, nested.join("a.txt"), AgentChangesView::LastTurn).await.unwrap();
assert_eq!(then.as_deref(), Some("one\n"));
mgr.rollback_changes(&task.id, None, AgentChangesView::LastTurn).await.unwrap();
assert_eq!(std::fs::read_to_string(nested.join("a.txt")).unwrap(), "one\n");
assert!(!nested.join("b.txt").exists());
assert_eq!(std::fs::read_to_string(root.join("a.txt")).unwrap(), "two\n", "the first turn's change stays");
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn the_last_turn_lists_and_rolls_back_only_its_own_changes() {
use ide_vcs::ChangeKind::{Added, Deleted, Modified};
@@ -4532,6 +4415,7 @@ async fn per_session_mcp_overrides_filter_session_and_reload_when_idle() {
base: None,
mcp_overrides: BTreeMap::from([("slack".into(), false)]),
idle: false,
skill_overrides: BTreeMap::new(),
})
.await
.unwrap();
@@ -4660,6 +4544,7 @@ async fn copilot_falls_back_to_acp_when_headless_probe_session_or_prompt_fails()
base: None,
mcp_overrides: BTreeMap::new(),
idle: false,
skill_overrides: BTreeMap::new(),
})
.await
.unwrap();
@@ -4685,6 +4570,7 @@ async fn copilot_falls_back_to_acp_when_headless_probe_session_or_prompt_fails()
base: None,
mcp_overrides: BTreeMap::new(),
idle: false,
skill_overrides: BTreeMap::new(),
})
.await
.unwrap();
@@ -4763,10 +4649,10 @@ done
#[test]
fn session_params_name_the_servers_off() {
let mcp = McpForSession { servers: vec![json!({ "name": "docs" })], off: vec!["github".into()] };
let params = session_params("/p", &mcp);
let params = session_params("/p", &mcp, None);
assert_eq!(params["cwd"], "/p");
assert_eq!(params["mcpServers"][0]["name"], "docs");
assert_eq!(params["_meta"]["openidea"]["mcpServersOff"], json!(["github"]));
let none = McpForSession { servers: Vec::new(), off: Vec::new() };
assert!(session_params("/p", &none).get("_meta").is_none());
assert!(session_params("/p", &none, None).get("_meta").is_none());
}
+238 -30
View File
@@ -25,6 +25,98 @@ fn discover(path: &Path) -> IdeResult<Option<Repo>> {
Ok(repo)
}
/// The repositories of a project with nested ones (an own `.git` under the project root, not a
/// submodule), with the folder their files are named from: the root of the repository holding
/// `cwd`, else `cwd`. `None` when only the repository holding `cwd` (if any) is there.
fn nested_repos(cwd: &Path) -> IdeResult<Option<(PathBuf, Vec<Repo>)>> {
let Ok(cwd) = dunce::canonicalize(cwd) else { return Ok(None) };
let found = ide_vcs::Repos::discover(&cwd, &|_| false)?;
if found.all().iter().all(|r| cwd.starts_with(r.root())) {
return Ok(None);
}
let base = found.all().iter().map(|r| r.root()).filter(|r| cwd.starts_with(r)).max().unwrap_or(&cwd).to_path_buf();
let mut repos = Vec::new();
for r in found.all() {
repos.extend(discover(r.root())?);
}
Ok(Some((base, repos)))
}
/// Whether the project at `cwd` holds repositories nested in it: its changes are each one's.
pub(crate) fn spans_repos(cwd: &Path) -> bool {
nested_repos(cwd).is_ok_and(|r| r.is_some())
}
/// The repositories a turn's files are in, and the folder those files are named from.
struct TurnRepos {
base: PathBuf,
repos: Vec<Repo>,
/// The project holds nested repositories: each one's `HEAD` is recorded on its own.
nested: bool,
}
impl TurnRepos {
fn of(cwd: &Path) -> IdeResult<Option<Self>> {
if let Some((base, repos)) = nested_repos(cwd)? {
return Ok(Some(Self { base, repos, nested: true }));
}
Ok(discover(cwd)?.map(|repo| Self { base: repo.root().to_path_buf(), repos: vec![repo], nested: false }))
}
/// The innermost repository holding `path`.
fn owner(&self, path: &Path) -> Option<&Repo> {
self.repos.iter().filter(|r| path.starts_with(r.root())).max_by_key(|r| r.root().as_os_str().len())
}
/// `repo`'s `HEAD` as the turn `start` began.
fn head_then<'a>(&self, start: &'a TurnStart, repo: &Repo) -> Option<&'a str> {
if self.nested { start.heads.get(&root_key(repo.root())) } else { start.head.as_ref() }.map(String::as_str)
}
}
fn root_key(root: &Path) -> String {
root.to_string_lossy().into_owned()
}
/// `path` as a task in `base` names it, if it is not in a repository nested below `repo` (that
/// one lists it itself; to `repo` its folder is untracked).
fn nested_rel(base: &Path, repo: &Repo, roots: &[PathBuf], path: &Path) -> Option<String> {
let rel = path.strip_prefix(base).ok()?;
if path.is_dir()
|| roots.iter().any(|n| n.as_path() != repo.root() && n.starts_with(repo.root()) && path.starts_with(n))
{
return None;
}
Some(rel.to_string_lossy().replace('\\', "/"))
}
/// The uncommitted changes in every repository of the project, against each one's `HEAD`.
fn nested_changes(cwd: &Path) -> IdeResult<Vec<AgentChange>> {
let Some((base, repos)) = nested_repos(cwd)? else { return Ok(Vec::new()) };
let roots: Vec<PathBuf> = repos.iter().map(|r| r.root().to_path_buf()).collect();
let mut out: Vec<AgentChange> = Vec::new();
for repo in &repos {
let listed = match repo.head()?.1 {
Some(head) => changes(repo.root(), &head)?,
None => {
repo.status()?.into_iter().filter(|s| s.path.is_file()).map(|s| added(s.path, s.rel_path)).collect()
}
};
for mut c in listed {
let Some(rel) = nested_rel(&base, repo, &roots, &c.path.0) else { continue };
if out.iter().any(|o| o.path == c.path) {
continue;
}
c.rel_path = rel;
c.old_path = None;
c.repo = Some(IpcPath(repo.root().to_path_buf()));
out.push(c);
}
}
out.sort_by(|a, b| a.rel_path.cmp(&b.rel_path));
Ok(out)
}
fn repo_at(path: &Path) -> IdeResult<Repo> {
discover(path)?.ok_or_else(|| IdeError::unavailable(format!("{} is not in a git repository", path.display())))
}
@@ -38,6 +130,9 @@ pub(crate) fn head_of(path: &Path) -> IdeResult<(String, String)> {
/// `HEAD`'s commit in `cwd`, `None` outside a repository or before its first commit.
pub(crate) fn head_commit(cwd: &Path) -> IdeResult<Option<String>> {
if spans_repos(cwd) {
return Ok(Some("HEAD".to_owned()));
}
match discover(cwd)? {
Some(repo) => Ok(repo.head()?.1),
None => Ok(None),
@@ -127,6 +222,7 @@ pub(crate) fn changes(cwd: &Path, base: &str) -> IdeResult<Vec<AgentChange>> {
added,
removed,
old_path: f.old_path,
repo: None,
}
})
.collect();
@@ -143,6 +239,9 @@ pub(crate) fn changes(cwd: &Path, base: &str) -> IdeResult<Vec<AgentChange>> {
/// Files renamed since `rev`, by their new repository-relative path: the old path, as a deletion
/// to roll back along with the rename.
pub(crate) fn rename_sources(cwd: &Path, rev: &str) -> IdeResult<BTreeMap<String, AgentChange>> {
if spans_repos(cwd) {
return Ok(BTreeMap::new());
}
let Some(repo) = discover(cwd)? else { return Ok(BTreeMap::new()) };
let root = repo.root().to_path_buf();
Ok(repo
@@ -157,6 +256,7 @@ pub(crate) fn rename_sources(cwd: &Path, rev: &str) -> IdeResult<BTreeMap<String
added: 0,
removed: 0,
old_path: None,
repo: None,
};
Some((f.path, source))
})
@@ -165,7 +265,7 @@ pub(crate) fn rename_sources(cwd: &Path, rev: &str) -> IdeResult<BTreeMap<String
fn added(path: IpcPath, rel_path: String) -> AgentChange {
let added = std::fs::read_to_string(&*path).map_or(0, |t| t.lines().count() as u32);
AgentChange { path, rel_path, kind: ChangeKind::Added, added, removed: 0, old_path: None }
AgentChange { path, rel_path, kind: ChangeKind::Added, added, removed: 0, old_path: None, repo: None }
}
/// The commits from `base` (exclusive) to `head` (inclusive) in `cwd`, newest first, each
@@ -201,6 +301,7 @@ pub(crate) fn commits(cwd: &Path, base: &str, head: &str) -> IdeResult<Vec<Agent
added,
removed,
old_path: f.old_path,
repo: None,
}
})
.collect();
@@ -266,6 +367,9 @@ impl TaskBase {
pub(crate) fn changes(&self, before: &BTreeMap<String, Stamp>) -> IdeResult<Vec<AgentChange>> {
let (cwd, start) = match self {
Self::Worktree { cwd, base } => return Ok(without_untouched(changes(cwd, base)?, before)),
Self::Local { cwd, .. } if spans_repos(cwd) => {
return Ok(without_untouched(nested_changes(cwd)?, before));
}
Self::Local { cwd, start } => (cwd, start.as_deref()),
};
let Some(repo) = discover(cwd)? else { return Ok(Vec::new()) };
@@ -324,6 +428,9 @@ impl TaskBase {
/// reads cannot put a file in both lists.
pub(crate) fn grouped_changes(&self, before: &BTreeMap<String, Stamp>) -> IdeResult<AgentChanges> {
let cwd = self.cwd();
if spans_repos(cwd) {
return Ok(AgentChanges { uncommitted: self.changes(before)?, commits: Vec::new() });
}
let Some(repo) = discover(cwd)? else { return Ok(AgentChanges::default()) };
let head = repo.head()?.1;
let uncommitted = match &head {
@@ -353,6 +460,8 @@ impl TaskBase {
pub(crate) fn rev(&self) -> IdeResult<Option<String>> {
let (cwd, start) = match self {
Self::Worktree { base, .. } => return Ok(Some(base.clone())),
// Each repository goes back to its own `HEAD`.
Self::Local { cwd, .. } if spans_repos(cwd) => return Ok(Some("HEAD".to_owned())),
Self::Local { cwd, start } => (cwd, start.as_deref()),
};
let Some(repo) = discover(cwd)? else { return Ok(None) };
@@ -545,6 +654,18 @@ pub(crate) fn stamp(path: &Path) -> Stamp {
pub(crate) fn snapshot(cwd: &Path) -> IdeResult<BTreeMap<String, Stamp>> {
// Paths and stamps only: no diff and no line counts, which read every untracked file
// and held up starting a task in a checkout with many of them.
if let Some((base, repos)) = nested_repos(cwd)? {
let roots: Vec<PathBuf> = repos.iter().map(|r| r.root().to_path_buf()).collect();
let mut out = BTreeMap::new();
for repo in &repos {
for s in repo.status()? {
if let Some(rel) = nested_rel(&base, repo, &roots, &s.path) {
out.insert(rel, stamp(&s.path));
}
}
}
return Ok(out);
}
let Some(repo) = Repo::discover(cwd)? else { return Ok(BTreeMap::new()) };
Ok(repo.status()?.into_iter().map(|s| (s.rel_path, stamp(&s.path))).collect())
}
@@ -587,10 +708,16 @@ fn saved_name(rel: &str) -> String {
/// into `dir`, so rolling back the task's changes to them restores the user's own edits.
/// Whether anything was saved.
pub(crate) fn save_before(cwd: &Path, before: &BTreeMap<String, Stamp>, dir: &Path) -> IdeResult<bool> {
let Some(repo) = Repo::discover(cwd)? else { return Ok(false) };
let root = match nested_repos(cwd)? {
Some((base, _)) => base,
None => match Repo::discover(cwd)? {
Some(repo) => repo.root().to_path_buf(),
None => return Ok(false),
},
};
let mut saved = false;
for (rel, stamp) in before {
let path = repo.root().join(rel);
let path = root.join(rel);
if stamp.is_none() || !std::fs::metadata(&path).is_ok_and(|m| m.is_file() && m.len() <= SAVED_MAX) {
continue;
}
@@ -625,7 +752,8 @@ pub(crate) fn restore(
}
None => match rev {
Some(rev) => {
let repo = Repo::discover(cwd)?.ok_or_else(|| IdeError::invalid("not in a git repository"))?;
let at = change.repo.as_ref().map_or(cwd, |r| r.0.as_path());
let repo = Repo::discover(at)?.ok_or_else(|| IdeError::invalid("not in a git repository"))?;
repo.file_bytes_at(&change.path.0, Some(rev))?
}
None => None,
@@ -665,6 +793,9 @@ pub(crate) struct TurnStart {
/// `HEAD` then (`None` outside a repository or before its first commit).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub head: Option<String>,
/// With nested repositories, each one's `HEAD` then, by its root.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub heads: BTreeMap<String, String>,
/// The files already changed then, stamped.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub before: BTreeMap<String, Stamp>,
@@ -680,8 +811,16 @@ pub(crate) struct TurnStart {
/// The copies `previous` saved of files unchanged since are kept rather than made again, so
/// starting a turn copies little more than what the turn before it changed.
pub(crate) fn start_turn(cwd: &Path, dir: &Path, previous: Option<&TurnStart>) -> IdeResult<TurnStart> {
let Some(repo) = discover(cwd)? else { return Ok(TurnStart::default()) };
let head = repo.head()?.1;
let Some(at) = TurnRepos::of(cwd)? else { return Ok(TurnStart::default()) };
let mut heads = BTreeMap::new();
let head = if at.nested {
for repo in &at.repos {
heads.extend(repo.head()?.1.map(|h| (root_key(repo.root()), h)));
}
None
} else {
at.repos[0].head()?.1
};
// As the turn's end is read, so the two compare.
let before = snapshot(cwd)?;
let mut saved = BTreeSet::new();
@@ -702,7 +841,7 @@ pub(crate) fn start_turn(cwd: &Path, dir: &Path, previous: Option<&TurnStart>) -
}
}
for (rel, stamp) in &before {
let path = repo.root().join(rel);
let path = at.base.join(rel);
if stamp.is_none()
|| saved.contains(rel)
|| !std::fs::metadata(&path).is_ok_and(|m| m.is_file() && m.len() <= SAVED_MAX)
@@ -715,7 +854,7 @@ pub(crate) fn start_turn(cwd: &Path, dir: &Path, previous: Option<&TurnStart>) -
saved.insert(rel.clone());
}
}
Ok(TurnStart { head, before, saved, changed: None })
Ok(TurnStart { head, heads, before, saved, changed: None })
}
/// The files that changed in `cwd` since the turn `start` began: in the working tree (as
@@ -724,20 +863,25 @@ pub(crate) fn changed_in_turn(cwd: &Path, start: &TurnStart) -> IdeResult<(Vec<S
let end = snapshot(cwd)?;
let worktree = changed_between(&start.before, &end);
let mut all: BTreeSet<String> = worktree.iter().cloned().collect();
if let Some(repo) = discover(cwd)?
&& let (Some(from), Some(to)) = (&start.head, repo.head()?.1)
&& *from != to
{
let Some(at) = TurnRepos::of(cwd)? else { return Ok((worktree, all)) };
for repo in &at.repos {
let (Some(from), Some(to)) = (at.head_then(start, repo), repo.head()?.1) else { continue };
if from == to {
continue;
}
// Named from the base, as the working tree's files are.
let prefix = rel_in(&at.base, repo.root())?;
let named = |rel: String| if prefix.is_empty() { rel } else { format!("{prefix}/{rel}") };
for f in repo.diff_revisions(from, &to)? {
all.extend(f.old_path);
all.insert(f.path);
all.extend(f.old_path.map(named));
all.insert(named(f.path));
}
}
Ok((worktree, all))
}
/// The content of `rel` as the turn `start` began (`None`: no file), its copies in `dir`.
fn at_turn_start(repo: &Repo, rel: &str, start: &TurnStart, dir: &Path) -> IdeResult<Option<Vec<u8>>> {
fn at_turn_start(at: &TurnRepos, rel: &str, start: &TurnStart, dir: &Path) -> IdeResult<Option<Vec<u8>>> {
match start.before.get(rel) {
Some(None) => Ok(None),
Some(Some(_)) => match start.saved.contains(rel).then(|| saved_copy(dir, rel)).flatten() {
@@ -746,10 +890,13 @@ fn at_turn_start(repo: &Repo, rel: &str, start: &TurnStart, dir: &Path) -> IdeRe
"{rel} had changes when the turn started that weren't saved; roll it back in Git instead"
))),
},
None => match &start.head {
Some(head) => repo.file_bytes_at(&repo.root().join(rel), Some(head)),
None => Ok(None),
},
None => {
let path = at.base.join(rel);
match at.owner(&path).and_then(|repo| Some((repo, at.head_then(start, repo)?))) {
Some((repo, head)) => repo.file_bytes_at(&path, Some(head)),
None => Ok(None),
}
}
}
}
@@ -771,13 +918,13 @@ pub(crate) fn turn_changes(
dir: &Path,
changed: &BTreeSet<String>,
) -> IdeResult<Vec<AgentChange>> {
let Some(repo) = discover(cwd)? else { return Ok(Vec::new()) };
let Some(at) = TurnRepos::of(cwd)? else { return Ok(Vec::new()) };
let mut out = Vec::new();
for rel in changed {
let path = repo.root().join(rel);
let path = at.base.join(rel);
// A folder (a submodule, say) or a file that can't be read has nothing to compare.
let Some(now) = existing(&path) else { continue };
let (kind, (added, removed)) = match at_turn_start(&repo, rel, start, dir) {
let (kind, (added, removed)) = match at_turn_start(&at, rel, start, dir) {
Ok(then) if then == now => continue,
Ok(then) => {
let kind = match (&then, &now) {
@@ -790,19 +937,29 @@ pub(crate) fn turn_changes(
// Its start wasn't saved: listed, without counts.
Err(_) => (ChangeKind::Modified, (0, 0)),
};
out.push(AgentChange { path: IpcPath(path), rel_path: rel.clone(), kind, added, removed, old_path: None });
out.push(AgentChange {
rel_path: rel.clone(),
kind,
added,
removed,
old_path: None,
repo: at.nested.then(|| at.owner(&path).map(|r| IpcPath(r.root().to_path_buf()))).flatten(),
path: IpcPath(path),
});
}
Ok(out)
}
/// The text of `path` as the turn `start` began, `None` when there was no file.
pub(crate) fn turn_text(cwd: &Path, path: &Path, start: &TurnStart, dir: &Path) -> IdeResult<Option<String>> {
let Some(repo) = discover(cwd)? else { return Ok(None) };
let rel = rel_in(repo.root(), path)?;
if let (None, Some(head)) = (start.before.get(&rel), &start.head) {
let Some(at) = TurnRepos::of(cwd)? else { return Ok(None) };
let rel = rel_in(&at.base, path)?;
if !start.before.contains_key(&rel)
&& let Some(head) = at.owner(&at.base.join(&rel)).and_then(|repo| at.head_then(start, repo))
{
return file_at(cwd, path, head);
}
let Some(bytes) = at_turn_start(&repo, &rel, start, dir)? else { return Ok(None) };
let Some(bytes) = at_turn_start(&at, &rel, start, dir)? else { return Ok(None) };
let encoding = match ide_vfs::load_text(path) {
Ok(loaded) => encoding_rs::Encoding::for_label(loaded.encoding.as_bytes()).unwrap_or(encoding_rs::UTF_8),
Err(_) => ide_vfs::detect_encoding(&bytes, None),
@@ -828,12 +985,15 @@ fn rel_in(root: &Path, path: &Path) -> IdeResult<String> {
/// Puts `change` back as it was when the turn `start` began.
pub(crate) fn restore_turn(cwd: &Path, start: &TurnStart, dir: &Path, change: &AgentChange) -> IdeResult<()> {
let repo = repo_at(cwd)?;
put(&change.path.0, at_turn_start(&repo, &change.rel_path, start, dir)?)
let at = TurnRepos::of(cwd)?
.ok_or_else(|| IdeError::unavailable(format!("{} is not in a git repository", cwd.display())))?;
put(&change.path.0, at_turn_start(&at, &change.rel_path, start, dir)?)
}
pub(crate) fn file_at(cwd: &Path, path: &Path, rev: &str) -> IdeResult<Option<String>> {
let Some(repo) = discover(cwd)? else { return Ok(None) };
// With nested repositories, the file's own one.
let at = if spans_repos(cwd) { path.parent().unwrap_or(cwd) } else { cwd };
let Some(repo) = discover(at)? else { return Ok(None) };
let encoding = match ide_vfs::load_text(path) {
Ok(loaded) => encoding_rs::Encoding::for_label(loaded.encoding.as_bytes()).unwrap_or(encoding_rs::UTF_8),
Err(_) => ide_vfs::detect_encoding(&repo.file_bytes_at(path, Some(rev))?.unwrap_or_default(), None),
@@ -962,6 +1122,54 @@ mod tests {
assert!(ok, "git {args:?}");
}
#[test]
fn a_project_with_nested_repositories_sees_changes_in_each_one() {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap();
let (nested, deeper) = (root.join("libs/validation"), root.join("libs/validation/pkg/sdk"));
for repo in [&root, &nested, &deeper] {
std::fs::create_dir_all(repo).unwrap();
git(repo, &["init", "-q", "-b", "main"]);
std::fs::write(repo.join("a.txt"), "one\n").unwrap();
git(repo, &["add", "a.txt"]);
git(repo, &["commit", "-q", "-m", "init"]);
}
assert!(spans_repos(&root));
std::fs::write(root.join("mine.txt"), "the user's\n").unwrap();
let before = snapshot(&root).unwrap();
assert_eq!(before.keys().collect::<Vec<_>>(), ["mine.txt"]);
std::fs::write(root.join("a.txt"), "two\n").unwrap();
std::fs::write(nested.join("a.txt"), "two\n").unwrap();
std::fs::write(nested.join("b.txt"), "new\n").unwrap();
std::fs::write(deeper.join("a.txt"), "two\n").unwrap();
let at = TaskBase::Local { cwd: root.clone(), start: None };
let changed = at.changes(&before).unwrap();
let listed: Vec<(&str, &Path)> =
changed.iter().map(|c| (c.rel_path.as_str(), c.repo.as_ref().unwrap().0.as_path())).collect();
assert_eq!(
listed,
[
("a.txt", root.as_path()),
("libs/validation/a.txt", nested.as_path()),
("libs/validation/b.txt", nested.as_path()),
("libs/validation/pkg/sdk/a.txt", deeper.as_path()),
]
);
assert_eq!(at.grouped_changes(&before).unwrap().uncommitted.len(), 4);
assert_eq!(file_at(&root, &nested.join("a.txt"), "HEAD").unwrap().as_deref(), Some("one\n"));
let rev = at.rev().unwrap();
for change in &changed {
restore(&root, rev.as_deref(), change, &before, None).unwrap();
}
for repo in [&root, &nested, &deeper] {
assert_eq!(std::fs::read_to_string(repo.join("a.txt")).unwrap(), "one\n");
}
assert!(!nested.join("b.txt").exists());
assert!(root.join("mine.txt").exists(), "the user's own change stays");
}
#[test]
fn worktree_changes_are_listed_against_the_base() {
let tmp = tempfile::tempdir().unwrap();
+2
View File
@@ -102,6 +102,8 @@ pub enum IdeEvent {
WorkspaceEditApplied {
id: u32,
paths: Vec<crate::IpcPath>,
/// Files the edit renamed, as the edit named them: editors open on them follow.
moves: Vec<crate::FileMove>,
/// Made by an agent through the MCP server's tools: undoable like a refactoring, but
/// not announced as one.
by_agent: bool,
+34
View File
@@ -130,6 +130,11 @@ pub struct AgentSettings {
#[serde(deserialize_with = "or_default")]
#[specta(type = BTreeMap<String, AgentMcpServer>)]
pub mcp_servers: BTreeMap<String, AgentMcpServer>,
/// How agent skills may run, keyed by skill name (`[agents.skills.<name>]`); `SKILL.md`
/// files on disk are never modified.
#[serde(deserialize_with = "or_default")]
#[specta(type = BTreeMap<String, AgentSkillPolicy>)]
pub skills: BTreeMap<String, AgentSkillPolicy>,
}
impl Default for AgentSettings {
@@ -150,6 +155,7 @@ impl Default for AgentSettings {
new_task_approvals: NewTaskApprovals::Bypass,
defaults: BTreeMap::new(),
mcp_servers: BTreeMap::new(),
skills: BTreeMap::new(),
}
}
}
@@ -205,6 +211,34 @@ impl Default for AgentMcpServer {
}
}
/// How an agent skill may run (`[agents.skills.<name>] mode = …`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentSkillMode {
/// The model decides when to use it.
#[default]
Auto,
/// Only when the user invokes it with `/name`.
SlashOnly,
/// Never.
Off,
}
/// A skill's policy in Settings › Agents › Skills, stored without touching its `SKILL.md`.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct AgentSkillPolicy {
#[serde(deserialize_with = "or_default")]
#[specta(type = AgentSkillMode)]
pub mode: AgentSkillMode,
}
impl Default for AgentSkillPolicy {
fn default() -> Self {
Self { mode: AgentSkillMode::Auto }
}
}
/// A hand-edited value these settings don't know reads as the default, rather than
/// failing the whole settings file.
fn or_default<'de, D, T>(d: D) -> Result<T, D::Error>
+19
View File
@@ -110,6 +110,17 @@ pub struct WorkspaceEditPrecondition {
}
impl WorkspaceEdit {
/// The files and folders the edit renames, in order.
pub fn moves(&self) -> Vec<FileMove> {
self.files
.iter()
.filter_map(|f| match f {
FileEdit::Rename { from, to } => Some(FileMove { from: from.clone(), to: to.clone() }),
_ => None,
})
.collect()
}
/// Coalesces aliases of the same file before applying edits against its original text.
/// Resource operations separate batches because later edits may use the new contents.
pub fn deduplicate(&mut self) {
@@ -184,6 +195,14 @@ pub enum FileEdit {
},
}
/// One file or folder move.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct FileMove {
pub from: crate::IpcPath,
pub to: crate::IpcPath,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum Severity {
+2
View File
@@ -151,6 +151,7 @@ pub struct CommitSettings {
/// Commit from the Commit tool window; off = Local Changes in the Git tool
/// window and a Commit dialog.
pub non_modal: bool,
pub include_changes_by_default: bool,
/// Start with an empty message instead of the last one / the changelist's.
pub clear_initial_message: bool,
pub analyze_code: bool,
@@ -190,6 +191,7 @@ impl Default for CommitSettings {
fn default() -> Self {
Self {
non_modal: true,
include_changes_by_default: true,
clear_initial_message: false,
analyze_code: true,
check_todo: true,
+2 -2
View File
@@ -72,7 +72,7 @@ pub struct Host {
/// Projects the MCP server serves without a window.
pub mcp_background: mcp::BackgroundProjects,
pub(crate) agent_catalogs: Arc<ide_agent::AgentCatalogs>,
pub trust: trust::TrustStore,
pub trust: std::sync::Arc<trust::TrustStore>,
pub(crate) mcp_approvals: Arc<trust::McpServerApprovals>,
pub config_dir: PathBuf,
/// Persistent user state, including credentials and recovery history.
@@ -169,7 +169,7 @@ impl Host {
mcp_agent_runs: Default::default(),
mcp_background: Default::default(),
agent_catalogs: Arc::default(),
trust: trust::TrustStore::load(&config_dir, &data_dir),
trust: std::sync::Arc::new(trust::TrustStore::load(&config_dir, &data_dir)),
mcp_approvals: Arc::new(trust::McpServerApprovals::load(&data_dir)),
proxy_password: ide_ssh::secrets::SecretFile::new(data_dir.join("proxy-password.json")),
proxy_session_password: Mutex::default(),
+7 -3
View File
@@ -668,8 +668,8 @@ async fn text_search(call: Call, is_regex: bool) -> IdeResult<Output> {
if hits.len() > limit {
break;
}
// Find in Files keeps a window of very long lines and drops the matches outside it:
// such lines are matched again in the file's whole text.
// Find in Files reports a very long line in windows cut around its matches: such lines
// are matched again in the file's whole text, so a match keeps its real end.
let long = |m: &ide_search::LineMatch| m.text_offset > 0 || m.text.encode_utf16().count() + 1 >= LINE_WINDOW;
let whole = if file.matches.iter().any(long) {
crate::ops::fs::fs_read_text(&host, call.window(), file.path.0.clone())
@@ -679,11 +679,15 @@ async fn text_search(call: Call, is_regex: bool) -> IdeResult<Output> {
} else {
None
};
// One window per far-apart match: a line is expanded once.
let mut expanded = std::collections::HashSet::new();
for m in &file.matches {
if let Some((ranges, text)) = &whole
&& long(m)
{
hits.extend(line_hits(path, text, ranges, m.line));
if expanded.insert(m.line) {
hits.extend(line_hits(path, text, ranges, m.line));
}
continue;
}
let line_end = m.text_offset + m.text.encode_utf16().count() as u32;
+148 -2
View File
@@ -7,8 +7,9 @@ use ide_agent::registry::{AgentRegistry, RegistryPaths};
use ide_agent::{
AcpImportOutcome, AgentAcceptOutcome, AgentChange, AgentChanges, AgentChangesView, AgentCliOffer,
AgentCliUpdateResult, AgentCommand, AgentContextUsage, AgentEntry, AgentEvent, AgentModelCatalog, AgentProbe,
AgentPrompt, AgentProvider, AgentQueued, AgentTask, CustomAgentInput, ExternalSession, McpExternalSource,
McpImportSelection, McpProbeResult, McpScope, McpServer, McpServerInput, McpTransport, NewAgentTask,
AgentPrompt, AgentProvider, AgentQueued, AgentSkillMode, AgentSkillPolicy, AgentSkillState, AgentTask,
CustomAgentInput, ExternalSession, McpExternalSource, McpImportSelection, McpProbeResult, McpScope, McpServer,
McpServerInput, McpTransport, NewAgentTask, SkillsPolicy,
};
use ide_command::command;
use ide_core::error::ErrorKind;
@@ -1028,6 +1029,148 @@ pub fn agent_set_mcp_overrides(
host.project(window)?.agents.set_mcp_overrides(&task, overrides)
}
/// Updates per-session skill modes on `task`.
#[command(trust = always)]
pub fn agent_set_skill_overrides(
host: &Host,
window: &str,
task: String,
overrides: std::collections::BTreeMap<String, AgentSkillMode>,
) -> IdeResult<AgentTask> {
host.project(window)?.agents.set_skill_overrides(&task, overrides)
}
/// Every skill discovered in the project and the user's folders, with the mode a session
/// of this project runs it with (without any session's own overrides).
#[command(trust = always)]
pub async fn agent_skills_list(host: &Host, window: &str) -> IdeResult<Vec<AgentSkillState>> {
let project = host.project(window)?;
let root = project.root.clone();
let (policy, home) = (skills_policy(&project), dirs::home_dir());
tokio::task::spawn_blocking(move || {
Ok(ide_agent::skills::resolve(
ide_agent::skills::discover_skills(&root, home.as_deref()),
None,
&policy.workspace,
&policy.user,
policy.workspace_trusted,
))
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?
}
/// Sets how `name` may run in `scope`, in the settings file of that scope, and returns the
/// updated list. `SKILL.md` files are never touched; the default `auto` removes the entry.
#[command(trust = always)]
pub fn agent_skills_set_mode(
host: &Host,
window: &str,
name: String,
scope: McpScope,
mode: AgentSkillMode,
) -> IdeResult<Vec<AgentSkillState>> {
let name = name.trim().to_owned();
if name.is_empty() {
return Err(IdeError::invalid("a skill needs a name"));
}
let project = host.project(window).ok().filter(|p| !p.light);
let (mut user, mut workspace) = skills_maps(host, project.as_ref());
match scope {
McpScope::User => {
let changed = if mode == AgentSkillMode::Auto {
user.remove(&name).is_some()
} else {
user.insert(name, AgentSkillPolicy { mode }).map(|p| p.mode) != Some(mode)
};
if changed {
persist_skills_map(host, None, scope, &user)?;
}
}
McpScope::Workspace => {
let map =
workspace.as_mut().ok_or_else(|| IdeError::invalid("Open a project to configure workspace skills"))?;
let changed = if mode == AgentSkillMode::Auto {
map.remove(&name).is_some()
} else {
map.insert(name, AgentSkillPolicy { mode }).map(|p| p.mode) != Some(mode)
};
if changed {
let map = map.clone();
persist_skills_map(host, project.as_ref(), scope, &map)?;
}
}
}
match project {
Some(project) => {
let root = project.root.clone();
let policy = skills_policy(&project);
let home = dirs::home_dir();
Ok(ide_agent::skills::resolve(
ide_agent::skills::discover_skills(&root, home.as_deref()),
None,
&policy.workspace,
&policy.user,
policy.workspace_trusted,
))
}
None => Ok(Vec::new()),
}
}
/// The user's and the workspace's skill policies (`[agents.skills.<name>]`).
fn skills_maps(
host: &Host,
project: Option<&std::sync::Arc<crate::Project>>,
) -> (std::collections::BTreeMap<String, AgentSkillPolicy>, Option<std::collections::BTreeMap<String, AgentSkillPolicy>>)
{
let user = host.global_settings.effective().agents.skills.clone();
let workspace =
project.map(|p| p.settings.layer(ide_workspace::settings::SettingsScope::Project).agents.skills.clone());
(user, workspace)
}
/// Saves `map` into its scope's settings and tells the windows.
fn persist_skills_map(
host: &Host,
project: Option<&std::sync::Arc<crate::Project>>,
scope: McpScope,
map: &std::collections::BTreeMap<String, AgentSkillPolicy>,
) -> IdeResult<()> {
let value = if map.is_empty() {
serde_json::Value::Null
} else {
serde_json::to_value(map).map_err(|e| IdeError::invalid(e.to_string()))?
};
let event = IdeEvent::SettingsChanged { key: "agents.skills".into() };
match scope {
McpScope::User => {
host.global_settings.set(ide_workspace::settings::SettingsScope::Global, "agents.skills", value)?;
for p in host.projects() {
p.settings.reload();
p.agents.notify_mcp_servers_changed();
p.sink.emit(event.clone());
}
}
McpScope::Workspace => {
let p = project.ok_or_else(|| IdeError::invalid("Open a project to configure workspace skills"))?;
p.settings.set(ide_workspace::settings::SettingsScope::Project, "agents.skills", value)?;
p.agents.notify_mcp_servers_changed();
p.sink.emit(event);
}
}
Ok(())
}
/// The skill policies a session of `project` resolves against.
fn skills_policy(project: &crate::Project) -> SkillsPolicy {
SkillsPolicy {
user: project.settings.layer(ide_workspace::settings::SettingsScope::Global).agents.skills.clone(),
workspace: project.settings.layer(ide_workspace::settings::SettingsScope::Project).agents.skills.clone(),
workspace_trusted: project.trusted.load(std::sync::atomic::Ordering::Acquire),
}
}
fn validate_project_root(root: &std::path::Path, requested: Option<&std::path::Path>) -> IdeResult<std::path::PathBuf> {
let Some(requested) = requested else {
return Ok(root.to_path_buf());
@@ -1183,6 +1326,9 @@ ide_command::domain!(
agent_set_config,
agent_set_env,
agent_set_mcp_overrides,
agent_set_skill_overrides,
agent_skills_list,
agent_skills_set_mode,
agent_stop_background,
agent_subscribe,
agent_unarchive,
+6 -3
View File
@@ -85,7 +85,7 @@ pub async fn doc_set_line_ending(host: &Host, window: &str, doc: DocId, line_end
}
/// Structure view: LSP document symbols when available (with tree-sitter
/// visibility), tree-sitter otherwise.
/// visibility and type-alias kinds), tree-sitter otherwise.
/// Tree-sitter answers come from the per-document tree cache (incremental
/// re-parse); large documents get no syntax structure.
#[command(trust = always)]
@@ -113,10 +113,13 @@ pub async fn doc_outline(host: &Host, window: &str, doc: DocId) -> IdeResult<Vec
};
let syntax = || project.syntax.outline(doc, &snap.language, snap.version, &snap.text);
Ok(match lsp {
// Server symbols carry no visibility; borrow it from the syntax tree.
// Server symbols carry no visibility, nor a kind for type aliases; borrow them from
// the syntax tree.
Some(mut items) => {
if !snap.large {
ide_language::merge_visibility(&mut items, &syntax());
let syntax = syntax();
ide_language::merge_visibility(&mut items, &syntax);
ide_language::merge_kinds(&mut items, &syntax);
}
items
}
+6
View File
@@ -335,6 +335,12 @@ pub fn set_settings(
project.agents.notify_mcp_servers_changed();
}
}
// A skill policy change re-resolves the modes; an idle session restarts to pick them up.
if key == "agents" || key == "agents.skills" || key.starts_with("agents.skills.") {
for project in affected() {
project.agents.notify_mcp_servers_changed();
}
}
// A new interpreter / toolchain / server executable restarts the language servers it affects.
// So do inspections that are compiler options (`ide-sdk` `configure_java_compiler`).
let code_style = key == "editor"
+12 -4
View File
@@ -22,6 +22,17 @@ pub fn literal_range(l: ide_language::Literal) -> ide_search::LiteralRange {
ide_search::LiteralRange { start: l.start, end: l.end, kind }
}
/// Comments and string literals of `text`, for the search context of Find and Replace in Files.
pub(crate) fn literals_of(
project: &crate::project::Project,
syntax: &ide_language::Syntax,
path: &Path,
text: &str,
) -> Option<Vec<ide_search::LiteralRange>> {
let language = project.languages.detect(path, text.lines().next());
Some(syntax.literals(&language, text)?.into_iter().map(literal_range).collect())
}
/// Find in Files. Results stream through `on_event`; ends with `Done`.
/// Cancel with `cancel_request(request)`.
#[command(trust = always)]
@@ -98,10 +109,7 @@ pub(crate) fn search_project(
Some(ProjectFileSet::Test) => roots.is_test(rel),
_ => true,
};
let literals = |path: &Path, text: &str| {
let language = project.languages.detect(path, text.lines().next());
Some(syntax.literals(&language, text)?.into_iter().map(literal_range).collect())
};
let literals = |path: &Path, text: &str| literals_of(project, syntax, path, text);
let defaults = project.documents.file_defaults();
let decode = |path: &Path, bytes: &[u8]| ide_vfs::decode_text(bytes, defaults.fallback_for(path));
let mut total = SearchSummary::default();
+13 -3
View File
@@ -75,9 +75,19 @@ pub async fn replace_in_files(
let summary = tokio::task::spawn_blocking(move || {
let targets = if all_in_scope { scope_targets(&project, &syntax, &query, targets, &cancel)? } else { targets };
let host = DocumentsHost(&project.documents);
ide_search::replace_files(&host, &query, &replacement, preserve_case, &targets, &cancel, &|e| {
let _ = events.send(e);
})
let literals = |path: &Path, text: &str| super::literals_of(&project, &syntax, path, text);
ide_search::replace_files_in_context(
&host,
&query,
&replacement,
preserve_case,
&targets,
Some(&literals),
&cancel,
&|e| {
let _ = events.send(e);
},
)
})
.await
.map_err(|e| ide_core::IdeError::internal(e.to_string()));
+13
View File
@@ -738,6 +738,19 @@ impl Host {
let approvals = self.mcp_approvals.clone();
let secrets = self.agent_secrets.clone();
let root = root.to_path_buf();
// The skill policies sessions resolve against: both settings layers and the
// workspace's trust as it stands when a session starts.
let skill_settings = settings.clone();
let skill_root = root.clone();
let trust = self.trust.clone();
agents.set_skills_policy_hook(Box::new(move || {
let layer = |scope| skill_settings.layer(scope).agents.skills.clone();
ide_agent::SkillsPolicy {
user: layer(ide_workspace::settings::SettingsScope::Global),
workspace: layer(ide_workspace::settings::SettingsScope::Project),
workspace_trusted: trust.trusted(&skill_root).unwrap_or(false),
}
}));
agents.set_mcp_servers_hook(Box::new(move || {
crate::ops::agent::session_mcp_servers(&settings, &approvals, &secrets, &root)
}));
+13
View File
@@ -187,6 +187,19 @@ async fn reads_unsaved_text_and_searches_the_overlay_with_a_limit() {
assert_eq!(std::fs::read_to_string(h.root.join("src/a.txt")).unwrap(), "old text\nneedle needle\n");
}
#[tokio::test(flavor = "multi_thread")]
async fn every_match_of_a_long_line_is_found_once() {
let h = Harness::new();
std::fs::write(
h.root.join("src/min.js"),
format!("a=1;{}b='longneedle';{}longneedle\n", "x".repeat(2000), "y".repeat(2000)),
)
.unwrap();
let found = h.json("search_text", json!({"q":"longneedle","limit":20})).await;
let columns: Vec<_> = found["items"].as_array().unwrap().iter().map(|i| i["startColumn"].clone()).collect();
assert_eq!(columns, [json!(2008), json!(4020)], "{found}");
}
#[tokio::test(flavor = "multi_thread")]
async fn window_reports_supply_editor_selection_and_problems_then_disappear_on_close() {
let h = Harness::new();
+53
View File
@@ -195,3 +195,56 @@ async fn replace_all_saves_open_buffers_without_unsaved_changes() {
assert_eq!(project.documents.text_snapshot(edited).unwrap().text, "DONE\nmore\n");
host.close_project("main");
}
/// Replace All past the limit replaces what the search lists: only the matches its Search
/// Context keeps (comments, string literals or code), as below the limit.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn replace_all_past_the_limit_keeps_to_the_search_context() {
use ide_search::SearchContext as C;
let comments = |word: &str| lines(2001, &format!("// {word}"));
let code = |name: &str, string: &str| format!("fn {name}() -> &'static str {{ \"{string}\" }}\n");
let original = format!("{}{}", comments("tok"), code("tok", "tok"));
let cases = [
(C::Any, format!("{}{}", comments("X"), code("X", "X"))),
(C::InComments, format!("{}{}", comments("X"), code("tok", "tok"))),
(C::InStringLiterals, format!("{}{}", comments("tok"), code("tok", "X"))),
(C::ExceptComments, format!("{}{}", comments("tok"), code("X", "X"))),
(C::ExceptStringLiterals, format!("{}{}", comments("X"), code("X", "tok"))),
(C::ExceptCommentsAndStringLiterals, format!("{}{}", comments("tok"), code("X", "tok"))),
];
for (context, expected) in cases {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
std::fs::create_dir_all(&root).unwrap();
std::fs::write(root.join("lib.rs"), &original).unwrap();
let host = Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(NullSink)),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
});
host.trust.decide(&root, true, false).unwrap();
host.open_project("main", &root).unwrap();
ops::search::replace_in_files(
&host,
"main",
RequestId::next(),
SearchQuery { context, ..query("tok", false) },
"X".into(),
false,
vec![],
true,
ops::Channel::new(|_| {}),
)
.await
.unwrap();
assert_eq!(std::fs::read_to_string(root.join("lib.rs")).unwrap(), expected, "{context:?}");
host.close_project("main");
}
}
+1 -1
View File
@@ -25,7 +25,7 @@ pub use syntax::{
CSS_CLASS, CSS_ID, CSS_VARIABLE, ClassBases, ConfigurationKey, ExternalFold, ExternalSymbol, ExternalSyntax,
ExternalToken, FileReference, Literal, LiteralKind, MAX_CACHED_TREES, MAX_PARSE_BYTES, ParsedTree, SpellingKind,
SpellingRegion, Syntax, SyntaxCache, SyntaxCacheStats, SyntaxHighlightKind, SyntaxHighlights, TreeError,
VueComponentImport, VueRefAccess, VueRefElement, WebReference, WebReferenceKind, merge_visibility,
VueComponentImport, VueRefAccess, VueRefElement, WebReference, WebReferenceKind, merge_kinds, merge_visibility,
set_external_syntax, shift_pos, shift_range,
};
pub use syntax::{MethodBody, PhpAlignment, PythonClassFacts, PythonFacts, PythonMethodFacts};
+1 -1
View File
@@ -28,7 +28,7 @@ use ide_core::{LanguageId, OutlineItem, Pos, Range};
pub use inheritance::ClassBases;
pub use lines::{shift_pos, shift_range};
pub use literals::{Literal, LiteralKind, SpellingKind, SpellingRegion};
pub use outline::merge_visibility;
pub use outline::{merge_kinds, merge_visibility};
pub use php_align::PhpAlignment;
pub use python_facts::{MethodBody, PythonClassFacts, PythonFacts, PythonMethodFacts};
use std::cell::RefCell;
+30
View File
@@ -495,6 +495,36 @@ pub fn merge_visibility(target: &mut [OutlineItem], source: &[OutlineItem]) {
}
}
/// Takes the syntax tree's kind where a server reported a declared type as a value or a type
/// parameter: LSP has no kind for type aliases, so servers fall back to one of those
/// (typescript-language-server: Variable; rust-analyzer, sourcekit-lsp: TypeParameter).
/// Matched by name and position like [`merge_visibility`].
pub fn merge_kinds(target: &mut [OutlineItem], source: &[OutlineItem]) {
fn index(items: &[OutlineItem], out: &mut HashMap<(ide_core::Pos, String), SymbolKind>) {
for i in items {
if i.kind.is_type_like() {
out.insert((i.selection_range.start, i.name.clone()), i.kind);
}
index(&i.children, out);
}
}
fn apply(items: &mut [OutlineItem], map: &HashMap<(ide_core::Pos, String), SymbolKind>) {
for i in items {
if matches!(i.kind, SymbolKind::Variable | SymbolKind::TypeParameter)
&& let Some(&kind) = map.get(&(i.selection_range.start, i.name.clone()))
{
i.kind = kind;
}
apply(&mut i.children, map);
}
}
let mut map = HashMap::new();
index(source, &mut map);
if !map.is_empty() {
apply(target, &map);
}
}
/// End of `node` without trailing whitespace (C macros and others include the newline).
fn trimmed_end(node: &Node, text: &str) -> usize {
let (s, e) = (node.start_byte(), node.end_byte());
+82
View File
@@ -1476,6 +1476,88 @@ fn merge_visibility_matches_by_name_and_position() {
assert_eq!(lsp[1].visibility, None);
}
#[test]
fn merge_kinds_names_types_a_server_reported_as_values_or_type_parameters() {
fn kinds(items: &[OutlineItem], out: &mut Vec<(String, SymbolKind)>) {
for i in items {
out.push((i.name.clone(), i.kind));
kinds(&i.children, out);
}
}
/// The syntax outline with each kind replaced as a server reports it.
fn as_server(ts: &[OutlineItem], server: &[(&str, SymbolKind)]) -> Vec<OutlineItem> {
fn set(items: &mut [OutlineItem], server: &[(&str, SymbolKind)], at: &mut usize) {
for i in items {
i.kind = server[*at].1;
assert_eq!(i.name, server[*at].0);
*at += 1;
set(&mut i.children, server, at);
}
}
let mut lsp = ts.to_vec();
set(&mut lsp, server, &mut 0);
lsp
}
fn merged(language: &str, src: &str, server: &[(&str, SymbolKind)]) -> Vec<(String, SymbolKind)> {
let ts = syntax().outline(&lang(language), src);
let mut lsp = as_server(&ts, server);
crate::merge_kinds(&mut lsp, &ts);
let mut out = Vec::new();
kinds(&lsp, &mut out);
out
}
use SymbolKind as K;
let owned = |v: &[(&str, SymbolKind)]| v.iter().map(|(n, k)| (n.to_string(), *k)).collect::<Vec<_>>();
// typescript-language-server: a type alias is a Variable; `const` is one too.
let ts = "type Cents = number;\ninterface Shape {}\nconst rate = 1;\n";
assert_eq!(
merged("typescript", ts, &[("Cents", K::Variable), ("Shape", K::Interface), ("rate", K::Variable)]),
owned(&[("Cents", K::TypeAlias), ("Shape", K::Interface), ("rate", K::Variable)]),
);
// rust-analyzer: type aliases and associated types are TypeParameters, a trait an Interface.
let rs = "pub type Meters = u32;\ntrait Measure { type Unit; }\nstruct Rope;\nimpl Measure for Rope { type Unit = Meters; }\n";
assert_eq!(
merged(
"rust",
rs,
&[
("Meters", K::TypeParameter),
("Measure", K::Interface),
("Unit", K::TypeParameter),
("Rope", K::Struct),
("impl Measure for Rope", K::Variable),
("Unit", K::TypeParameter),
],
),
owned(&[
("Meters", K::TypeAlias),
("Measure", K::Interface),
("Unit", K::TypeAlias),
("Rope", K::Struct),
("impl Measure for Rope", K::Variable),
("Unit", K::TypeAlias),
]),
);
// sourcekit-lsp: typealias and associatedtype are TypeParameters.
let swift = "typealias Meters = Int\nprotocol Measure { associatedtype Unit }\n";
assert_eq!(
merged("swift", swift, &[("Meters", K::TypeParameter), ("Measure", K::Interface), ("Unit", K::TypeParameter)]),
owned(&[("Meters", K::TypeAlias), ("Measure", K::Interface), ("Unit", K::TypeAlias)]),
);
// A type kind the server chose stays: clangd's Class for a typedef, gopls's Struct.
let c = "typedef unsigned int meters;\n";
assert_eq!(merged("c", c, &[("meters", K::Class)]), owned(&[("meters", K::Class)]));
let go = "package p\n\ntype Point struct{}\n";
assert_eq!(
merged("go", go, &[("p", K::Package), ("Point", K::Struct)]),
owned(&[("p", K::Package), ("Point", K::Struct)])
);
}
#[test]
fn spelling_regions_cover_declared_names_only() {
let src = "// note\nfn parse_input(raw_text: &str) -> Value { let mut counter = helper(raw_text); \"hi\" }\n";
+4
View File
@@ -1337,6 +1337,10 @@ pub fn configure_server(cfg: &mut LanguageServerConfig, root: &Path, server_root
cfg.args = vec!["--lsp".into(), "--stdio".into()];
cfg.display_name = Some("TypeScript 7".into());
cfg.initialization_options = None;
// Completing a JSX prop adds `=""` or `={}` by its type, as vtsls does by default;
// TypeScript 7 adds no value unless asked.
let jsx = json!({ "preferences": { "jsxAttributeCompletionStyle": "auto" } });
merge_init_options(cfg, json!({ "typescript": jsx, "javascript": jsx }));
cfg.tsserver_project = false;
return;
}
+9 -1
View File
@@ -1725,7 +1725,15 @@ fn typescript_7_runs_its_own_language_server() {
assert_eq!(Path::new(&cfg.command), native, "{name}");
assert_eq!(cfg.args, ["--lsp", "--stdio"]);
assert_eq!(cfg.display_name.as_deref(), Some("TypeScript 7"));
assert!(cfg.initialization_options.is_none());
// The tsserver-based server's options don't apply; JSX prop completion adds a value.
let options = serde_json::to_value(cfg.initialization_options.as_ref().unwrap()).unwrap();
for language in ["typescript", "javascript"] {
assert_eq!(
options[language],
serde_json::json!({ "preferences": { "jsxAttributeCompletionStyle": "auto" } })
);
}
assert_eq!(options.as_object().unwrap().len(), 2, "{options}");
}
// Picked as a directory (its `lib`, as for older versions), too.
s.languages.typescript.version = modules.join("typescript/lib").to_string_lossy().into_owned();
+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")]);
+35
View File
@@ -315,6 +315,41 @@ mod tests {
assert_eq!(skipped.all().len(), 2);
}
/// A workspace: members in repositories of their own (one with a nested repository, not a
/// submodule), a plain folder, and a member that is a subfolder of a bigger repository; the
/// container's agent folder links to each member and must not add a repository again.
#[cfg(unix)]
#[test]
fn workspace_members_bring_their_repositories_once() {
let tmp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(tmp.path()).unwrap();
let (api, web, plain, mono) = (base.join("api"), base.join("web"), base.join("plain"), base.join("mono"));
git_init(&api);
git_init(&api.join("libs/sdk"));
git_init(&web);
std::fs::create_dir_all(&plain).unwrap();
git_init(&mono);
let docs = mono.join("docs");
std::fs::create_dir_all(&docs).unwrap();
let container = base.join("ws");
let links = container.join(".openidea/agent-root");
std::fs::create_dir_all(&links).unwrap();
for (name, target) in [("api", &api), ("web", &web), ("plain", &plain), ("docs", &docs)] {
std::os::unix::fs::symlink(target, links.join(name)).unwrap();
// A link elsewhere in the container: never followed either.
std::os::unix::fs::symlink(target, container.join(name)).unwrap();
}
let roots = [container.clone(), api.clone(), web.clone(), plain.clone(), docs.clone()];
let repos = Repos::discover_roots(&roots, &|_| false).unwrap();
let found: Vec<&Path> = repos.all().iter().map(|r| r.root()).collect();
assert_eq!(found, [api.as_path(), &api.join("libs/sdk"), &mono, &web]);
let file = api.join("libs/sdk/lib.rs");
assert_eq!(repos.for_path(&file).unwrap().root(), api.join("libs/sdk"), "a nested file is its own repo's");
assert_eq!(repos.for_path(&docs.join("a.md")).unwrap().root(), mono, "a subfolder member is its repo's");
assert!(repos.for_path(&plain.join("x")).is_none());
}
#[test]
fn side_by_side_repositories_without_an_enclosing_one() {
let tmp = tempfile::tempdir().unwrap();
+31 -2
View File
@@ -235,6 +235,12 @@ fn gix_status(r: &Repo, ignored: &IgnoredNames) -> IdeResult<Entries> {
Ok((map, conflicts))
}
/// Keeps `git status` from rewriting the index with refreshed stat data. Such a write is not
/// one of ours to the watcher, so it would schedule another refresh, which runs git again (#4792).
fn read_only() -> [(&'static str, &'static std::ffi::OsStr); 1] {
[("GIT_OPTIONAL_LOCKS", std::ffi::OsStr::new("0"))]
}
/// `git status --porcelain=v2`: what git lists, unreadable directories skipped.
/// In Restricted Mode git compares content without the repository's clean/process
/// filters and doesn't ask submodules for their own status (which runs their config).
@@ -245,7 +251,7 @@ fn cli_status(r: &Repo, ignored: &IgnoredNames) -> IdeResult<Entries> {
if !crate::execution_allowed() {
args.push("--ignore-submodules=dirty");
}
let out = crate::cli::run(r.root(), &args, None)?;
let out = crate::cli::run_env(r.root(), &args, None, &read_only())?;
Ok(parse_porcelain_v2(&String::from_utf8_lossy(&out.stdout), ignored))
}
@@ -260,7 +266,7 @@ fn cli_status_paths(r: &Repo, ignored: &IgnoredNames, paths: &[String]) -> IdeRe
}
args.push("--");
args.extend(paths.iter().map(String::as_str));
let out = crate::cli::run(r.root(), &args, None)?;
let out = crate::cli::run_env(r.root(), &args, None, &read_only())?;
Ok(parse_porcelain_v2(&String::from_utf8_lossy(&out.stdout), ignored))
}
@@ -397,6 +403,29 @@ mod tests {
assert!(staged.stdout.is_empty(), "{}", String::from_utf8_lossy(&staged.stdout));
}
/// #4792: the dirty-scope `git status` must not rewrite the index after refreshing stale
/// stat data, or the watcher sees a foreign index write and refreshes again.
#[test]
fn git_status_of_paths_leaves_the_index_alone() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
git(dir, &["init", "-q"]);
git(dir, &["config", "user.name", "Test User"]);
git(dir, &["config", "user.email", "[email protected]"]);
git(dir, &["config", "commit.gpgsign", "false"]);
std::fs::write(dir.join("a.txt"), "a\n").unwrap();
commit_all(dir, "base");
// Same content, new stat data: plain `git status` would refresh and write the index.
std::thread::sleep(std::time::Duration::from_millis(1100));
std::fs::write(dir.join("a.txt"), "a\n").unwrap();
let index = dir.join(".git/index");
let before = std::fs::read(&index).unwrap();
let repo = Repo::discover(dir).unwrap().expect("repository found");
assert!(status_paths(&repo, &["a.txt".to_owned()]).unwrap().is_empty());
assert_eq!(std::fs::read(&index).unwrap(), before, "git status rewrote the index");
}
/// git's porcelain answer (used when gitoxide can't read the tree) matches gitoxide's.
#[test]
fn git_and_gitoxide_report_the_same_status() {
@@ -422,6 +422,8 @@ impl Documents {
}
// Validate project rules before path resolution can erase linked components.
crate::file_ops::validate_workspace_edit_paths(edit)?;
// Editors know the paths as the edit named them, before link resolution.
let moves = edit.moves();
let mut edit = normalize_edit(edit)?;
let captured = !edit.preconditions.is_empty();
crate::file_ops::expand_workspace_edit(&mut edit)?;
@@ -501,7 +503,7 @@ impl Documents {
});
}
history.prune(SystemTime::now(), MAX_HISTORY_BYTES, MAX_HISTORY_AGE);
self.sink.emit(IdeEvent::WorkspaceEditApplied { id, paths: affected, by_agent });
self.sink.emit(IdeEvent::WorkspaceEditApplied { id, paths: affected, moves, by_agent });
}
Ok(())
}
+1 -8
View File
@@ -4,20 +4,13 @@
use crate::documents::Documents;
use crate::history::LocalHistory;
pub use ide_core::FileMove;
use ide_core::{FileEdit, IdeError, IdeResult, WorkspaceEdit};
use parking_lot::Mutex;
use serde::{Deserialize, Serialize};
use specta::Type;
use std::path::{Path, PathBuf};
/// One file or folder move.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct FileMove {
pub from: ide_core::IpcPath,
pub to: ide_core::IpcPath,
}
/// What [`FileMoves::undo`] did.
#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
+10
View File
@@ -898,6 +898,16 @@ mod tests {
);
}
#[test]
fn commit_default_inclusion_persists() {
let tmp = tempfile::tempdir().unwrap();
let store = SettingsStore::load(tmp.path(), None);
assert!(store.effective().vcs.commit.include_changes_by_default);
let settings = store.set(SettingsScope::Global, "vcs.commit.includeChangesByDefault", json!(false)).unwrap();
assert!(!settings.vcs.commit.include_changes_by_default);
assert!(!SettingsStore::load(tmp.path(), None).effective().vcs.commit.include_changes_by_default);
}
#[test]
fn inspection_profiles_live_in_their_layers() {
let tmp = tempfile::tempdir().unwrap();
+40 -1
View File
@@ -1,4 +1,4 @@
use ide_core::{ChangeSet, FileEdit, LanguageId, NullSink, Pos, Range, TextChange, TextEdit, WorkspaceEdit};
use ide_core::{ChangeSet, FileEdit, FileMove, LanguageId, NullSink, Pos, Range, TextChange, TextEdit, WorkspaceEdit};
use ide_core::{IdeEvent, error::ErrorKind};
use ide_workspace::Documents;
use parking_lot::Mutex;
@@ -162,6 +162,45 @@ fn undo_id(events: &Mutex<Vec<IdeEvent>>) -> u32 {
.expect("successful transaction has one undo record")
}
#[test]
fn applied_event_lists_the_files_the_edit_renamed() {
for by_agent in [false, true] {
let tmp = tempfile::tempdir().unwrap();
let from = tmp.path().join("ListPrice.java");
let to = tmp.path().join("BasePrice.java");
let user = tmp.path().join("BulkDiscount.java");
std::fs::write(&from, "old").unwrap();
std::fs::write(&user, "old\n").unwrap();
let (docs, events) = recorded_documents();
let edit = WorkspaceEdit {
files: vec![edit(&user, "new"), FileEdit::Rename { from: from.clone().into(), to: to.clone().into() }],
..Default::default()
};
if by_agent { docs.apply_agent_workspace_edit(&edit) } else { docs.apply_workspace_edit(&edit) }.unwrap();
let moves = events
.lock()
.iter()
.find_map(|event| match event {
IdeEvent::WorkspaceEditApplied { moves, .. } => Some(moves.clone()),
_ => None,
})
.unwrap();
assert_eq!(moves, vec![FileMove { from: from.into(), to: to.into() }], "by_agent: {by_agent}");
}
}
#[test]
fn applied_event_lists_no_moves_for_text_edits() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("a.txt");
std::fs::write(&path, "old\n").unwrap();
let (docs, events) = recorded_documents();
docs.apply_workspace_edit(&WorkspaceEdit { files: vec![edit(&path, "new")], ..Default::default() }).unwrap();
assert!(
events.lock().iter().any(|e| matches!(e, IdeEvent::WorkspaceEditApplied { moves, .. } if moves.is_empty()))
);
}
#[test]
fn undo_keeps_the_encoding_chosen_for_a_file_opened_after_the_edit() {
let tmp = tempfile::tempdir().unwrap();
+10
View File
@@ -83,6 +83,8 @@ On your own messages you can **Edit** (the messages after it are replaced; files
In an existing chat, open **Model › Refresh models** to discover newly available models without sending a message or changing the selection. If the agent can't switch in place, the choice stays pending. You can choose an effort level as soon as the provider reports the new model's options. On your next message, OpenIDEA reopens the same session and applies the model and any effort you selected before sending. If the session can't be reopened or rejects either choice, OpenIDEA restores the previous selection and reports the error without sending the message.
The model picker of an existing chat offers the agent's current model list, the same one New Task uses, plus the model the chat runs. It doesn't depend on what that chat's session reported when it started, so a model found by a refresh in any chat or in New Task can be chosen in every chat of that agent.
**Focus Agent Input** defaults to `⌘L` on macOS and `Ctrl+L` on Windows / Linux in every built-in keymap. When focus is inside your writable task conversation, in either an editor tab or the tool window, it returns focus to the message input without changing your draft, caret position or selection—even when pressed repeatedly. It does not send a message or jump through message history.
With focus anywhere else, the same shortcut jumps to the message input of the task shown in an editor tab or the tool window (the one you used last, if several are shown), unless a panel claims the shortcut there: in a code editor `⌘L` / `Ctrl+L` keeps its editor meaning (for example Go to Line), and in a terminal on Windows / Linux `Ctrl+L` still reaches the shell. It does not apply to archived tasks, subagent conversations or the New Task page, and does not take focus from open popups or dialogs. To change or remove the binding, open **Settings › Keymap › Agents › Focus Agent Input**.
@@ -139,6 +141,14 @@ Tasks are saved per project and survive restarts. When the agent supports resumi
- **Agent Configs**: discovers servers already configured in `~/.copilot/mcp-config.json` (and installed Copilot CLI plugins), `~/.claude.json`, `~/.codex/config.toml`, `~/.cursor/mcp.json`, `~/.gemini/settings.json`, `~/.jetbrains/mcp/mcp.json`, `.mcp.json`, and `.vscode/mcp.json` so you can import them into Global or Project settings with one click. You can also add or edit servers via structured fields or raw `mcpServers` JSON (**Add from JSON**), and run **Test Connection** to inspect the tools a server advertises.
- **Per-session (`MCP` / `/mcp`)**: in both **New Agent Task** and active task conversations, open **MCP** in the composer toolbar (or run `/mcp`) to enable or disable individual servers—including the built-in `openidea` server—for that task only, or click **Reset** to return to the inherited defaults.
### Agent skills
**Settings › Agents › Skills** lists every skill (`SKILL.md` folders) in one place, grouped by the folder it was found in: the project's `.agents/skills` and `.openidea/skills`, your `~/.agents/skills` (what `npx skills add` fills), and each CLI's own folders (`.claude/skills`, `.github/skills`, `.codex/skills`, `.cursor/skills`, `~/.claude/skills`, `~/.copilot/skills` and its installed plugins, `~/.codex/skills`, `~/.cursor/skills`). Symlinked copies of the same skill appear once, and expanding a row shows its canonical path and the `SKILL.md` validation result.
Each skill runs in one of three modes, set globally or per workspace without ever editing the skill's files: **Auto** (the model decides), **Slash only** (just `/name`), or **Off**. A workspace can turn a global skill off without prose rules in `AGENTS.md`; a skill the settings keep off shows as **Enable in Settings** in the session picker.
In the composer, `/skills` (or the **Add Context** menu) opens the per-session picker next to the MCP one: turn individual skills off for this task only, or **Reset** to the inherited modes. The `/` menu offers the active skills of every agent, and Claude Code, Copilot and Codex all receive the same set. Agents that only speak ACP keep their own `/` menu, so turning a skill off there stops OpenIDEA from offering it but is otherwise best-effort.
While the agent works, the line under the conversation says what it is doing: thinking, reading, editing, running a command, writing its reply.
## Add a custom agent
+1 -1
View File
@@ -36,7 +36,7 @@ Enable or disable postfix completion, individual templates, `Tab` expansion and
## Emmet
In HTML, Vue and Svelte files, and in CSS, SCSS, Less and Sass, `⇥` / `Tab` expands Emmet abbreviations, for example `ul>li*3` or `m10`. In markup files, the editor context menu also has **Update Tag with Emmet**, which rewrites the tag at the caret from an abbreviation.
In HTML, Vue, Svelte, JSX and TSX files, and in CSS, SCSS, Less and Sass, `⇥` / `Tab` expands Emmet abbreviations, for example `ul>li*3` or `m10`. In markup files, the editor context menu also has **Update Tag with Emmet**, which rewrites the tag at the caret from an abbreviation.
## Write your own templates
+1 -2
View File
@@ -96,7 +96,7 @@ With **Do not step into library scripts** (**Settings › Build, Execution, Depl
## Framework support
- **React**: JSX and TSX get their own highlighting modes and full TypeScript server support. There is no React-specific tooling beyond that.
- **React**: JSX and TSX get their own highlighting modes and full TypeScript server support. Typing `>` closes the tag, renaming an opening or closing tag renames its partner, and completing a prop name or typing `=` after one inserts `""` for string props or `{}` for others (from the prop's type). `⇥` / `Tab` expands Emmet abbreviations among an element's children or after `return` / `=>`: `.card` becomes `<div className="card"></div>`.
- **Vue**: `.vue` files are highlighted per block and served by Vue Language Server in hybrid mode. In a Vue CLI project without `tsconfig.json`, webpack's `resolve.alias` entries (such as `@/`) are read so imports resolve. Prettier formats `.vue` files. Emmet works in templates.
- **Svelte**: Svelte Language Server; highlighting uses the HTML mode (script as TypeScript, style as CSS). Emmet works in markup.
- **Astro**: Astro Language Server with its own highlighting mode. It needs Node.js; if it can't find one, select it in **Settings › Languages & Frameworks › JavaScript Runtime**.
@@ -109,4 +109,3 @@ With **Do not step into library scripts** (**Settings › Build, Execution, Depl
- Bun runs but can't be debugged: its inspector uses the WebKit protocol, which vscode-js-debug can't attach to.
- Deno has run and debug support but no Deno language server; Deno files use the TypeScript servers.
- Coverage of Deno tasks is not supported.
- Emmet expands in HTML, Vue and Svelte, not in JSX.
+10
View File
@@ -83,6 +83,8 @@ Codex 有自己的项目信任设置。如果它禁用了当前项目的 `.codex
在已有对话中,打开**模型 › 刷新模型**即可查找新上线的模型,不会发送消息或更改当前选择。如果 agent 无法直接切换,所选模型会保持待应用状态。提供商返回新模型支持的思考强度后,你就可以选择强度。发送下一条消息时,OpenIDEA 会先恢复原会话并应用所选模型和思考强度,再发送消息。如果无法恢复会话,或原会话不接受其中任何一项,OpenIDEA 会还原之前的选择并提示错误,不会发送该消息。
已有对话的模型选择器会列出该 agent 当前的模型列表(与新任务使用的相同),外加该对话正在使用的模型。它不依赖该对话会话启动时报告的列表,因此在任一对话或新任务中通过刷新找到的模型,可在该 agent 的所有对话中选用。
所有内置按键映射中,**聚焦 Agent 输入框** 的默认快捷键都是 macOS 上的 `⌘L`、Windows / Linux 上的 `Ctrl+L`。焦点位于你自己的可输入任务对话中时,无论对话显示在编辑器标签页还是工具窗口中,它都会将焦点移回消息输入框,保留草稿、光标位置和选区;重复按下也不会改变这些内容。它不会发送消息,也不会跳转消息历史。
焦点位于其他位置时,同一快捷键会跳转到编辑器标签页或工具窗口中显示的任务的消息输入框(显示多个时,选择你最近使用的那个),除非该位置有面板占用此快捷键:在代码编辑器中,`⌘L` / `Ctrl+L` 保留编辑器含义(例如“转到行”);在 Windows / Linux 的终端中,`Ctrl+L` 仍会发送给 shell。此快捷键不适用于已归档任务、子 agent 对话或“新建任务”页面,也不会从打开的弹出窗口或对话框中抢走焦点。要修改或移除绑定,请打开 **设置 › 按键映射 › 智能体 › 聚焦 Agent 输入框**。
@@ -139,6 +141,14 @@ agent 运行过一个任务后,新任务会以它自动批准所有操作的
- **智能体配置**:自动发现 `~/.copilot/mcp-config.json`(及已安装的 Copilot CLI 插件)、`~/.claude.json`、`~/.codex/config.toml`、`~/.cursor/mcp.json`、`~/.gemini/settings.json`、`~/.jetbrains/mcp/mcp.json`、`.mcp.json` 和 `.vscode/mcp.json` 中已配置的服务器,可一键导入到全局或项目设置。添加或编辑服务器时既可使用表单,也可直接粘贴 `mcpServers` JSON(**从 JSON 添加**),并可通过 **测试连接** 查看服务器声明的工具列表。
- **按会话覆盖(`MCP` / `/mcp`)**:在 **新建 Agent 任务** 和进行中的任务对话中,单击输入框工具栏的 **MCP**(或输入 `/mcp`),即可仅针对当前任务开启或关闭任意服务器(包括内置的 `openidea` 服务器),或点击 **重置** 恢复继承的默认状态。
### 智能体技能
**设置 › 智能体 › 技能** 把所有技能(`SKILL.md` 文件夹)汇总在一个列表里,并按发现它们的文件夹分组:项目的 `.agents/skills` 与 `.openidea/skills`、你的 `~/.agents/skills`(即 `npx skills add` 填充的目录),以及各 CLI 自己的文件夹(`.claude/skills`、`.github/skills`、`.codex/skills`、`.cursor/skills`、`~/.claude/skills`、`~/.copilot/skills` 及其已安装插件、`~/.codex/skills`、`~/.cursor/skills`)。同一技能的符号链接副本只显示一次,展开一行可以看到其规范路径与 `SKILL.md` 的校验结果。
每个技能有三种运行模式,可全局或按工作区设置,且从不改动技能自身的文件:**自动**(由模型决定)、**仅斜杠**(只通过 `/名称` 调用)或 **关闭**。工作区可以关闭一个全局技能,而无需在 `AGENTS.md` 里写文字规则;被设置关闭的技能在会话选择器中会显示为 **在设置中启用**。
在输入框中,`/skills`(或 **添加上下文** 菜单)会打开与 MCP 并排的会话技能选择器:仅为当前任务关闭单个技能,或点击 **重置** 恢复继承的模式。`/` 菜单会列出所有智能体的活动技能,Claude Code、Copilot 与 Codex 收到的是同一套技能。只讲 ACP 协议的智能体保留自己的 `/` 菜单,因此在那里关闭技能只会让 OpenIDEA 不再提供它,其余尽力而为。
agent 工作时,对话下方的状态行显示它正在做什么:思考、读取、编辑、运行命令、输出回复。
## 添加自定义 agent
+1 -1
View File
@@ -36,7 +36,7 @@ items.for → for (var item : items) { … }
## Emmet
在 HTML、Vue、Svelte 文件以及 CSS、SCSS、Less、Sass 中,`⇥` / `Tab` 会展开 Emmet 缩写,例如 `ul>li*3` 或 `m10`。在标记语言文件中,编辑器右键菜单还提供 **使用 Emmet 更新标签**,用一个缩写改写光标所在的标签。
在 HTML、Vue、Svelte、JSX、TSX 文件以及 CSS、SCSS、Less、Sass 中,`⇥` / `Tab` 会展开 Emmet 缩写,例如 `ul>li*3` 或 `m10`。在标记语言文件中,编辑器右键菜单还提供 **使用 Emmet 更新标签**,用一个缩写改写光标所在的标签。
## 编写自己的模板
+1 -2
View File
@@ -96,7 +96,7 @@ Jest 和 Vitest 的输出会解析成测试树,支持 **重新运行失败的
## 框架支持
- **React**:JSX 和 TSX 有各自的高亮模式,并获得完整的 TypeScript 服务器支持;除此之外没有 React 专属功能。
- **React**:JSX 和 TSX 有各自的高亮模式,并获得完整的 TypeScript 服务器支持。输入 `>` 会自动闭合标签,修改开始或结束标签名会同步修改另一端,补全属性名或在属性名后输入 `=` 会按属性类型插入 `""`(字符串)或 `{}`(其他类型)。在元素的子内容中或 `return` / `=>` 之后,`⇥` / `Tab` 会展开 Emmet 缩写:`.card` 会变成 `<div className="card"></div>`。
- **Vue**:`.vue` 文件按块高亮,由 Vue Language Server 以 hybrid 模式提供支持。没有 `tsconfig.json` 的 Vue CLI 项目会读取 webpack 的 `resolve.alias`(如 `@/`),让 import 能正确解析。Prettier 可格式化 `.vue` 文件,模板中可用 Emmet。
- **Svelte**:使用 Svelte Language Server;高亮沿用 HTML 模式(script 按 TypeScript、style 按 CSS),标记部分可用 Emmet。
- **Astro**:使用 Astro Language Server,有专门的高亮模式。它需要 Node.js,找不到时请在 **设置 › 语言和框架 › JavaScript 运行时** 中选择。
@@ -109,4 +109,3 @@ Jest 和 Vitest 的输出会解析成测试树,支持 **重新运行失败的
- Bun 可以运行但无法调试:它的 inspector 使用 WebKit 协议,vscode-js-debug 无法附加。
- Deno 支持运行和调试,但没有 Deno 语言服务器,Deno 文件使用 TypeScript 服务器。
- 不支持 Deno task 的覆盖率。
- Emmet 只在 HTML、Vue 和 Svelte 中展开,JSX 中不可用。
+62 -2
View File
@@ -1,7 +1,18 @@
import type { Page } from "@playwright/test";
import type { BuildModel, BuildTool } from "../src/platform/ipc";
import type { BuildModel, BuildTool, MavenDependency } from "../src/platform/ipc";
import { expect, stubDesktop, test } from "./fixtures";
const jsonCore: MavenDependency = {
groupId: "com.example.json",
artifactId: "json-core",
version: "2.1.0",
type: "jar",
classifier: null,
scope: "compile",
optional: false,
children: [],
};
const model: BuildModel = {
maven: {
projects: [
@@ -17,7 +28,14 @@ const model: BuildModel = {
modules: [],
aggregated: false,
plugins: [],
dependencies: [],
dependencies: [
jsonCore,
{
...jsonCore,
artifactId: "json-mapper",
children: [{ ...jsonCore, version: "2.0.0", omitted: "conflict", conflictWith: "2.1.0" }],
},
],
profiles: [],
javaVersion: 21,
command: "mvn",
@@ -97,3 +115,45 @@ for (const tool of ["maven", "gradle"] as const) {
await expect(menu).toBeHidden();
});
}
test("Dependency Analyzer pairs its pane controls and stacks usages in a narrow editor", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 1360, height: 780 });
await showTool(page, "maven");
const toolActions = page.getByRole("toolbar", { name: "Maven actions" });
await toolActions.getByRole("button", { name: "More Actions", exact: true }).click();
await page.getByRole("menuitem", { name: "Analyze Dependencies…", exact: true }).click();
const filters = page.getByRole("toolbar", { name: "Dependency Analyzer", exact: true });
const resolved = page.getByRole("heading", { name: "Resolved Dependencies", exact: true });
const usages = page.getByRole("heading", { name: "Usages of com.example.json:json-core:2.1.0", exact: true });
const dependencies = page.getByRole("tree", { name: "Dependencies", exact: true });
const core = dependencies.getByRole("treeitem", { name: /^com\.example\.json:json-core\b/ });
const treeMode = page.getByRole("button", { name: "Show as Tree", exact: true });
const conflicts = filters.getByRole("button", { name: "Show conflicts only", exact: true });
await expect(resolved).toBeVisible();
await expect(filters.getByRole("button", { name: "Show as Tree" })).toHaveCount(0);
await treeMode.click();
await expect(treeMode).toHaveAttribute("aria-pressed", "true");
await page.getByRole("button", { name: "Show as List", exact: true }).click();
await conflicts.press("Space");
await expect(conflicts).toHaveAttribute("aria-pressed", "true");
await expect(dependencies.getByRole("treeitem")).toHaveCount(1);
await core.click();
await expect(usages).toBeVisible();
await expect(page.getByText("omitted for conflict with 2.1.0")).toBeVisible();
const wideLeft = (await resolved.boundingBox())!;
const wideRight = (await usages.boundingBox())!;
expect(Math.abs(wideLeft.y - wideRight.y)).toBeLessThan(1);
expect(wideRight.x).toBeGreaterThan(wideLeft.x + wideLeft.width);
await page.setViewportSize({ width: 790, height: 780 });
await expect
.poll(async () => (await usages.boundingBox())!.y - (await resolved.boundingBox())!.y)
.toBeGreaterThan(100);
expect(Math.abs((await usages.boundingBox())!.x - (await resolved.boundingBox())!.x)).toBeLessThan(1);
expect(await filters.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await expect(core).toHaveAttribute("aria-selected", "true");
await expect(page.getByRole("button", { name: "Copy Coordinates" })).toBeInViewport({ ratio: 1 });
});
+28
View File
@@ -76,6 +76,34 @@ test("⌘K commits the checked changes with the typed message", async ({ workben
await expect(changes.getByRole("checkbox", { name: "Include build.gradle.kts in commit" })).toBeHidden();
});
test("turning off default inclusion starts Commit with all files unchecked", async ({ workbench: page }) => {
await page.keyboard.press("Meta+,");
const settings = page.getByRole("dialog", { name: "Settings", exact: true });
const label = "Include changes in the commit by default";
await settings.getByRole("textbox", { name: "Search settings" }).fill(label);
await settings.getByRole("treeitem", { name: "Commit", exact: true }).click();
const toggle = settings.getByRole("checkbox", { name: label, exact: true });
await expect(toggle).toBeChecked();
await toggle.click();
await settings.getByRole("button", { name: "OK", exact: true }).click();
await expect(settings).not.toBeVisible();
await stubRepository(page);
await page.keyboard.press("Meta+k");
const panel = page.getByRole("region", { name: "Commit", exact: true });
const changes = panel.getByRole("tree", { name: "Changes" });
const tracked = changes.getByRole("checkbox", { name: "Include build.gradle.kts in commit" });
await expect(tracked).toHaveAttribute("aria-checked", "false");
await expect(changes.getByRole("checkbox", { name: "Include Unversioned Files in commit" })).not.toBeChecked();
await tracked.click();
await expect(tracked).toBeChecked();
await panel.getByRole("textbox", { name: "Commit message" }).fill("Commit the selected file");
await panel.getByRole("button", { name: "Commit", exact: true }).click();
await expect.poll(() => ipcCalls(page, "vcs_commit")).toHaveLength(1);
const [committed] = await ipcCalls(page, "vcs_commit");
expect(committed!.options).toMatchObject({ stage: [`${ROOT}/build.gradle.kts`] });
});
test("commit message history opens above the message without an empty icon column", async ({ workbench: page }) => {
await stubRepository(page);
await page.keyboard.press("Meta+k");
+79
View File
@@ -121,3 +121,82 @@ test("Git Log keeps filters and actions inside the commit pane at the minimum wi
await toolbar.getByRole("button", { name: "More Filters" }).click();
await expect(page.getByRole("menuitem", { name: "Paths" })).toBeVisible();
});
test("the Paths filter replaces the repository filter and can be cleared from overflow", async ({
workbench: page,
}) => {
await page.evaluate(async () => {
const storeModule = "/src/features/vcs/store.ts";
const { useVcs } = await import(/* @vite-ignore */ storeModule);
const root = "/dev/acme-api";
const other = "/dev/tools";
const branch = (name: string) => ({
name,
current: true,
remote: false,
upstream: null,
ahead: 0,
behind: 0,
lastCommitMs: 0,
commit: "",
});
const handlers = window.__ipc.handlers;
handlers.vcs_branches = ({ repo }) => [branch(repo === other ? "tools-main" : "api-main")];
useVcs.setState({ roots: [root, other], branches: [branch("api-main")] });
handlers.fs_read_dir = ({ path }) =>
path === root ? [{ name: "api.ts", path: root + "/api.ts", kind: "file", size: 0, mtimeMs: 0 }] : [];
const log = handlers.vcs_log!;
handlers.vcs_log = (args) => {
const { paths } = args.query as { paths?: string[] };
return log({ ...args, query: { ...(args.query as object), skip: paths?.includes(root + "/api.ts") ? 1 : 0 } });
};
});
await page.setViewportSize({ width: 600, height: 550 });
const toolbar = page.getByRole("toolbar", { name: "Log filters" });
const overflow = toolbar.getByRole("button", { name: "More Filters" });
await overflow.click();
await page.getByRole("menuitem", { name: "Paths", exact: true }).click();
const acme = page.getByRole("menuitemcheckbox", { name: "acme-api" });
await expect(acme).toHaveAttribute("aria-checked", "true");
await acme.click();
await overflow.click();
await page.getByRole("menuitem", { name: "Paths: tools", exact: true }).click();
await expect(acme).toHaveAttribute("aria-checked", "false");
await page.getByRole("menuitem", { name: "Select in Tree…" }).click();
const picker = page.getByRole("dialog", { name: "Filter by Paths" });
const pathTree = picker.getByRole("tree", { name: "Files and folders" });
const repo = pathTree.getByRole("checkbox", { name: "acme-api" });
await expect(repo).toBeVisible();
const tree = await pathTree.boundingBox();
const row = await repo.locator("xpath=ancestor::label").boundingBox();
expect(tree!.x + tree!.width).toBeGreaterThanOrEqual(row!.x + row!.width);
await repo.check();
await picker.getByRole("button", { name: "OK" }).click();
await page.setViewportSize({ width: 1100, height: 720 });
const branches = page.getByRole("tree", { name: "Branches", exact: true });
await expect(branches.getByText("api-main", { exact: true })).toBeVisible();
await expect(branches.getByText("tools-main", { exact: true })).toHaveCount(0);
await page.setViewportSize({ width: 600, height: 550 });
await overflow.click();
await page.getByRole("menuitem", { name: /^Paths:/ }).click();
await page.getByRole("menuitem", { name: "Select in Tree…" }).click();
await repo.uncheck();
await repo.locator("xpath=ancestor::*[@data-row]").locator("[data-tree-toggle]").click();
await picker.getByRole("checkbox", { name: "api.ts" }).check();
await picker.getByRole("button", { name: "OK" }).click();
const firstCommit = page.getByRole("listbox", { name: "Commits" }).getByRole("option").first();
await expect(firstCommit.getByText("Commit 1", { exact: true })).toBeVisible();
await overflow.click();
await page.getByRole("menuitem", { name: /^Paths:/ }).click();
await page.getByRole("menuitem", { name: "All" }).click();
await expect(firstCommit.getByText("Commit 0", { exact: true })).toBeVisible();
await overflow.click();
await page.getByRole("menuitem", { name: "Paths", exact: true }).click();
await expect(page.getByRole("menuitemcheckbox", { name: "api.ts" })).toBeVisible();
await page.getByRole("menuitem", { name: "Select…", exact: true }).click();
await picker.getByRole("textbox", { name: "Paths" }).fill("acme-api/api.ts");
await picker.getByRole("button", { name: "OK" }).click();
await expect(firstCommit.getByText("Commit 1", { exact: true })).toBeVisible();
});
+43 -5
View File
@@ -120,15 +120,53 @@ test("Directory Mappings keeps the controls and headers visible while scrolling
name: "VCS of integrations/finance-and-order-reconciliation/ledger-adapter-32",
exact: true,
});
await vcs.click();
await page.getByRole("option", { name: "<none>", exact: true }).click();
await expect(vcs).toHaveText("<none>");
await name.click();
const remove = toolbar.getByRole("button", { name: "Remove", exact: true });
await expect(remove).toBeEnabled();
await remove.click();
const unregistered = table.getByRole("rowgroup", { name: "Unregistered roots" });
await expect(unregistered.getByRole("row").last()).toContainText("ledger-adapter-32");
await expect(repo).toHaveAttribute("aria-selected", "true");
await expect(repo.getByRole("cell", { name: "Git", exact: true })).toBeVisible();
await expect(remove).toBeDisabled();
await toolbar.getByRole("button", { name: "Add", exact: true }).click();
const add = toolbar.getByRole("button", { name: "Add", exact: true });
await add.click();
await expect(vcs).toHaveText("Git");
await expect(unregistered).toHaveCount(0);
await expect(table.getByText("billing-audit-adapter", { exact: true })).toHaveCount(0);
const ledger = (n: number) => table.getByText(`ledger-adapter-${n}`, { exact: true });
const selectedNames = () => table.locator("tr[aria-selected=true] td:first-child").allTextContents();
await ledger(29).click();
await ledger(31).click({ modifiers: ["Meta"] });
expect(await selectedNames()).toEqual([
"integrations/finance-and-order-reconciliation/ledger-adapter-29",
"integrations/finance-and-order-reconciliation/ledger-adapter-31",
]);
await ledger(29).click();
await ledger(31).click({ modifiers: ["Shift"] });
await expect(table.locator("tr[aria-selected=true]")).toHaveCount(3);
expect(await page.evaluate(() => window.getSelection()?.toString())).toBe("");
await remove.click();
await expect(unregistered.getByRole("row")).toHaveCount(4);
await expect(unregistered.locator("tr[aria-selected=true]")).toHaveCount(3);
await expect(unregistered.getByText("ledger-adapter-29", { exact: true })).toBeVisible();
await expect(unregistered.getByText("ledger-adapter-30", { exact: true })).toBeVisible();
await expect(unregistered.getByText("ledger-adapter-31", { exact: true })).toBeVisible();
await ledger(32).click({ modifiers: ["Meta"] });
await expect(remove).toBeDisabled();
await expect(add).toBeDisabled();
await ledger(32).click({ modifiers: ["Meta"] });
await add.click();
await expect(unregistered).toHaveCount(0);
await expect(table.locator("tr[aria-selected=true]")).toHaveCount(3);
await add.click();
const added = table.getByRole("row").filter({ hasText: "billing-audit-adapter" });
await expect(added.getByText("billing-audit-adapter", { exact: true })).toBeInViewport({ ratio: 1 });
await expect(added).toHaveAttribute("aria-selected", "true");
await toolbar.getByRole("button", { name: "Remove", exact: true }).click();
await remove.click();
await expect(added).toHaveCount(0);
await settings.getByRole("button", { name: "Cancel", exact: true }).click();
+20
View File
@@ -65,6 +65,26 @@ for (const locale of ["en", "zh"]) {
});
}
test("keeps Open project in options within narrow System Settings", async ({ workbench: page }) => {
await page.keyboard.press("Meta+,");
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
await expect(dialog).toBeVisible();
await selectPage(page, "general");
const group = dialog.getByRole("radiogroup", { name: "Open project in", exact: true });
const longest = group.getByRole("radio", { name: "New tab in current window", exact: true });
await expect(longest).toBeVisible();
await page.setViewportSize({ width: 520, height: 760 });
const overflow = await longest.evaluate(async (radio) => {
await new Promise<void>((resolve) => requestAnimationFrame(() => requestAnimationFrame(() => resolve())));
const label = radio.closest("label")!;
const group = radio.closest('[role="radiogroup"]')!;
const text = document.createRange();
text.selectNodeContents(label);
return text.getBoundingClientRect().right - group.getBoundingClientRect().right;
});
expect(overflow).toBeLessThanOrEqual(1);
});
test("settings sidebar resizes with mouse and keyboard and remembers its width", async ({ workbench: page }) => {
await page.keyboard.press("Meta+,");
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
+5
View File
@@ -71,12 +71,17 @@ test("⌘1 focuses, hides and re-shows the Project tool window", async ({ workbe
test("⌘4 toggles Run; Shift+Escape hides the active tool window", async ({ workbench: page }) => {
const run = page.getByRole("region", { name: "Run" });
// The shortcut hides the window only once it is active: activation focuses it a frame after it shows.
const focusedInRun = () =>
expect.poll(() => page.evaluate(() => !!document.activeElement?.closest('[data-toolwindow="run"]'))).toBe(true);
await page.keyboard.press("Meta+4");
await expect(run).toBeVisible();
await focusedInRun();
await page.keyboard.press("Meta+4");
await expect(run).toBeHidden();
await page.keyboard.press("Meta+4");
await expect(run).toBeVisible();
await focusedInRun();
await page.keyboard.press("Shift+Escape");
await expect(run).toBeHidden();
});
+3
View File
@@ -46,7 +46,10 @@ agent_set_command trusted project_host bin
agent_set_config trusted project_host bindings async
agent_set_env trusted project_host bindings sync
agent_set_mcp_overrides always project_host bindings sync
agent_set_skill_overrides always project_host bindings sync
agent_shell trusted project_host bindings async
agent_skills_list always project_host bindings async
agent_skills_set_mode always project_host bindings sync
agent_stop_background always project_host bindings async
agent_subscribe always project_host bindings sync
agent_unarchive always project_host bindings sync
+116 -2
View File
@@ -143,11 +143,23 @@ export const commands = {
agentSetEnv: (id: string, env: { [key in string]: string }) => typedError<null, IdeError>(__TAURI_INVOKE("agent_set_env", { id, env })),
/** Updates per-session MCP server enable/disable overrides on `task`. */
agentSetMcpOverrides: (task: string, overrides: { [key in string]: boolean }) => typedError<AgentTask_Serialize, IdeError>(__TAURI_INVOKE("agent_set_mcp_overrides", { task, overrides })),
/** Updates per-session skill modes on `task`. */
agentSetSkillOverrides: (task: string, overrides: { [key in string]: AgentSkillMode }) => typedError<AgentTask_Serialize, IdeError>(__TAURI_INVOKE("agent_set_skill_overrides", { task, overrides })),
/**
* Runs a `!` line of the composer in the task's folder with the user's shell, without
* starting a turn; its output goes to the agent with the next message.
*/
agentShell: (task: string, command: string, request: RequestId) => typedError<null, IdeError>(__TAURI_INVOKE("agent_shell", { task, command, request })),
/**
* Every skill discovered in the project and the user's folders, with the mode a session
* of this project runs it with (without any session's own overrides).
*/
agentSkillsList: () => typedError<AgentSkillState[], IdeError>(__TAURI_INVOKE("agent_skills_list")),
/**
* Sets how `name` may run in `scope`, in the settings file of that scope, and returns the
* updated list. `SKILL.md` files are never touched; the default `auto` removes the entry.
*/
agentSkillsSetMode: (name: string, scope: McpScope, mode: AgentSkillMode) => typedError<AgentSkillState[], IdeError>(__TAURI_INVOKE("agent_skills_set_mode", { name, scope, mode })),
/** Stops one of the task's background tasks. */
agentStopBackground: (task: string, background: string) => typedError<null, IdeError>(__TAURI_INVOKE("agent_stop_background", { task, background })),
/**
@@ -538,7 +550,7 @@ export const commands = {
docOpenVirtual: (uri: string) => typedError<DocumentInfo, IdeError>(__TAURI_INVOKE("doc_open_virtual", { uri })),
/**
* Structure view: LSP document symbols when available (with tree-sitter
* visibility), tree-sitter otherwise.
* visibility and type-alias kinds), tree-sitter otherwise.
* Tree-sitter answers come from the per-document tree cache (incremental
* re-parse); large documents get no syntax structure.
*/
@@ -2193,6 +2205,8 @@ export type AgentChange = {
removed: number,
/** Path before a rename; the left side of its diff reads this path. */
oldPath: string | null,
/** The repository the file is in, when the task's project holds nested repositories. */
repo: IpcPath | null,
};
/** A task's uncommitted files and the commits made since it started. */
@@ -2688,6 +2702,11 @@ export type AgentSettings_Deserialize = {
* keyed by server name (`[agents.mcpServers.<name>]`).
*/
mcpServers?: { [key in string]: AgentMcpServer_Deserialize },
/**
* How agent skills may run, keyed by skill name (`[agents.skills.<name>]`); `SKILL.md`
* files on disk are never modified.
*/
skills?: { [key in string]: AgentSkillPolicy_Deserialize },
};
/** Settings › Agents: what the conversation shows and how messages are sent. */
@@ -2728,6 +2747,89 @@ export type AgentSettings_Serialize = {
* keyed by server name (`[agents.mcpServers.<name>]`).
*/
mcpServers: { [key in string]: AgentMcpServer_Serialize },
/**
* How agent skills may run, keyed by skill name (`[agents.skills.<name>]`); `SKILL.md`
* files on disk are never modified.
*/
skills: { [key in string]: AgentSkillPolicy_Serialize },
};
/** One discovered skill: a folder with a `SKILL.md`. */
export type AgentSkill = {
/** The frontmatter `name`, else the folder's name. */
name: string,
description: string,
/** Canonical folder holding `SKILL.md` (symlinks resolved, so duplicates collapse). */
path: IpcPath,
source: AgentSkillSource,
/** The `SKILL.md` passes validation (`name` matches its folder, `description` present). */
valid: boolean,
/** What validation found (`name` mismatch, missing or over-long description…). */
warnings: string[],
};
/** How an agent skill may run (`[agents.skills.<name>] mode = …`). */
export type AgentSkillMode =
/** The model decides when to use it. */
"auto" |
/** Only when the user invokes it with `/name`. */
"slashOnly" |
/** Never. */
"off";
/** Which layer decided a skill's [`AgentSkillState::mode`]. */
export type AgentSkillOrigin = "none" | "session" | "workspace" | "user" |
/** An untrusted workspace's skills and policies may only turn skills off. */
"trust";
/** A skill's policy in Settings › Agents › Skills, stored without touching its `SKILL.md`. */
export type AgentSkillPolicy = AgentSkillPolicy_Serialize | AgentSkillPolicy_Deserialize;
/** A skill's policy in Settings › Agents › Skills, stored without touching its `SKILL.md`. */
export type AgentSkillPolicy_Deserialize = {
mode?: AgentSkillMode,
};
/** A skill's policy in Settings › Agents › Skills, stored without touching its `SKILL.md`. */
export type AgentSkillPolicy_Serialize = {
mode: AgentSkillMode,
};
/** Which CLI's own folders a skill was discovered in (Settings › Agents › Skills groups by it). */
export type AgentSkillSource =
/** The project's `.agents/skills` and `.openidea/skills`. */
"workspace" |
/** The user's `~/.agents/skills` (what `npx skills add` fills). */
"user" |
/** The project's `.claude/skills`. */
"claudeWorkspace" |
/** `~/.claude/skills`. */
"claudeUser" |
/** The project's `.github/skills` (Copilot's repository skills). */
"githubWorkspace" |
/** `~/.copilot/skills` and `~/.copilot/installed-plugins/*`. */
"copilotUser" |
/** The project's `.codex/skills`. */
"codexWorkspace" |
/** `~/.codex/skills`. */
"codexUser" |
/** The project's `.cursor/skills`. */
"cursorWorkspace" |
/** `~/.cursor/skills`. */
"cursorUser";
/**
* A skill as Settings › Agents › Skills shows it: discovery plus the effective mode and
* which layer decided it.
*/
export type AgentSkillState = {
skill: AgentSkill,
mode: AgentSkillMode,
/**
* What set `mode`: a session override, the workspace, the user's settings, workspace
* trust, or nothing (the default `auto`).
*/
origin: AgentSkillOrigin,
};
/** Where an agent comes from. */
@@ -2802,6 +2904,8 @@ export type AgentTask_Deserialize = {
background?: AgentBackgroundTask[],
/** Per-session MCP server enable/disable overrides (`server_name` -> `enabled`), including `"openidea"`. */
mcpOverrides?: { [key in string]: boolean },
/** Per-session skill modes (`skill name` -> mode), on top of the settings' policies. */
skillOverrides?: { [key in string]: AgentSkillMode },
/** Token counts of the last turn and context compressions, when the agent reports them. */
stats?: AgentSessionStats,
};
@@ -2852,6 +2956,8 @@ export type AgentTask_Serialize = {
background: AgentBackgroundTask[],
/** Per-session MCP server enable/disable overrides (`server_name` -> `enabled`), including `"openidea"`. */
mcpOverrides?: { [key in string]: boolean },
/** Per-session skill modes (`skill name` -> mode), on top of the settings' policies. */
skillOverrides?: { [key in string]: AgentSkillMode },
/** Token counts of the last turn and context compressions, when the agent reports them. */
stats: AgentSessionStats,
};
@@ -3802,6 +3908,7 @@ export type CommitSettings = {
* window and a Commit dialog.
*/
nonModal?: boolean,
includeChangesByDefault?: boolean,
/** Start with an empty message instead of the last one / the changelist's. */
clearInitialMessage?: boolean,
analyzeCode?: boolean,
@@ -7126,6 +7233,8 @@ version: number } |
{ type: "docDiskConflict"; doc: DocId; path: string } |
/** A complete workspace edit can be undone as one operation. */
{ type: "workspaceEditApplied"; id: number; paths: IpcPath[];
/** Files the edit renamed, as the edit named them: editors open on them follow. */
moves: FileMove[];
/**
* Made by an agent through the MCP server's tools: undoable like a refactoring, but
* not announced as one.
@@ -8161,7 +8270,10 @@ export type LineMarkerInfo = {
export type LineMatch = {
/** 0-based line. */
line: number,
/** Line text, truncated around the match for very long lines. */
/**
* Line text, truncated around the matches for very long lines: such a line comes as one
* `LineMatch` per window, so the same `line` can repeat.
*/
text: string,
/** UTF-16 column ranges within `text`. */
ranges: ([number, number])[],
@@ -9014,6 +9126,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.
+118
View File
@@ -0,0 +1,118 @@
import { afterEach, describe, expect, it } from "vitest";
import { EditorSelection, EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { closeBrackets } from "@codemirror/autocomplete";
import { insertNewlineAndIndent } from "@codemirror/commands";
import { javascript } from "@codemirror/lang-javascript";
import { validateEditorExtras } from "@/platform/editorSettings";
import { prefsExtension } from "./prefs";
import { findLanguageDescription, loadSupport } from "./languages";
const views: EditorView[] = [];
afterEach(() => views.splice(0).forEach((v) => v.destroy()));
/** A TSX editor wired as the real one: language support (with `autoCloseTags`), closeBrackets and prefs. */
function make(text: string) {
const at = text.indexOf("|");
const view = new EditorView({
state: EditorState.create({
doc: text.replace("|", ""),
selection: EditorSelection.cursor(at),
extensions: [
javascript({ jsx: true, typescript: true }),
closeBrackets(),
prefsExtension({
prefs: validateEditorExtras({}),
path: "",
softWrap: false,
showWhitespace: false,
hardWrapAt: 120,
readOnly: false,
language: "typescriptreact",
}),
],
}),
parent: document.body,
});
views.push(view);
return view;
}
function show(view: EditorView): string {
const doc = view.state.doc.toString();
const head = view.state.selection.main.head;
return doc.slice(0, head) + "|" + doc.slice(head);
}
/** Types `text` one character at a time through the real input handlers. */
function type(v: EditorView, text: string) {
for (const ch of text) {
const r = v.state.selection.main;
const insert = () => v.state.update(v.state.replaceSelection(ch), { userEvent: "input.type" });
if (!v.state.facet(EditorView.inputHandler).some((h) => h(v, r.from, r.to, ch, insert))) v.dispatch(insert());
}
}
describe("JSX tag auto-close", () => {
it("closes an opening tag on `>`", () => {
const v = make("const a = |;");
type(v, "<div>");
expect(show(v)).toBe("const a = <div>|</div>;");
});
it("closes components, member names and fragments", () => {
const v = make("const a = |;");
type(v, "<Foo.Bar>");
expect(show(v)).toBe("const a = <Foo.Bar>|</Foo.Bar>;");
const f = make("const a = |;");
type(f, "<>");
expect(show(f)).toBe("const a = <>|</>;");
});
it("closes after attributes, but not self-closing tags", () => {
const v = make("const a = |;");
type(v, '<div id="x">');
expect(show(v)).toBe('const a = <div id="x">|</div>;');
const s = make("const a = |;");
type(s, "<Foo />");
expect(show(s)).toBe("const a = <Foo />|;");
});
it("completes the closing tag on `</`", () => {
const v = make("const a = <div>x|;");
type(v, "</");
expect(show(v)).toBe("const a = <div>x</div>|;");
});
});
describe("Enter between JSX tags", () => {
/** Presses Enter at `|` with the editor's TSX / JSX mode (its grammar patches included). */
async function enter(mode: "TSX" | "JSX", text: string) {
const support = await loadSupport(findLanguageDescription(mode, `/p/a.${mode.toLowerCase()}`)!);
const at = text.indexOf("|");
const view = new EditorView({
state: EditorState.create({
doc: text.replace("|", ""),
selection: EditorSelection.cursor(at),
extensions: support!,
}),
parent: document.body,
});
views.push(view);
insertNewlineAndIndent(view);
return show(view);
}
it("puts the caret on an indented line with the closing tag below, at the opening tag's indent", async () => {
expect(await enter("TSX", "function A() {\n return (\n <div>|</div>\n );\n}")).toBe(
"function A() {\n return (\n <div>\n |\n </div>\n );\n}",
);
expect(await enter("JSX", 'const a = <Foo.Bar id="x">|</Foo.Bar>;')).toBe(
'const a = <Foo.Bar id="x">\n |\n</Foo.Bar>;',
);
});
it("only splits a tag pair", async () => {
expect(await enter("TSX", "const a = <div>x|</div>;")).toBe("const a = <div>x\n|</div>;");
});
});
+13 -1
View File
@@ -17,6 +17,7 @@ import {
language as languageFacet,
type StreamParser,
} from "@codemirror/language";
import { NodeProp } from "@lezer/common";
import { styleTags, tags as t } from "@lezer/highlight";
import { languages as languageData } from "@codemirror/language-data";
import type { DocBackend, LanguageInfo } from "../backend";
@@ -450,8 +451,19 @@ const EXTRA_TAGS: Record<string, Parameters<typeof styleTags>[0]> = {
const bracedIndent = delimitedIndent({ closing: "}" });
/** Grammar props the stock languages lack: indentation that follows the language's usual style. */
/**
* JSX tags pair up as HTML's do: Enter between `<div>` and `</div>` puts the caret on an
* indented line of its own with the closing tag below, and the tags match each other.
*/
const JSX_TAG_PAIRS = [
NodeProp.closedBy.add({ JSXOpenTag: ["JSXCloseTag"] }),
NodeProp.openedBy.add({ JSXCloseTag: ["JSXOpenTag"] }),
];
/** Grammar props the stock languages lack: indentation that follows the language's usual style, JSX tag pairs. */
const EXTRA_PROPS: Record<string, NonNullable<Parameters<LRLanguage["configure"]>[0]["props"]>> = {
JSX: JSX_TAG_PAIRS,
TSX: JSX_TAG_PAIRS,
// clang-format's built-in styles (NamespaceIndentation: None, no extern block indent) keep the
// contents of `namespace x { … }` and `extern "C" { … }` at the level of the braces' line.
"C++": [
+70
View File
@@ -3,6 +3,7 @@ import { EditorSelection, EditorState, type Extension } from "@codemirror/state"
import { EditorView } from "@codemirror/view";
import { history, redo, undo } from "@codemirror/commands";
import { html } from "@codemirror/lang-html";
import { javascript } from "@codemirror/lang-javascript";
import { linkedTags } from "./linkedTags";
import { prefsExtension } from "./prefs";
import { angular } from "./angular";
@@ -221,6 +222,53 @@ describe("linked html tags", () => {
}
});
describe("in JSX / TSX", () => {
const tsx = (text: string) => makeWith([javascript({ jsx: true, typescript: true }), linkedTags, history()], text);
it("renames the closing tag while the opening one is typed, and back", () => {
const v = tsx('const a = <div| className="x">hi</div>;');
type(v, "s");
expect(show(v)).toBe('const a = <divs| className="x">hi</divs>;');
const w = tsx("const a = <Foo>hi</Fo|o>;");
type(w, "x");
expect(show(w)).toBe("const a = <Foxo>hi</Fox|o>;");
});
it("renames member and namespaced names as a whole", () => {
const v = tsx("const a = <Foo.Bar|>x</Foo.Bar>;");
type(v, "z");
expect(v.state.doc.toString()).toBe("const a = <Foo.Barz>x</Foo.Barz>;");
const w = tsx("const a = <|Foo.Bar>x</Foo.Bar>;");
type(w, "My");
expect(w.state.doc.toString()).toBe("const a = <MyFoo.Bar>x</MyFoo.Bar>;");
});
it("follows the element's own closing tag through nested same-name elements", () => {
const v = tsx("const a = <div|><div></div></div>;");
type(v, "x");
expect(v.state.doc.toString()).toBe("const a = <divx><div></div></divx>;");
});
it("leaves fragments, self-closing tags and attributes alone", () => {
const v = tsx("const a = <Foo| />;");
type(v, "x");
expect(v.state.doc.toString()).toBe("const a = <Foox />;");
const w = tsx("const a = <div |>x</div>;");
type(w, "a");
expect(w.state.doc.toString()).toBe("const a = <div a>x</div>;");
const f = tsx("const a = <|>x</>;");
type(f, "p");
expect(f.state.doc.toString()).toBe("const a = <p>x</>;");
});
it("undoes both tags in one step", () => {
const v = tsx("const a = <div|></div>;");
type(v, "x");
expect(undo(v)).toBe(true);
expect(v.state.doc.toString()).toBe("const a = <div></div>;");
});
});
describe("the smart key gates the filter", () => {
/** The real wiring: prefsExtension attaches the filter for the document's language. */
const prefs = (language: string | undefined, smartKeys: Record<string, unknown> = {}) =>
@@ -256,6 +304,28 @@ describe("linked html tags", () => {
}
});
it("links tags for JSX / TSX", () => {
for (const language of ["typescriptreact", "javascriptreact"]) {
const v = makeWith(
[
javascript({ jsx: true, typescript: language === "typescriptreact" }),
prefsExtension({
prefs: validateEditorExtras({ smartKeys: {} }),
path: "",
softWrap: false,
showWhitespace: false,
hardWrapAt: 120,
readOnly: false,
language,
}),
],
"const a = <div|></div>;",
);
type(v, "s");
expect(v.state.doc.toString()).toBe("const a = <divs></divs>;");
}
});
it("stays off when the option is off", () => {
const v = prefs("html", { simultaneousTagEditing: false });
type(v, "s");
+31 -11
View File
@@ -1,12 +1,13 @@
/**
* Linked editing for matching HTML tags, as in IDEA's Simultaneous
* Linked editing for matching HTML and JSX tags, as in IDEA's Simultaneous
* `<tag></tag>` editing (on by default) and VS Code's Linked Editing: editing
* the name in an opening (or closing) tag renames the matching tag of the same
* element as you type. Done from the syntax tree — `@lezer/html`'s
* `OpenTag`/`CloseTag` elements, shared by every HTML-based mode — so it works
* without a language server.
* `OpenTag`/`CloseTag` elements, shared by every HTML-based mode, and
* `@lezer/javascript`'s `JSXOpenTag`/`JSXCloseTag` — so it works without a
* language server.
*
* A transaction whose change lies inside one tag's `TagName` is extended with
* A transaction whose change lies inside one tag's name is extended with
* the same edit at the same offset in the counterpart's name — one
* transaction, so undo takes both back together. Without a matching tag (void
* and self-closing tags, unclosed elements, a stray close tag) or with the two
@@ -18,18 +19,37 @@ import { syntaxTree } from "@codemirror/language";
import type { SyntaxNode, Tree } from "@lezer/common";
import { isExternalChange } from "@/editor/api";
/** The `TagName` a changed range edits — an insertion at either edge extends the name. */
/** A JSX tag's whole name — `div`, `Foo`, `Foo.Bar`, `svg:rect` — as a direct child of its tag. */
const JSX_NAMES = new Set(["JSXIdentifier", "JSXBuiltin", "JSXMemberExpression", "JSXNamespacedName"]);
const JSX_TAGS = new Set(["JSXOpenTag", "JSXCloseTag"]);
/** The JSX tag name `n` lies in, or null outside one. */
function jsxNameOf(n: SyntaxNode | null): SyntaxNode | null {
while (n?.parent && !JSX_TAGS.has(n.parent.name)) n = n.parent;
return n?.parent && JSX_NAMES.has(n.name) ? n : null;
}
/** The tag name a changed range edits — an insertion at either edge extends the name. */
function tagNameAround(tree: Tree, from: number, to: number): SyntaxNode | null {
let n = tree.resolveInner(from, -1);
if (n.name !== "TagName") n = tree.resolveInner(from, 1);
return n.name === "TagName" && n.from <= from && to <= n.to ? n : null;
for (const side of [-1, 1] as const) {
const inner = tree.resolveInner(from, side);
const n = inner.name === "TagName" ? inner : jsxNameOf(inner);
if (n && n.from <= from && to <= n.to) return n;
}
return null;
}
/** The matching tag's name of the same element, or null without one. */
function counterpartName(name: SyntaxNode): SyntaxNode | null {
const tag = name.parent;
const element = tag?.parent;
if (!tag || element?.name !== "Element") return null;
if (!tag || !element) return null;
if (element.name === "JSXElement") {
const other = element.getChild(tag.name === "JSXOpenTag" ? "JSXCloseTag" : "JSXOpenTag");
for (let c = other?.firstChild; c; c = c.nextSibling) if (JSX_NAMES.has(c.name)) return c;
return null;
}
if (element.name !== "Element") return null;
const other = element.getChild(
/^Open/.test(tag.name) ? tag.name.replace("Open", "Close") : tag.name.replace("Close", "Open"),
);
@@ -37,10 +57,10 @@ function counterpartName(name: SyntaxNode): SyntaxNode | null {
}
/** Insertions at a name's edge must extend the name; structural characters end it. */
const NOT_NAME_CHARS = /[\s/>"'<=]/;
const NOT_NAME_CHARS = /[\s/>"'<={}]/;
/**
* Editing the name of an opening (or closing) HTML tag renames its matching
* Editing the name of an opening (or closing) HTML or JSX tag renames its matching
* tag, from the syntax tree — no language server. Installed while Smart Keys ›
* Simultaneous `<tag></tag>` editing is on (the default).
*/
+15 -7
View File
@@ -518,12 +518,20 @@ export const GUTTER_ICON_GROUPS = [
] as const;
/**
* Languages whose outer parser is `@lezer/html`, where simultaneous
* `<tag></tag>` editing works from the syntax tree. Angular templates carry
* the `html` backend id (the Angular mode is picked per project), `erb` is a
* token-based mode without a syntax tree and stays out.
* Languages whose outer parser is `@lezer/html`, plus JSX / TSX, where
* simultaneous `<tag></tag>` editing works from the syntax tree. Angular
* templates carry the `html` backend id (the Angular mode is picked per
* project), `erb` is a token-based mode without a syntax tree and stays out.
*/
const LINKED_TAG_LANGUAGES = new Set(["html", "vue", "jsp", "django-html", "astro"]);
const LINKED_TAG_LANGUAGES = new Set([
"html",
"vue",
"jsp",
"django-html",
"astro",
"typescriptreact",
"javascriptreact",
]);
export interface PrefsOptions {
prefs: EditorExtras;
@@ -652,8 +660,8 @@ export function prefsExtension(o: PrefsOptions): Extension {
if (k.tabOutOfPair) out.push(tabOut);
// Simultaneous `<tag></tag>` editing, from the syntax tree: every mode whose outer
// parser is `@lezer/html` — plain HTML plus the HTML-based modes (Vue SFCs, Angular
// templates, JSP, Django and Astro; Angular templates carry the `html` backend id).
// ERB is token-based (no syntax tree), so it stays out.
// templates, JSP, Django and Astro; Angular templates carry the `html` backend id),
// and JSX / TSX. ERB is token-based (no syntax tree), so it stays out.
if (!o.readOnly && k.simultaneousTagEditing && LINKED_TAG_LANGUAGES.has(o.language ?? "")) out.push(linkedTags);
if (o.commentStyle) out.push(lineCommentStyle.of(o.commentStyle));
+3
View File
@@ -571,7 +571,10 @@ describe("DocumentManager + slots", () => {
if (id === a.doc) throw new Error("disk full");
await save(id);
});
const logged = vi.spyOn(console, "error").mockImplementation(() => {});
await expect(manager.saveAll("explicit")).rejects.toThrow("disk full");
expect(logged).toHaveBeenCalledWith("saving /p/a.txt failed", expect.objectContaining({ message: "disk full" }));
logged.mockRestore();
expect(backend.files.get("/p/a.txt")).toBe("a\n");
expect(backend.files.get("/p/b.txt")).toBe("changed b\n");
expect(a.getMeta().dirty).toBe(true);
+3 -1
View File
@@ -927,7 +927,7 @@ export class DocumentManager {
try {
await model.save("auto");
} catch (e) {
console.warn(`autosave of ${model.path} failed`, e);
logError(`autosave of ${model.path} failed`, e);
}
}
// As in IDEA, a file whose changes are not saved (autosave off, or a failed save) stays
@@ -985,6 +985,8 @@ export class DocumentManager {
.filter((m) => !(skipUntitled && isUntitledUri(m.path)))
.map((m) =>
m.save(reason).catch((e) => {
// The notification shows the message only; the log keeps the stack for reports.
logError(`saving ${m.path} failed`, e);
errors.push(e);
}),
),
+68 -3
View File
@@ -1,9 +1,14 @@
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { redo, redoDepth, undo, undoDepth, history } from "@codemirror/commands";
import { EditorView } from "@codemirror/view";
import { workspaceEditHistory } from "@/editor/api";
import { _provideOpenEditorPaths, workspaceEditHistory } from "@/editor/api";
import { installWorkspaceEditUndo } from "@/features/code-insight/workspaceUndo";
import { provideNotificationService, type NotificationService } from "@/workbench/contributions";
import {
provideEditorService,
provideNotificationService,
type EditorService,
type NotificationService,
} from "@/workbench/contributions";
import { emitLocalIdeEvent } from "@/platform/ipc";
import { createMemoryBackend, type MemoryBackend } from "../backend";
import { _resetLanguages } from "../cm/languages";
@@ -61,6 +66,7 @@ async function rename() {
type: "workspaceEditApplied",
id: 9,
paths: ["/p/A.java", "/p/B.java", "/p/closed.java"],
moves: [],
byAgent: false,
});
}
@@ -188,7 +194,13 @@ it("rebuilds multiple redo markers in order when a closed file opens", async ()
const a = await open("/p/A.java");
await rename();
await replace("alt");
emitLocalIdeEvent({ type: "workspaceEditApplied", id: 10, paths: ["/p/A.java", "/p/B.java"], byAgent: true });
emitLocalIdeEvent({
type: "workspaceEditApplied",
id: 10,
paths: ["/p/A.java", "/p/B.java"],
moves: [],
byAgent: true,
});
commands.undoWorkspaceEdit.mockImplementation(async (id: number) => {
await replace(id === 10 ? "new" : "old");
return { status: "ok", data: null };
@@ -257,3 +269,56 @@ it("keeps refactoring markers current while a secondary view is unmounted", asyn
expect(commands.undoWorkspaceEdit).toHaveBeenCalledOnce();
att.release();
});
it("editors on a file the edit renamed reopen at its new path, through Undo and Redo", async () => {
const live = () => slots.filter((s) => !closed.has(s));
const closed = new Set<EditorSlot>();
const openFile = vi.fn(async (path: string) => {
if (!live().some((s) => s.model.path === path)) await open(path);
});
const closePath = vi.fn(async (path: string) => {
for (const s of live())
if (s.model.path === path) {
closed.add(s);
s.dispose();
}
return true;
});
provideEditorService({
openFile,
closePath,
activePath: () => live().at(-1)?.model.path ?? null,
saveAll: vi.fn(),
} as unknown as EditorService);
_provideOpenEditorPaths(() => live().map((s) => s.model.path));
backend.files.set("/p/Renamed.java", "old");
const moved = async (from: string, to: string, run: () => Promise<unknown>) => {
openFile.mockClear();
await run();
await vi.waitFor(() => expect(openFile).toHaveBeenCalledExactlyOnceWith(to, { focus: false }));
expect(closePath).toHaveBeenCalledWith(from);
expect(live().map((s) => s.model.path)).toEqual(["/p/B.java", to]);
};
try {
await open("/p/B.java");
await open("/p/A.java");
await moved("/p/A.java", "/p/Renamed.java", async () => {
await replace("new");
emitLocalIdeEvent({
type: "workspaceEditApplied",
id: 11,
paths: ["/p/A.java", "/p/Renamed.java", "/p/B.java"],
moves: [{ from: "/p/A.java", to: "/p/Renamed.java" }],
byAgent: false,
});
});
// Reopened editors take part in the refactoring's history like the ones they replace.
await moved("/p/Renamed.java", "/p/A.java", () => workspaceEditHistory(11));
await moved("/p/A.java", "/p/Renamed.java", () => workspaceEditHistory(11, true));
await moved("/p/Renamed.java", "/p/A.java", () => workspaceEditHistory(11));
expect(notify).not.toHaveBeenCalled();
} finally {
provideEditorService(undefined as unknown as EditorService);
_provideOpenEditorPaths(() => []);
}
});
+22 -12
View File
@@ -3,7 +3,8 @@ import { invertedEffects, isolateHistory, redo, undo } from "@codemirror/command
import { EditorState, Prec, StateEffect, type Transaction, type Extension } from "@codemirror/state";
import { EditorView, keymap } from "@codemirror/view";
import { _emitWorkspaceEditHistory, _provideWorkspaceHistory, isExternalChange } from "@/editor/api";
import { call, commands, onIdeEvent } from "@/platform/ipc";
import { editorsFollowAppliedMoves, reversedMoves, withEditorsFollowing } from "@/editor/fileMoves";
import { call, commands, onIdeEvent, type FileMove } from "@/platform/ipc";
import { useProject } from "@/platform/project";
interface Marker {
@@ -20,7 +21,7 @@ export interface WorkspaceHistoryTarget {
export class WorkspaceHistory {
private targets = new Set<WorkspaceHistoryTarget>();
private records = new Map<number, { paths: string[]; undone: boolean }>();
private records = new Map<number, { paths: string[]; moves: FileMove[]; undone: boolean }>();
private project = useProject.getState().project;
private busy = false;
private moving = false;
@@ -31,7 +32,7 @@ export class WorkspaceHistory {
) {}
start(): () => void {
const stop = onIdeEvent("workspaceEditApplied", ({ id, paths }) => {
const stop = onIdeEvent("workspaceEditApplied", ({ id, paths, moves }) => {
if (this.project !== useProject.getState().project) {
this.records.clear();
this.project = useProject.getState().project;
@@ -43,9 +44,11 @@ export class WorkspaceHistory {
record.paths.some((path) => this.affects(paths, path) || paths.some((root) => root.startsWith(`${path}/`)))
)
this.records.delete(key);
this.records.set(id, { paths, undone: false });
this.records.set(id, { paths, moves, undone: false });
while (this.records.size > 20) this.records.delete(this.records.keys().next().value!);
for (const target of this.targets) if (this.affects(paths, target.path)) this.mark(target, id);
// Now, before the file watcher reports the old paths gone and their tabs close.
void editorsFollowAppliedMoves(moves);
});
const unprovide = _provideWorkspaceHistory((id, redo) => this.run(id, redo));
return () => {
@@ -154,14 +157,21 @@ export class WorkspaceHistory {
for (const target of targets)
if (!this.step(target, id, forward))
throw new Error("Undo newer editor changes before undoing this refactoring");
await call(forward ? commands.redoWorkspaceEdit(id) : commands.undoWorkspaceEdit(id));
await this.synced();
for (const target of targets) {
if (!this.targets.has(target)) continue;
const tr = this.step(target, id, forward);
if (tr) target.dispatch(tr);
}
record.undone = !forward;
await withEditorsFollowing(
async () => {
await call(forward ? commands.redoWorkspaceEdit(id) : commands.undoWorkspaceEdit(id));
await this.synced();
for (const target of targets) {
if (!this.targets.has(target)) continue;
const tr = this.step(target, id, forward);
if (tr) target.dispatch(tr);
}
// Editors reopened at moved paths build their history from the record: settle it first.
record.undone = !forward;
},
() => (forward ? record.moves : reversedMoves(record.moves)),
{ save: false },
);
_emitWorkspaceEditHistory({ id, undone: record.undone });
} catch (error) {
// A refused backend restore must leave the initiating editor's history intact.
+59
View File
@@ -0,0 +1,59 @@
import { afterEach, expect, it } from "vitest";
import { onIdeEvent } from "@/platform/ipc";
import { provideEditorService, type EditorService } from "@/workbench/contributions";
import { createMemoryBackend } from "./core/backend";
import { EditorController, useTabs } from "./core/controller";
import { initialTabsState } from "./core/model/tabs";
import { editorsFollowAppliedMoves } from "./fileMoves";
let ctrl: EditorController | null = null;
afterEach(() => {
ctrl?.stop();
ctrl = null;
useTabs.setState(initialTabsState(), true);
});
function setup(files: Record<string, string>) {
const backend = createMemoryBackend(files);
backend.onFsChanged = (h) => onIdeEvent("fsChanged", h);
const controller = new EditorController(backend);
controller.start();
ctrl = controller;
provideEditorService({
openFile: (path, o) => controller.openFile(path, o),
activePath: () => controller.activePath(),
closePath: (path) => controller.closePath(path),
saveAll: async () => {},
} as Partial<EditorService> as EditorService);
return { controller, backend };
}
const tabPaths = () =>
Object.values(useTabs.getState().panes).flatMap((pane) => pane.tabs.map((tab) => tab.input.path));
it("a renamed active file stays the active editor", async () => {
const { controller, backend } = setup({ "/p/A.java": "class A {}", "/p/B.java": "class B {}" });
await controller.openFile("/p/B.java", { focus: false });
await controller.openFile("/p/A.java", { focus: false });
backend.files.set("/p/Renamed.java", backend.files.get("/p/A.java")!);
backend.files.delete("/p/A.java");
await editorsFollowAppliedMoves([{ from: "/p/A.java", to: "/p/Renamed.java" }]);
expect(tabPaths()).toEqual(["/p/B.java", "/p/Renamed.java"]);
expect(controller.activePath()).toBe("/p/Renamed.java");
});
it("a renamed background file leaves the active editor in place", async () => {
const { controller, backend } = setup({ "/p/A.java": "class A {}", "/p/B.java": "class B {}" });
await controller.openFile("/p/A.java", { focus: false });
await controller.openFile("/p/B.java", { focus: false });
backend.files.set("/p/Renamed.java", backend.files.get("/p/A.java")!);
backend.files.delete("/p/A.java");
await editorsFollowAppliedMoves([{ from: "/p/A.java", to: "/p/Renamed.java" }]);
expect(tabPaths().sort()).toEqual(["/p/B.java", "/p/Renamed.java"]);
expect(controller.activePath()).toBe("/p/B.java");
});
+81
View File
@@ -0,0 +1,81 @@
/** IDEA keeps editors on files that a refactoring moves or renames: they reopen at the new paths. */
import type { FileMove } from "@/bindings";
import { openEditorPaths } from "@/editor/api";
import { notifyFilesMoved, trackFileMove } from "@/platform/fileOps";
import { emitLocalIdeEvent } from "@/platform/ipc";
import { isSameOrInside } from "@/platform/paths";
import { useProject } from "@/platform/project";
import { maybeEditorService } from "@/workbench/contributions";
export async function saveAllQuietly(editor: { saveAll(): Promise<void> }) {
try {
await editor.saveAll();
} catch {
/* unsaved files are reported by the editor */
}
}
/** `path` after `moves`. */
export function movedPath(path: string, moves: readonly FileMove[]): string {
let p = path;
for (const m of moves) if (isSameOrInside(p, m.from)) p = m.to + p.slice(m.from.length);
return p;
}
/** Moves in the opposite direction, last first: what Undo of `moves` does. */
export function reversedMoves(moves: readonly FileMove[]): FileMove[] {
return [...moves].reverse().map((m) => ({ from: m.to, to: m.from }));
}
/**
* Runs `run`, which moves the files `done` names, with the editors following: unsaved changes
* are saved first (unless `save` is false), tabs reopen at the new paths.
*/
export async function withEditorsFollowing<T>(
run: () => Promise<T>,
done: (r: T) => readonly FileMove[],
{ save = true }: { save?: boolean } = {},
): Promise<T> {
const projectRoot = () => useProject.getState().project?.root ?? null;
const root = projectRoot();
const editor = maybeEditorService();
const openBefore = editor ? openEditorPaths() : [];
if (editor && save) await saveAllQuietly(editor);
const active = editor?.activePath() ?? null;
const { result, applied } = await trackFileMove(root, async () => {
const result = await run();
const applied = done(result);
if (root === projectRoot()) await notifyFilesMoved(applied);
return { result, applied };
});
if (root !== projectRoot()) return result;
const open = openBefore.filter((p) => applied.some((m) => isSameOrInside(p, m.from)));
if (applied.length)
emitLocalIdeEvent({
type: "fsChanged",
created: applied.map((m) => m.to),
modified: [],
removed: applied.map((m) => m.from),
});
if (!editor || !open.length) return result;
// The editor closes tabs of removed files in a queue; an open that starts before an
// active tab's close counts as superseded and stays in the background.
for (const p of open) await editor.closePath?.(p).catch(() => false);
const ordered = active && open.includes(active) ? [...open.filter((p) => p !== active), active] : open;
for (const p of ordered) await editor.openFile(movedPath(p, applied), { focus: false }).catch(() => {});
if (active && !open.includes(active)) await editor.openFile(active, { focus: false }).catch(() => {});
return result;
}
/**
* Editors follow `moves` that a workspace edit already made (a server's rename, Move, a quick
* fix): called when the backend reports the edit, before the file watcher closes their tabs.
*/
export function editorsFollowAppliedMoves(moves: readonly FileMove[]): Promise<void> {
if (!moves.length) return Promise.resolve();
return withEditorsFollowing(
() => Promise.resolve(),
() => moves,
{ save: false },
);
}
+16
View File
@@ -323,6 +323,22 @@ describe("applying completions", () => {
}
});
it("puts the caret inside the parentheses of a server-inserted call that takes arguments", async () => {
setInvokeRoute(() => Promise.resolve(null));
try {
const { view, req } = setup("x.rea|\n", "", [completionExtension()]);
view.dispatch({ effects: StateEffect.appendConfig.of(lspDoc.of({ doc: 1 } as EditorDocContext)) });
const command = { title: "Apply Completion", command: "jetbrains.kotlin.completion.apply", arguments: ["1"] };
const kotlin = item({ label: "read", kind: "method", labelDetail: "(name: String)", insertText: "", command });
applyLspCompletion(view, makeCompletion(kotlin, req), 5, 5, "insert");
view.dispatch({ changes: { from: 5, insert: "d()" }, annotations: remoteChange.of(true) });
expect(view.state.doc.toString()).toBe("x.read()\n");
expect(view.state.selection.main.head).toBe(7);
} finally {
setInvokeRoute(null);
}
});
it("completes at every caret whose typed prefix matches the main caret's", () => {
const { view, req } = setup("a.cr|\nb.cr\nc.xy", "", [EditorState.allowMultipleSelections.of(true)]);
// Carets after both `cr`s (the main one first) and after `xy`.
+20 -3
View File
@@ -462,6 +462,8 @@ async function applyLateEdits(view: EditorView, c: LspCompletion, insertedAt: nu
interface ServerInsert {
at: number;
others: readonly number[];
/** The item is a call that takes arguments: the caret goes inside an inserted `()`. */
inside?: boolean;
}
const awaitServerInsert = StateEffect.define<ServerInsert | null>();
const serverInsertAt = StateField.define<ServerInsert | null>({
@@ -470,7 +472,11 @@ const serverInsertAt = StateField.define<ServerInsert | null>({
for (const e of tr.effects) if (e.is(awaitServerInsert)) return e.value;
// The edit landed, or the caret moved on before it did.
if (value === null || tr.annotation(remoteChange) || tr.selection) return null;
return { at: tr.changes.mapPos(value.at, -1), others: value.others.map((p) => tr.changes.mapPos(p, -1)) };
return {
at: tr.changes.mapPos(value.at, -1),
others: value.others.map((p) => tr.changes.mapPos(p, -1)),
inside: value.inside,
};
},
});
@@ -541,7 +547,9 @@ const caretAfterServerInsert = EditorState.transactionFilter.of((tr) => {
if (tr.changes.touchesRange(from, to)) continue;
others.push({ from: tr.changes.mapPos(from, 1), to: tr.changes.mapPos(to, -1) });
}
const selection = EditorSelection.cursor(mainAfter);
const inside =
pending.inside && /\(\)$/.test(landed.insert) && tr.newDoc.sliceString(mainAfter - 2, mainAfter) === "()";
const selection = EditorSelection.cursor(inside ? mainAfter - 1 : mainAfter);
if (!others.length) return [tr, { selection, sequential: true }];
// Not part of this transaction: a remote one is not sent back to the document model.
const changes = others
@@ -553,6 +561,12 @@ const caretAfterServerInsert = EditorState.transactionFilter.of((tr) => {
/** Client-side commands handled by the editor itself (VS Code ids servers commonly send). */
const CLIENT_COMMANDS = new Set(["editor.action.triggerParameterHints", "editor.action.triggerSuggest"]);
/** A function or method whose signature lists parameters (`(name: String)`), as far as the item tells. */
function takesArguments(item: Pick<CompletionItem, "kind" | "labelDetail" | "detail">): boolean {
if (item.kind && !CALLABLE.has(item.kind)) return false;
return /^\s*\(\s*[^)\s]/.test(item.labelDetail ?? item.detail ?? "");
}
/** kotlin-lsp inserts the item itself (`jetbrains.kotlin.completion.apply`): nothing goes in here. */
function serverInserts(item: CompletionItem): boolean {
const cmd = item.command?.command;
@@ -564,7 +578,10 @@ function runCommand(view: EditorView, item: CompletionItem, others: readonly num
if (!command?.command) return;
const cmd = command.command;
const serverInserted = serverInserts(item);
if (serverInserted) view.dispatch({ effects: awaitServerInsert.of({ at: view.state.selection.main.head, others }) });
if (serverInserted)
view.dispatch({
effects: awaitServerInsert.of({ at: view.state.selection.main.head, others, inside: takesArguments(item) }),
});
if (cmd === "editor.action.triggerParameterHints") setTimeout(() => triggerSignatureHelp(view), 0);
else if (cmd === "editor.action.triggerSuggest") setTimeout(() => startCompletion(view), 0);
else if (!CLIENT_COMMANDS.has(cmd) && !cmd.startsWith("editor.")) {
+2
View File
@@ -28,6 +28,7 @@ import { inlineCompletionExtension, registerInlineCompletionActions } from "./in
import { semanticExtension } from "./semantic";
import { usagesLensExtension } from "./codeLens";
import { autoImportExtension } from "./autoImport";
import { jsxAttrValueExtension } from "./jsxAttrValue";
import { importsOnPasteExtension, registerImportsOnPasteActions } from "./importsOnPaste";
import { installConfigurationNavigationEvents } from "./configurationNavigation";
import { installAvailabilityEvents } from "./availability";
@@ -69,6 +70,7 @@ export function lspExtensions(ctx: EditorDocContext): Extension[] {
semanticExtension(),
usagesLensExtension(),
autoImportExtension(),
jsxAttrValueExtension(ctx.language),
importsOnPasteExtension(),
unresolvedReferences(),
syntaxErrorsExtension(),
+190
View File
@@ -0,0 +1,190 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { EditorSelection, EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { history, undo } from "@codemirror/commands";
import { javascript } from "@codemirror/lang-javascript";
const ipc = vi.hoisted(() => ({
lspHover: vi.fn(),
cancelRequest: vi.fn<(id: number) => Promise<void>>(async () => {}),
}));
vi.mock("@/platform/ipc", async (orig) => {
const real = await orig<typeof import("@/platform/ipc")>();
return { ...real, isTauri: () => true, commands: { ...real.commands, ...ipc } };
});
const { attrValueKind, isStringLikeType, jsxAttrValueExtension } = await import("./jsxAttrValue");
const { lspDoc } = await import("./lsp");
const ctx = { doc: 3, path: "/p/a.tsx", language: "typescriptreact", uiMode: "TSX", readOnly: false };
const views: EditorView[] = [];
const hover = (sig: string) => ({
status: "ok" as const,
data: { contents: { kind: "markdown", value: "```typescript\n" + sig + "\n```" }, range: null },
});
function editor(text: string, language = "typescriptreact") {
const at = text.indexOf("|");
const view = new EditorView({
state: EditorState.create({
doc: text.replace("|", ""),
selection: EditorSelection.cursor(at),
extensions: [
javascript({ jsx: true, typescript: true }),
history(),
lspDoc.of({ ...ctx, language }),
jsxAttrValueExtension(language),
],
}),
parent: document.body,
});
views.push(view);
return view;
}
function show(view: EditorView): string {
const doc = view.state.doc.toString();
const head = view.state.selection.main.head;
return doc.slice(0, head) + "|" + doc.slice(head);
}
/** Types `ch` through the real input handlers. */
function type(v: EditorView, ch: string) {
const r = v.state.selection.main;
const insert = () => v.state.update(v.state.replaceSelection(ch), { userEvent: "input.type" });
if (!v.state.facet(EditorView.inputHandler).some((h) => h(v, r.from, r.to, ch, insert))) v.dispatch(insert());
}
beforeEach(() => {
vi.useFakeTimers();
ipc.lspHover.mockReset();
ipc.cancelRequest.mockClear();
});
afterEach(() => {
views.splice(0).forEach((v) => v.destroy());
vi.useRealTimers();
});
describe("isStringLikeType", () => {
it("accepts strings, string literals and template literal types", () => {
expect(isStringLikeType("string")).toBe(true);
expect(isStringLikeType("string | undefined")).toBe(true);
expect(isStringLikeType('"primary" | "secondary" | undefined')).toBe(true);
expect(isStringLikeType("'a|b' | 'c'")).toBe(true);
expect(isStringLikeType("`btn-${string}`")).toBe(true);
});
it("rejects everything else", () => {
expect(isStringLikeType("number")).toBe(false);
expect(isStringLikeType("string | number")).toBe(false);
expect(isStringLikeType("() => void")).toBe(false);
expect(isStringLikeType("ReactNode")).toBe(false);
expect(isStringLikeType("any")).toBe(false);
expect(isStringLikeType("undefined")).toBe(false);
expect(isStringLikeType("Record<string, string | number>")).toBe(false);
});
});
describe("attrValueKind", () => {
const md = (sig: string) => hover(sig).data.contents;
it("reads DOM and component prop signatures", () => {
expect(
attrValueKind(md("(property) React.HTMLAttributes<HTMLDivElement>.className?: string | undefined"), "className"),
).toBe("quotes");
expect(attrValueKind(md("(property) label: string"), "label")).toBe("quotes");
expect(attrValueKind(md('(property) "aria-label"?: string | undefined'), "aria-label")).toBe("quotes");
expect(
attrValueKind(
md('(property) React.HTMLAttributes<HTMLDivElement>["aria-label"]?: string | undefined'),
"aria-label",
),
).toBe("quotes");
expect(attrValueKind(md('(property) variant?: "ghost" | "primary" | undefined'), "variant")).toBe("quotes");
expect(
attrValueKind(md("(property) React.HTMLAttributes<HTMLDivElement>.tabIndex?: number | undefined"), "tabIndex"),
).toBe("braces");
expect(attrValueKind(md("(property) count: number"), "count")).toBe("braces");
expect(
attrValueKind(
md(
"(property) React.DOMAttributes<HTMLButtonElement>.onClick?: React.MouseEventHandler<HTMLButtonElement> | undefined",
),
"onClick",
),
).toBe("braces");
});
it("falls back to braces without a type", () => {
expect(attrValueKind(null, "x")).toBe("braces");
expect(attrValueKind({ kind: "markdown", value: "any" }, "x")).toBe("braces");
});
});
describe("= after a JSX attribute name", () => {
it("inserts quotes for a string prop, caret inside", async () => {
ipc.lspHover.mockResolvedValue(hover("(property) label: string"));
const v = editor("const a = <Btn label| />;");
type(v, "=");
expect(show(v)).toBe("const a = <Btn label=| />;");
await vi.advanceTimersByTimeAsync(0);
expect(show(v)).toBe('const a = <Btn label="|" />;');
expect(ipc.lspHover).toHaveBeenCalledWith(expect.any(Number), 3, { line: 0, col: 15 });
});
it("inserts braces for other props, and undo takes the pair back first", async () => {
ipc.lspHover.mockResolvedValue(hover("(property) count: number"));
const v = editor("const a = <Btn count|>x</Btn>;");
type(v, "=");
await vi.advanceTimersByTimeAsync(0);
expect(show(v)).toBe("const a = <Btn count={|}>x</Btn>;");
undo(v);
expect(v.state.doc.toString()).toBe("const a = <Btn count=>x</Btn>;");
});
it("falls back to braces when the server is unavailable or slow", async () => {
ipc.lspHover.mockRejectedValue({ kind: "unavailable", message: "none" });
const v = editor("const a = <Btn count| />;");
type(v, "=");
await vi.advanceTimersByTimeAsync(0);
expect(show(v)).toBe("const a = <Btn count={|} />;");
ipc.lspHover.mockReturnValue(new Promise(() => {}));
const w = editor("const a = <Btn label| />;");
type(w, "=");
await vi.advanceTimersByTimeAsync(600);
expect(show(w)).toBe("const a = <Btn label={|} />;");
expect(ipc.cancelRequest).toHaveBeenCalled();
});
it("drops the pair once something else was typed", async () => {
let answer!: (v: unknown) => void;
ipc.lspHover.mockReturnValue(new Promise((r) => (answer = r)));
const v = editor("const a = <Btn label| />;");
type(v, "=");
type(v, "x");
answer(hover("(property) label: string"));
await vi.advanceTimersByTimeAsync(0);
expect(show(v)).toBe("const a = <Btn label=x| />;");
});
it("stays out where there is no value-less attribute name before the caret", () => {
for (const text of [
'const a = <Btn label|"x" />;',
"const a = <Btn label|{x} />;",
"const a = |;",
'const a = <Btn label="x|" />;',
"const a = <Btn {...p}| />;",
]) {
const v = editor(text);
type(v, "=");
expect(ipc.lspHover).not.toHaveBeenCalled();
}
});
it("is only installed for JSX languages", () => {
const v = editor("const a = <Btn label| />;", "typescript");
type(v, "=");
expect(ipc.lspHover).not.toHaveBeenCalled();
});
});
+134
View File
@@ -0,0 +1,134 @@
/**
* JSX attribute values on `=`, as in WebStorm's "Add for JSX attribute: Based
* on type": typing `=` after an attribute name that has no value yet inserts
* `""` when the prop's type is string-like and `{}` otherwise, with the caret
* between them. The type comes from the language server's hover on the name;
* without an answer in time (no server, still starting) it falls back to `{}`.
*
* The `=` goes in at once and the pair follows as its own `input.complete`
* step — undo removes the pair first and Tab steps out of it. Anything typed
* meanwhile wins: the pair is dropped.
*/
import { EditorSelection, type EditorState, type Extension } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { syntaxTree } from "@codemirror/language";
import type { SyntaxNode } from "@lezer/common";
import type { Markup } from "@/bindings";
import { commands, nextRequestId } from "@/platform/ipc";
import { editorPrefs } from "@/platform/editorSettings";
import { docOf, lspRequest } from "./lsp";
import { offsetToPos } from "./positions";
/** Languages whose editors parse JSX. */
const JSX_LANGUAGES = new Set(["typescriptreact", "javascriptreact"]);
/** How long the pair waits for the prop's type before falling back to `{}`. */
const WAIT_MS = 500;
type ValueKind = "quotes" | "braces";
/** The name of the value-less JSX attribute ending at `pos`, or null. */
function attributeNameBefore(state: EditorState, pos: number): SyntaxNode | null {
let n: SyntaxNode | null = syntaxTree(state).resolveInner(pos, -1);
while (n?.parent && n.parent.name !== "JSXAttribute") n = n.parent;
const attr = n?.parent;
if (!n || !attr || attr.firstChild?.from !== n.from || n.to !== pos || attr.to !== pos) return null;
return n;
}
/** Splits a type at its top-level `|`s: unions inside parentheses, generics, objects or strings stay whole. */
function unionMembers(type: string): string[] {
const out: string[] = [];
let depth = 0;
let quote: string | null = null;
let start = 0;
for (let i = 0; i < type.length; i++) {
const ch = type[i]!;
if (quote) {
if (ch === "\\") i++;
else if (ch === quote) quote = null;
} else if (ch === '"' || ch === "'" || ch === "`") quote = ch;
else if ("([{<".includes(ch)) depth++;
else if (")]}>".includes(ch) && !(ch === ">" && type[i - 1] === "=")) depth--;
else if (ch === "|" && depth === 0) {
out.push(type.slice(start, i).trim());
start = i + 1;
}
}
out.push(type.slice(start).trim());
return out.filter(Boolean);
}
const STRING_MEMBER = /^(?:string|"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`)$/;
/** `string`, string literals and template literal types, optionally with `undefined` / `null`. */
export function isStringLikeType(type: string): boolean {
const members = unionMembers(type).filter((m) => m !== "undefined" && m !== "null");
return members.length > 0 && members.every((m) => STRING_MEMBER.test(m));
}
const escape = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
/**
* The delimiters for `attr`'s value from its hover: TypeScript shows
* `(property) label: string` for a component prop and
* `(property) React.HTMLAttributes<T>.className?: string | undefined` for a DOM one
* (`HTMLAttributes<T>["aria-label"]?:` for a name that is not an identifier).
*/
export function attrValueKind(markup: Markup | null | undefined, attr: string): ValueKind {
if (!markup) return "braces";
const code = /```[^\n]*\n([\s\S]*?)```/.exec(markup.value)?.[1] ?? markup.value;
const sig = code.replace(/\s+/g, " ").trim();
const name = escape(attr);
const typed = new RegExp(`(?:^|[\\s.)>])(?:${name}|\\[?"${name}"\\]?|'${name}')\\??\\s*:\\s*([\\s\\S]+)$`).exec(sig);
return typed && isStringLikeType(typed[1]!) ? "quotes" : "braces";
}
async function valueKind(view: EditorView, nameFrom: number, attr: string): Promise<ValueKind> {
const doc = docOf(view);
if (!doc) return "braces";
const state = view.state;
const id = nextRequestId();
const wanted = () => view.state.doc === state.doc;
const hover = lspRequest(() => commands.lspHover(id, doc.doc, offsetToPos(state.doc, nameFrom)), wanted)
.then((h) => attrValueKind(h?.contents, attr))
.catch((): ValueKind => "braces");
let timer: ReturnType<typeof setTimeout> | undefined;
const timeout = new Promise<null>((resolve) => (timer = setTimeout(() => resolve(null), WAIT_MS)));
const kind = await Promise.race([hover, timeout]);
clearTimeout(timer);
if (kind) return kind;
void commands.cancelRequest(id).catch(() => {});
return "braces";
}
async function insertValue(view: EditorView, nameFrom: number, attr: string) {
const state = view.state;
const after = state.selection.main.head;
const kind = await valueKind(view, nameFrom, attr);
if (!view.dom.isConnected || view.state.doc !== state.doc || view.state.selection.main.head !== after) return;
const { pairQuotes, pairBrackets } = editorPrefs().smartKeys;
if (kind === "quotes" ? !pairQuotes : !pairBrackets) return;
view.dispatch({
changes: { from: after, insert: kind === "quotes" ? '""' : "{}" },
selection: EditorSelection.cursor(after + 1),
userEvent: "input.complete",
});
}
const attrValueInput = EditorView.inputHandler.of((view, from, to, text, insert) => {
const { state } = view;
if (text !== "=" || from !== to || state.readOnly || state.selection.ranges.length > 1) return false;
const name = attributeNameBefore(state, from);
if (!name || /["'{]/.test(state.sliceDoc(from, from + 1))) return false;
const { pairQuotes, pairBrackets } = editorPrefs().smartKeys;
if (!pairQuotes && !pairBrackets) return false;
view.dispatch(insert());
void insertValue(view, name.from, state.sliceDoc(name.from, name.to));
return true;
});
/** `=` after a JSX attribute name fills in `""` or `{}` by the prop's type, in JSX / TSX editors. */
export function jsxAttrValueExtension(language: string): Extension {
return JSX_LANGUAGES.has(language) ? attrValueInput : [];
}
+11
View File
@@ -37,6 +37,17 @@ describe("markdown LaTeX math", () => {
expect(root.querySelector("p")?.textContent?.startsWith("Prices $5 and $10, with ")).toBe(true);
});
it("leaves separate code spans inside dollar signs as code", () => {
const root = parseSafe("($`x` `y`$)");
expect(root.querySelector("p")?.innerHTML).toBe("($<code>x</code> <code>y</code>$)");
});
it("matches a longer backtick delimiter around math inside emphasis", () => {
const root = parseSafe("**($``x` + y``$)**");
expect(root.querySelector("strong .katex annotation")?.textContent).toBe("x` + y");
expect(root.querySelector("code")).toBeNull();
});
it("keeps an unfinished protected delimiter from swallowing a later formula", () => {
const root = parseSafe("Unfinished $`x` and $y$.");
expect(root.querySelector("p > code")?.textContent).toBe("x");
+4 -3
View File
@@ -39,9 +39,10 @@ function findClosingDelimiter(src: string, from: number, delim: string): number
return -1;
}
const PROTECTED_INLINE_DOLLAR = /^\$`([^`\r\n]+)`\$/;
// The first backtick run of the opening length ends the code span.
const PROTECTED_INLINE_DOLLAR = /^\$(?<ticks>`+)(?!`)(?<tex>(?:[^`\r\n]|(?!\k<ticks>(?!`))`+(?!`))+)\k<ticks>\$/;
// Marked masks code spans as `[aaa]` before calling emStrongMask
const MASKED_PROTECTED_INLINE_DOLLAR = /^\$\[(a+)\]\$/;
const MASKED_PROTECTED_INLINE_DOLLAR = /^\$\[(?<tex>a+)\]\$/;
/**
* Matches inline `$...$` from index 0 using Pandoc-style guards so currency
@@ -87,7 +88,7 @@ function matchInlineMath(
if (src[0] === "$") {
const match = protectedDollar.exec(src);
if (match) {
const text = match[1]!;
const text = match.groups!.tex!;
return text.trim() ? { raw: match[0], text, display: false } : null;
}
if (src[1] === "`") return null;
+90
View File
@@ -205,6 +205,96 @@ describe("locationItems", () => {
expect((await locationItems([target("/p/src/a.py", "refresh", 3)]))[0]!.label).toBe("refresh");
});
describe("takes the container only from a type whose body holds the target", () => {
const cart = [
'import { type Cents } from "./money.ts";',
"",
"export interface Product {",
" id: string;",
" price: Cents;",
"}",
"",
"export interface CartLine {",
" product: Product;",
" quantity: number;",
"}",
"",
'export type Discount = { kind: "percent"; percent: number } | { kind: "fixed"; amount: Cents };',
"",
"export class Cart {",
" private discount: Discount | null = null;",
"",
" total(): Cents {",
" return 0;",
" }",
"}",
];
const at = (line: number, col: number) => ({
path: "/p/src/cart.ts",
uri: null,
range: { start: { line, col }, end: { line, col: col + 1 } },
});
beforeEach(() => {
readManyFileLines.mockResolvedValue(new Map([["/p/src/cart.ts", cart]]));
project("/p");
});
it("anonymous targets after a closed interface", async () => {
const union = cart[12]!;
const items = await locationItems([at(12, union.indexOf("{")), at(12, union.lastIndexOf("{ kind"))]);
expect(items.map((i) => [i.label, i.detail])).toEqual([
["cart.ts", "src/cart.ts:13"],
["cart.ts", "src/cart.ts:13"],
]);
});
it("a named target after a closed interface", async () => {
const item = (await locationItems([at(7, cart[7]!.indexOf("CartLine"))]))[0]!;
expect([item.label, item.detail]).toEqual(["CartLine", "src/cart.ts:8"]);
});
it("a member after a closed type, inside its own class", async () => {
const item = (await locationItems([at(17, cart[17]!.indexOf("total"))]))[0]!;
expect([item.label, item.detail]).toEqual(["total", "Cart · src/cart.ts:18"]);
});
it("indentation-delimited bodies: a function after a class, a method after a dict literal", async () => {
const lines = [
"class Config:",
" defaults = {}",
"",
" def load(self) -> None:",
" pass",
"",
"def main() -> None:",
" pass",
];
readManyFileLines.mockResolvedValue(new Map([["/p/src/mod.py", lines]]));
const items = await locationItems([target("/p/src/mod.py", "load", 3), target("/p/src/mod.py", "main", 6)]);
expect(items.map((i) => i.detail)).toEqual(["Config · src/mod.py:4", "src/mod.py:7"]);
const main = {
...target("/p/src/mod.py", "main", 6),
range: { start: { line: 6, col: 0 }, end: { line: 6, col: 3 } },
};
expect((await locationItems([main]))[0]!.detail).toBe("src/mod.py:7");
});
it("Go: a method's container is its receiver, declared outside the struct's body", async () => {
const lines = [
"type Square struct {",
"\tside float64",
"}",
"",
"func (s *Square) Area() float64 {",
"\treturn 0",
"}",
];
readManyFileLines.mockResolvedValue(new Map([["/p/shapes.go", lines]]));
const at = { path: "/p/shapes.go", uri: null, range: { start: { line: 4, col: 17 }, end: { line: 4, col: 21 } } };
expect((await locationItems([at]))[0]!.detail).toBe("Square · shapes.go:5");
});
});
it("does not query the index for index symbols, which carry their container", async () => {
readManyFileLines.mockResolvedValue(new Map());
project("/p");
+61 -13
View File
@@ -172,41 +172,89 @@ const GO_RECEIVER = /^\s*func\s*\(\s*(?:[\p{L}_][\p{L}\p{N}_]*\s+)?\*?\s*([\p{L}
const FENCES = [`"""`, `'''`];
/** Code of a line without comments, strings and docstring text; null for a line with no code. */
type CodeLine = string | null;
/**
* Name of the type a target sits in (the nearest type declaration above it); null without one.
* Name of the type a target sits in (the nearest type declaration above it whose body is still
* open at the target); null without one.
* Text heuristic: docstrings (`"""` / `'''` fences) and line comments (`#`, `//`, `*`…) cannot
* declare a type, so "the base class does all that is needed" in a comment is not one.
*/
export function enclosingType(lines: readonly string[] | null | undefined, target: Location): string | null {
if (!lines) return null;
let container: string | null = null;
const targetLine = lines[target.range.start.line] ?? "";
const receiver = GO_RECEIVER.exec(targetLine)?.[1];
if (receiver) return receiver;
const from = Math.max(0, target.range.start.line - 2000);
const code: CodeLine[] = [];
const declarations: { line: number; end: number; name: string }[] = [];
let fence: string | null = null;
for (let l = Math.max(0, target.range.start.line - 2000); l < target.range.start.line; l++) {
for (let l = from; l < target.range.start.line; l++) {
const line = lines[l] ?? "";
code.push(null);
if (fence) {
if ((line.split(fence).length - 1) % 2 === 1) fence = null;
continue;
}
// Comments first: a `#`/`//` line cannot open a docstring fence either.
const code = line.replace(/(^|\s)(#|\/\/).*$/, "$1");
if (!code.trim()) continue;
const opened = FENCES.find((f) => (code.split(f).length - 1) % 2 === 1);
const text = line.replace(/(^|\s)(#|\/\/).*$/, "$1");
if (!text.trim()) continue;
const opened = FENCES.find((f) => (text.split(f).length - 1) % 2 === 1);
if (opened) {
fence = opened;
continue;
}
// A single-line docstring (fences open and close on the line) is text too.
if (FENCES.some((f) => code.includes(f))) continue;
const m = TYPE_DECLARATION.exec(code);
if (m && !/^\s*(\*|\/\*)/.test(line)) container = (m[1] ?? m[2])!;
if (FENCES.some((f) => text.includes(f)) || /^\s*(\*|\/\*)/.test(line)) continue;
code[l - from] = text;
const m = TYPE_DECLARATION.exec(text);
if (m) declarations.push({ line: l - from, end: m.index + m[0].length, name: (m[1] ?? m[2])! });
}
return container;
code.push(targetLine);
const col = target.range.start.col;
for (const d of declarations.reverse()) if (bodyHolds(code, d.line, d.end, col)) return d.name;
return null;
}
/** Name of the type a target sits in: the nearest type declaration above it, else the file name. */
const STRING_LITERAL = /"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`/g;
/**
* Whether the body of the declaration on `code[line]` (ending at `end`) is still open at `col`
* of the last entry of `code` (the target's line): braces when the body opens with one on the
* declaration's line or the next (Allman style), else indentation (Python, Ruby, a declaration
* without a body).
*/
function bodyHolds(code: readonly CodeLine[], line: number, end: number, col: number): boolean {
const last = code.length - 1;
const next = code.findIndex((c, i) => i > line && i < last && c !== null);
const braced = code[line]!.slice(end).includes("{") || (next > 0 && /^\s*\{/.test(code[next]!));
if (braced) {
let depth = 0;
let opened = false;
for (let i = line; i <= last; i++) {
const text = (i === line ? code[i]!.slice(end) : i === last ? code[i]!.slice(0, col) : code[i]) ?? "";
for (const c of text.replace(STRING_LITERAL, "")) {
if (c === "{") {
depth++;
opened = true;
} else if (c === "}" && --depth === 0 && opened) return false;
}
}
return depth > 0;
}
const indent = (s: string) => s.length - s.trimStart().length;
const own = indent(code[line]!);
for (let i = line + 1; i < code.length; i++) {
const text = code[i];
// A wrapped header (`) : Base {`) continues the declaration.
if (text?.trim() && indent(text) <= own && !/^\s*[)\]]/.test(text)) return false;
}
return true;
}
/** Name of the type a target sits in: the type declaration around it, else the file name. */
export function enclosingTypeName(lines: readonly string[] | null | undefined, target: Location): string {
const receiver = GO_RECEIVER.exec(lines?.[target.range.start.line] ?? "")?.[1];
if (receiver) return receiver;
const found = enclosingType(lines, target);
if (found) return found;
const file = target.path.split(/[\\/]/).pop() ?? target.path;
+44 -11
View File
@@ -130,6 +130,8 @@ export interface ComposerProps {
onSubmit: (now: boolean) => void;
/** Opens the per-session MCP servers picker when `/mcp` is run. */
onOpenMcp?: () => void;
/** Opens the per-session skills picker when `/skills` is run. */
onOpenSkills?: () => void;
disabled?: boolean;
autoFocus?: boolean;
/** A request from this host to focus its input without changing the selection. */
@@ -514,17 +516,26 @@ export function Composer(props: ComposerProps) {
...rest,
];
}
const openPickerCommands: AgentCommand[] = [];
if (props.onOpenMcp && !props.commands.some((c) => c.name === "mcp")) {
openPickerCommands.push({
name: "mcp",
description: tx("Configure MCP servers for this session"),
hint: null,
source: "command" as const,
});
}
if (props.onOpenSkills && !props.commands.some((c) => c.name === "skills")) {
openPickerCommands.push({
name: "skills",
description: tx("Configure skills for this session"),
hint: null,
source: "command" as const,
});
}
const availableCommands =
props.onOpenMcp && completion.query.length > 0 && !props.commands.some((c) => c.name === "mcp")
? [
{
name: "mcp",
description: tx("Configure MCP servers for this session"),
hint: null,
source: "command" as const,
},
...props.commands,
]
completion.query.length > 0 && openPickerCommands.length > 0
? [...openPickerCommands, ...props.commands]
: props.commands;
const out: Item[] = [];
let source: "command" | "skill" | undefined;
@@ -537,7 +548,18 @@ export function Composer(props: ComposerProps) {
out.push({ kind: "command", command });
}
return out;
}, [completion, files, shellFound, shellQuery, recentCommands, props.history, props.commands, props.onOpenMcp, tx]);
}, [
completion,
files,
shellFound,
shellQuery,
recentCommands,
props.history,
props.commands,
props.onOpenMcp,
props.onOpenSkills,
tx,
]);
const activeIndex = items[active] && !isSection(items[active]!) ? active : firstSelectable(items, isSection);
const open = !!completion && items.some((item) => !isSection(item));
const anchorAt = open ? completion.to : null;
@@ -629,6 +651,11 @@ export function Composer(props: ComposerProps) {
setCompletion(null);
props.onOpenMcp();
return;
} else if (item.command.name === "skills" && props.onOpenSkills) {
replace(completion.from, completion.to, "");
setCompletion(null);
props.onOpenSkills();
return;
} else {
const next = applyCompletion(current, completion, `/${item.command.name}`);
setText(next.text, next.caret);
@@ -980,6 +1007,12 @@ export function Composer(props: ComposerProps) {
props.onOpenMcp();
return handled();
}
if (props.onOpenSkills && view.state.doc.toString().trim() === "/skills") {
setText("");
setCompletion(null);
props.onOpenSkills();
return handled();
}
if (!props.disabled) props.onSubmit(send === "now");
recalled.current = { index: -1, stash: "" };
return handled();
+22 -1
View File
@@ -15,6 +15,7 @@ import { canSend, emptyDraft } from "./composerModel";
import { ConfigPickers } from "./ConfigPickers";
import { HermesProfilePicker } from "./HermesProfilePicker";
import { McpPicker } from "./McpPicker";
import { SkillsPicker } from "./SkillsPicker";
import { useEffortFocus } from "./effortFocus";
import { useAgentFontZoomSurface } from "./fontZoom";
import { HOME_KEY, providerIcon } from "./model";
@@ -27,6 +28,7 @@ import {
refreshProviders,
refreshModels,
setDraftMcpOverrides,
setDraftSkillOverrides,
setDraftOption,
startTask,
updateDraft,
@@ -66,6 +68,7 @@ export function HomeEditor({ docked = false, input }: { docked?: boolean; input?
const [error, setError] = useState<string | null>(null);
const [starting, setStarting] = useState(false);
const [mcpOpenRequest, setMcpOpenRequest] = useState(0);
const [skillsOpenRequest, setSkillsOpenRequest] = useState(0);
// Kept mounted while another tab shows: what changed meanwhile is read again when it shows.
const shown = useEditorShown();
@@ -163,6 +166,7 @@ export function HomeEditor({ docked = false, input }: { docked?: boolean; input?
(!project?.workspace || repoState?.root === root);
const openMcp = () => setMcpOpenRequest((n) => n + 1);
const openSkills = () => setSkillsOpenRequest((n) => n + 1);
// The agent shows as its icon; its name and version are in the tooltip.
const agentTitle = [provider?.name ?? tx("Agent"), probe?.version].filter(Boolean).join(" ");
@@ -208,8 +212,16 @@ export function HomeEditor({ docked = false, input }: { docked?: boolean; input?
onConfig={setDraftOption}
onSubmit={start}
onOpenMcp={openMcp}
onOpenSkills={openSkills}
disabled={!canStart}
addMenu={provider ? [{ id: "mcp", label: "MCP Servers…", icon: "plugin", run: openMcp }] : undefined}
addMenu={
provider
? [
{ id: "mcp", label: "MCP Servers…", icon: "plugin", run: openMcp },
{ id: "skills", label: "Skills…", icon: "bulb", run: openSkills },
]
: undefined
}
toolbar={
<>
<span className={styles.agentPicker} {...tooltipAttrs(agentTitle, undefined, true)}>
@@ -270,6 +282,15 @@ export function HomeEditor({ docked = false, input }: { docked?: boolean; input?
hideTrigger
/>
)}
{provider && (
<SkillsPicker
provider={provider.id}
overrides={draft.skillOverrides}
onChange={setDraftSkillOverrides}
openRequest={skillsOpenRequest}
hideTrigger
/>
)}
</>
}
actions={
@@ -357,3 +357,56 @@ describe("SessionAssets component", () => {
expect(await screen.findByRole("button", { name: "1 Artifact" })).toBeInTheDocument();
});
});
describe("SessionAssets binary file artifacts", () => {
const entries: AgentEntry[] = [
{
type: "tool",
id: "t-doc",
title: "Write spec",
kind: "edit",
status: "completed",
locations: ["/repo/spec.docx"],
output: null,
diffs: [{ path: "/repo/spec.docx", added: 1, removed: 0 }],
},
];
beforeEach(() => {
vi.clearAllMocks();
resetSessionAssetsCacheForTests();
clearDismissedAssets("task-1");
useAgents.setState({ composers: new Map([["task-1", emptyDraft()]]) });
vi.spyOn(ipc, "isTauri").mockReturnValue(true);
vi.spyOn(ipc, "call").mockImplementation(async (promise) => promise);
vi.spyOn(ipc.commands, "vcsRemotes").mockResolvedValue([] as never);
});
afterEach(() => {
vi.restoreAllMocks();
});
async function openArtifact() {
render(<SessionAssets task={makeTask()} entries={entries} head="feat/session" />);
fireEvent.click(await screen.findByRole("button", { name: "1 Artifact" }));
const dialog = await screen.findByRole("dialog", { name: "Artifacts" });
fireEvent.click(within(dialog).getByText("spec.docx"));
}
it("opens a binary file with its application through the backend's checked command", async () => {
const open = vi.spyOn(ipc.commands, "fsOpenWithSystem").mockResolvedValue(null as never);
await openArtifact();
await waitFor(() => expect(open).toHaveBeenCalledWith("/repo/spec.docx"));
expect(openFileMock).not.toHaveBeenCalled();
});
it("falls back to the editor when the backend refuses the launch", async () => {
vi.spyOn(console, "warn").mockImplementation(() => {});
const open = vi
.spyOn(ipc.commands, "fsOpenWithSystem")
.mockRejectedValue({ kind: "unavailable", message: "Project is in Restricted Mode." } as never);
await openArtifact();
await waitFor(() => expect(openFileMock).toHaveBeenCalledWith("/repo/spec.docx", { focus: true }));
expect(open).toHaveBeenCalledWith("/repo/spec.docx");
});
});
+2 -9
View File
@@ -5,6 +5,7 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { AgentEntry, AgentTask, PullRequestSummary } from "@/bindings";
import { call, commands, isTauri, onIdeEvent } from "@/platform/ipc";
import { openWithSystemApp } from "@/platform/fileManager";
import { useTx } from "@/platform/i18n";
import { openExternalUrl } from "@/platform/openUrl";
import { useProject } from "@/platform/project";
@@ -148,15 +149,7 @@ function issueIcon(state: IssueAssetState | undefined): IconName {
}
async function openFileArtifact(artifact: Extract<SessionArtifact, { kind: "file" }>) {
if (artifact.externalBinary && isTauri()) {
try {
const { openPath } = await import("@tauri-apps/plugin-opener");
await openPath(artifact.path);
return;
} catch {
/* fall back to editor */
}
}
if (artifact.externalBinary && (await openWithSystemApp(artifact.path))) return;
await editorService().openFile(artifact.path, { focus: true });
}
+334
View File
@@ -0,0 +1,334 @@
.page {
display: flex;
flex-direction: column;
gap: var(--space-2);
font-size: var(--fs-ui);
color: var(--fg-strong);
}
.header {
display: flex;
align-items: center;
justify-content: space-between;
flex-wrap: wrap;
gap: var(--space-2);
}
.headerActions {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: var(--space-1-5);
}
.title {
margin: 0;
font-size: 16px;
font-weight: 600;
color: var(--fg-strong);
}
.lead {
margin: 0;
color: var(--fg-muted);
line-height: 1.45;
}
.link {
padding: 0;
border: none;
background: none;
color: var(--link);
font: inherit;
cursor: pointer;
}
.link:hover {
text-decoration: underline;
}
.topControls {
display: flex;
flex-direction: column;
gap: var(--space-2);
}
.tabBar {
border-bottom: 1px solid var(--border);
}
.search {
width: 100%;
}
.error {
display: flex;
align-items: flex-start;
gap: var(--space-1-5);
padding: 6px 8px;
border-radius: var(--radius-control);
background: color-mix(in srgb, var(--danger) 12%, transparent);
color: var(--danger);
font-size: var(--fs-small);
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.sections {
display: flex;
flex-direction: column;
gap: var(--space-3);
}
.section {
display: flex;
flex-direction: column;
gap: var(--space-1-5);
}
.sectionBar {
display: flex;
align-items: center;
justify-content: space-between;
min-height: 28px;
padding: 2px 2px;
gap: var(--space-2);
}
.sectionToggle {
display: flex;
align-items: center;
gap: var(--space-1-5);
flex: 1;
min-width: 0;
padding: 4px 2px;
border: none;
background: none;
color: var(--fg-strong);
font: inherit;
font-weight: 600;
text-align: left;
cursor: pointer;
}
.chevron {
color: var(--fg-muted);
flex-shrink: 0;
}
.sectionTitle {
font-size: var(--fs-ui);
font-weight: 600;
}
.sectionHint {
color: var(--fg-muted);
font-size: var(--fs-small);
font-weight: 400;
}
.badge {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 18px;
height: 18px;
padding: 0 6px;
border-radius: 999px;
background: var(--bg-hover);
color: var(--fg-muted);
font-size: 11px;
font-weight: 600;
line-height: 1;
}
.sectionBody {
display: flex;
flex-direction: column;
gap: var(--space-1-5);
}
.emptyBox {
padding: 12px 14px;
border-radius: var(--radius-control);
background: var(--bg-elev);
box-shadow: inset 0 0 0 1px var(--border);
color: var(--fg-muted);
font-size: var(--fs-small);
}
/* Expandable skill card, mirroring the MCP server card. */
.card {
display: flex;
flex-direction: column;
border-radius: var(--radius-control);
background: var(--bg-elev);
box-shadow: inset 0 0 0 1px var(--border);
overflow: hidden;
}
.cardHeader {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-2);
padding: 8px 10px;
}
.cardHeader:hover {
background: var(--bg-hover);
}
.cardExpandBtn {
display: flex;
align-items: center;
gap: var(--space-2);
flex: 1;
min-width: 0;
padding: 0;
border: 0;
background: none;
color: inherit;
font: inherit;
text-align: left;
cursor: pointer;
}
.cardMain {
display: flex;
flex-direction: column;
gap: var(--space-0-5);
min-width: 0;
flex: 1;
}
.cardTitleRow {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: var(--space-1-5);
min-width: 0;
}
.skillName {
font-weight: 600;
color: var(--fg-strong);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.tag {
display: inline-flex;
align-items: center;
gap: var(--space-1);
height: 18px;
padding: 0 6px;
border-radius: var(--radius-small, 3px);
background: var(--bg-floating-toolbar);
color: var(--fg-secondary);
font-size: var(--fs-tiny);
font-weight: 500;
white-space: nowrap;
}
.tagAccent {
background: color-mix(in srgb, var(--accent) 18%, var(--bg-elev));
color: var(--link);
}
.tagWarning {
background: color-mix(in srgb, var(--warning) 18%, var(--bg-elev));
color: var(--warning);
}
.subtitle {
color: var(--fg-muted);
font-size: var(--fs-small);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.rowActions {
display: flex;
align-items: center;
gap: var(--space-2);
flex-shrink: 0;
}
.modeControls {
display: flex;
align-items: center;
gap: var(--space-1-5);
}
.modeSelect {
min-width: 96px;
}
.scopeSelect {
min-width: 104px;
}
.statusDot {
width: 8px;
height: 8px;
border-radius: 50%;
flex-shrink: 0;
background: var(--control-off);
}
.statusOn {
background: var(--success);
}
.cardDrawer {
display: flex;
flex-direction: column;
gap: var(--space-2);
padding: 8px 12px 10px 28px;
border-top: 1px solid var(--border);
background: var(--bg-app);
font-size: var(--fs-small);
}
.metaGrid {
display: grid;
grid-template-columns: max-content minmax(0, 1fr);
gap: var(--space-1) var(--space-3);
align-items: baseline;
}
.metaLabel {
color: var(--fg-muted);
white-space: nowrap;
}
.metaValue {
color: var(--fg);
font-family: var(--font-mono);
overflow-wrap: anywhere;
}
.drawerFooter {
display: flex;
align-items: center;
justify-content: space-between;
flex-wrap: wrap;
gap: var(--space-2);
padding-top: 4px;
}
.drawerButtons {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: var(--space-1-5);
}
.hint {
color: var(--fg-muted);
font-size: var(--fs-small);
line-height: 1.4;
}
+139
View File
@@ -0,0 +1,139 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import type { AgentSkillMode, AgentSkillSource, AgentSkillState, McpScope, ProjectInfo } from "@/bindings";
import { useProject } from "@/platform/project";
import { SkillsPage, type SkillsBackend } from "./SkillsPage";
const state = (
name: string,
source: AgentSkillSource,
mode: AgentSkillMode = "auto",
partial: Partial<AgentSkillState["skill"]> = {},
): AgentSkillState => ({
skill: {
name,
description: `${name} helps with ${name} things`,
path: `/skills/${name}`,
source,
valid: true,
warnings: [],
...partial,
},
mode,
origin: mode === "off" ? "user" : mode === "slashOnly" ? "workspace" : "none",
});
const SKILLS: AgentSkillState[] = [
state("tdd", "workspace"),
state("impeccable", "user", "off"),
state("ux-flow", "claudeWorkspace", "slashOnly"),
state("playwright", "copilotUser"),
];
function backend(): SkillsBackend & { setModeCalls: Array<{ name: string; scope: McpScope; mode: AgentSkillMode }> } {
const setModeCalls: Array<{ name: string; scope: McpScope; mode: AgentSkillMode }> = [];
return {
setModeCalls,
list: vi.fn(async () => SKILLS),
setMode: vi.fn(async (name: string, scope: McpScope, mode: AgentSkillMode) => {
setModeCalls.push({ name, scope, mode });
return SKILLS.map((s) => (s.skill.name === name ? { ...s, mode } : s));
}),
};
}
/** Opens one row's select and picks an option by text. */
function pick(triggerLabel: string, option: string) {
fireEvent.click(screen.getByRole("button", { name: triggerLabel }));
fireEvent.click(within(screen.getByRole("listbox")).getByText(option));
}
afterEach(() => useProject.setState({ project: null }));
describe("SkillsPage", () => {
it("groups skills by source with their mode and validation tags", async () => {
render(<SkillsPage backend={backend()} />);
await waitFor(() => expect(screen.getByText("tdd")).toBeInTheDocument());
const workspace = screen.getByRole("region", { name: "Workspace" });
expect(within(workspace).getByText("tdd")).toBeInTheDocument();
expect(screen.getByRole("region", { name: "User" })).toBeInTheDocument();
expect(screen.getByRole("region", { name: "Claude Code" })).toBeInTheDocument();
expect(screen.getByRole("region", { name: "GitHub Copilot" })).toBeInTheDocument();
expect(screen.getAllByText("Slash only").length).toBeGreaterThan(0);
expect(screen.getByRole("button", { name: "Mode for impeccable" })).toHaveTextContent("Off");
expect(screen.queryByText("Valid")).not.toBeInTheDocument();
});
it("filters skills by search", async () => {
render(<SkillsPage backend={backend()} />);
await waitFor(() => expect(screen.getByText("tdd")).toBeInTheDocument());
fireEvent.change(screen.getByPlaceholderText("Type to search..."), { target: { value: "playwright" } });
expect(screen.getByText("playwright")).toBeInTheDocument();
expect(screen.queryByText("tdd")).not.toBeInTheDocument();
expect(screen.getByRole("region", { name: "GitHub Copilot" })).toBeInTheDocument();
expect(screen.queryByRole("region", { name: "Workspace" })).not.toBeInTheDocument();
});
it("limits the list to the chosen source tab", async () => {
render(<SkillsPage backend={backend()} />);
await waitFor(() => expect(screen.getByText("tdd")).toBeInTheDocument());
fireEvent.click(screen.getByRole("tab", { name: /Agent Folders/ }));
expect(screen.getByText("playwright")).toBeInTheDocument();
expect(screen.queryByText("tdd")).not.toBeInTheDocument();
expect(screen.queryByText("impeccable")).not.toBeInTheDocument();
});
it("sets a skill's mode in Global from its row", async () => {
const backendSpy = backend();
render(<SkillsPage backend={backendSpy} />);
await waitFor(() => expect(screen.getByText("tdd")).toBeInTheDocument());
pick("Mode for tdd", "Off");
await waitFor(() => expect(backendSpy.setModeCalls).toEqual([{ name: "tdd", scope: "user", mode: "off" }]));
await waitFor(() => expect(screen.getByRole("button", { name: "Mode for tdd" })).toHaveTextContent("Off"));
});
it("sets a skill's mode in the workspace scope", async () => {
const project = { root: "/proj", name: "Proj", trusted: true, isGit: true } as ProjectInfo;
useProject.setState({ project });
const backendSpy = backend();
render(<SkillsPage backend={backendSpy} />);
await waitFor(() => expect(screen.getByText("tdd")).toBeInTheDocument());
pick("Scope for tdd", "Workspace");
pick("Mode for tdd", "Slash only");
await waitFor(() =>
expect(backendSpy.setModeCalls).toEqual([{ name: "tdd", scope: "workspace", mode: "slashOnly" }]),
);
});
it("expands a row to its canonical path, validation result, and open action", async () => {
render(<SkillsPage backend={backend()} />);
await waitFor(() => expect(screen.getByText("tdd")).toBeInTheDocument());
fireEvent.click(screen.getByRole("button", { name: /^tdd/ }));
expect(await screen.findByText("/skills/tdd")).toBeInTheDocument();
expect(screen.getByText("SKILL.md is valid")).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Open SKILL.md" })).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Copy the path of tdd" })).toBeInTheDocument();
});
it("surfaces validation warnings of an invalid SKILL.md", async () => {
const invalid = [
state("broken", "workspace", "auto", {
valid: false,
warnings: ["the frontmatter name does not match the folder"],
}),
];
render(<SkillsPage backend={{ list: vi.fn(async () => invalid), setMode: vi.fn(async () => invalid) }} />);
await waitFor(() => expect(screen.getByText("broken")).toBeInTheDocument());
expect(screen.getByText("Invalid SKILL.md")).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: /^broken/ }));
expect(await screen.findByText(/does not match the folder/)).toBeInTheDocument();
expect(screen.queryByText("SKILL.md is valid")).not.toBeInTheDocument();
});
});
+420
View File
@@ -0,0 +1,420 @@
/**
* Settings › Agents › Skills: every skill the CLI folders expose in one list, grouped by the
* source it was discovered in (workspace, user, and each CLI's own folders, symlinked copies
* collapsed by the backend), with the auto / slash-only / off modes settable globally or per
* workspace, and an expandable inspector showing the canonical path and SKILL.md validation.
*/
import clsx from "clsx";
import { useCallback, useEffect, useMemo, useState } from "react";
import type { AgentSkillMode, AgentSkillState, McpScope } from "@/bindings";
import { revealInFileManager, revealInFileManagerLabel } from "@/platform/fileManager";
import { formatMessage, useTx } from "@/platform/i18n";
import { useProject } from "@/platform/project";
import { Button, Icon, IconButton, SearchField, Select, Tabs, T } from "@/ui";
import { editorService } from "@/workbench/contributions";
import { providerIcon } from "./model";
import {
SKILL_SOURCE_GROUPS,
defaultSkillsBackend,
isDiscoveredSource,
useSkillsCatalog,
type SkillsBackend,
} from "./skillsModel";
import styles from "./SkillsPage.module.css";
export { defaultSkillsBackend, type SkillsBackend };
type SourceTab = "all" | "workspace" | "user" | "cli";
/** A key of the source-group table (and so, a skill source). */
type SkillSource = keyof typeof SKILL_SOURCE_GROUPS;
const MODE_OPTIONS: ReadonlyArray<{ value: AgentSkillMode; label: string }> = [
{ value: "auto", label: "Auto" },
{ value: "slashOnly", label: "Slash only" },
{ value: "off", label: "Off" },
];
/** Groups a tab shows, in source precedence order. */
function groupsForTab(tab: SourceTab): readonly SkillSource[] {
const order = Object.keys(SKILL_SOURCE_GROUPS) as SkillSource[];
if (tab === "all") return order;
if (tab === "workspace") return order.filter((s) => s === "workspace" || s.endsWith("Workspace"));
if (tab === "user") return order.filter((s) => s === "user" || s.endsWith("User"));
return order.filter(isDiscoveredSource);
}
export function SkillsPage({ backend = defaultSkillsBackend }: { backend?: SkillsBackend }) {
const tx = useTx();
const hasProject = useProject((s) => !!s.project?.root);
const [tab, setTab] = useState<SourceTab>("all");
const [skills, setSkills] = useState<AgentSkillState[]>([]);
const [query, setQuery] = useState("");
const [error, setError] = useState<string | null>(null);
const [busyName, setBusyName] = useState<string | null>(null);
const [expanded, setExpanded] = useState<Record<string, boolean>>({});
const [collapsed, setCollapsed] = useState<Record<string, boolean>>({});
// The scope the row's mode selector writes to; defaults follow where the mode came from.
const [scopes, setScopes] = useState<Record<string, McpScope>>({});
const syncCatalog = useCallback(
(next: AgentSkillState[]) => {
setSkills(next);
if (backend === defaultSkillsBackend) {
useSkillsCatalog.setState({ skills: next, loaded: true });
}
},
[backend],
);
const load = useCallback(() => {
backend
.list()
.then((list) => {
syncCatalog(list);
setError(null);
})
.catch((e: unknown) => setError(e instanceof Error ? e.message : String(e)));
}, [backend, syncCatalog]);
useEffect(() => {
load();
}, [load]);
const filtered = useMemo(() => {
const q = query.trim().toLowerCase();
if (!q) return skills;
return skills.filter(
(s) =>
s.skill.name.toLowerCase().includes(q) ||
s.skill.description.toLowerCase().includes(q) ||
s.skill.path.toLowerCase().includes(q),
);
}, [skills, query]);
const grouped = useMemo(() => {
const order = groupsForTab(tab);
const map = new Map<SkillSource, AgentSkillState[]>();
for (const source of order) {
const items = filtered.filter((s) => s.skill.source === source);
if (items.length > 0) map.set(source, items);
}
return [...map.entries()];
}, [filtered, tab]);
const tabCount = (tab: SourceTab): number => {
if (tab === "all") return skills.length;
const sources = groupsForTab(tab);
return skills.filter((s) => (sources as readonly SkillSource[]).includes(s.skill.source)).length;
};
const setMode = async (state: AgentSkillState, scope: McpScope, mode: AgentSkillMode) => {
setBusyName(state.skill.name);
setError(null);
try {
const next = await backend.setMode(state.skill.name, scope, mode);
syncCatalog(next);
} catch (e: unknown) {
setError(e instanceof Error ? e.message : String(e));
load();
} finally {
setBusyName(null);
}
};
const scopeOf = (state: AgentSkillState): McpScope =>
scopes[state.skill.name] ?? (state.origin === "workspace" || state.origin === "trust" ? "workspace" : "user");
return (
<div className={styles.page}>
<div className={styles.header}>
<h2 className={styles.title}>
<T>Skills</T>
</h2>
<div className={styles.headerActions}>
<Button variant="secondary" onClick={load}>
<Icon name="refresh" size={14} /> <T>Rescan</T>
</Button>
</div>
</div>
<p className={styles.lead}>
<T>
Skills are SKILL.md folders the coding agents load: the workspace's and your user folders first, then what
each CLI discovers on its own. A mode set here never edits the skill's files, and a repo can quiet a global
skill without rules in AGENTS.md.
</T>
</p>
<div className={styles.topControls}>
<div className={styles.tabBar}>
<Tabs
variant="compact"
aria-label={tx("Skill sources")}
activeId={tab}
onSelect={(id) => setTab(id as SourceTab)}
items={[
{
id: "all",
label: tx("All Sources"),
text: tx("All Sources"),
trailing: <span className={styles.badge}>{skills.length}</span>,
},
{
id: "workspace",
label: tx("Workspace"),
text: tx("Workspace"),
trailing: <span className={styles.badge}>{tabCount("workspace")}</span>,
},
{
id: "user",
label: tx("User"),
text: tx("User"),
trailing: <span className={styles.badge}>{tabCount("user")}</span>,
},
{
id: "cli",
label: tx("Agent Folders"),
text: tx("Agent Folders"),
trailing: <span className={styles.badge}>{tabCount("cli")}</span>,
},
]}
/>
</div>
<SearchField
className={styles.search}
value={query}
onChange={setQuery}
placeholder={tx("Type to search...")}
aria-label={tx("Search skills")}
/>
</div>
{error && (
<div className={styles.error} role="alert">
<Icon name="error" size={14} />
<span>{error}</span>
</div>
)}
<div className={styles.sections}>
{grouped.map(([source, items]) => {
const group = SKILL_SOURCE_GROUPS[source];
const isCollapsed = collapsed[source];
return (
<section key={source} className={styles.section} aria-label={tx(group.label)}>
<div className={styles.sectionBar}>
<button
type="button"
className={styles.sectionToggle}
aria-expanded={!isCollapsed}
onClick={() => setCollapsed((prev) => ({ ...prev, [source]: !prev[source] }))}
>
<Icon name={isCollapsed ? "chevron-right" : "chevron-down"} size={14} className={styles.chevron} />
<span className={styles.sectionTitle}>{tx(group.label)}</span>
<span className={styles.badge}>{items.length}</span>
<span className={styles.sectionHint}>{group.paths}</span>
</button>
</div>
{!isCollapsed && (
<div className={styles.sectionBody} role="list">
{items.map((state) => (
<SkillCard
key={`${state.skill.source}:${state.skill.name}`}
state={state}
scope={scopeOf(state)}
hasProject={hasProject}
busy={busyName === state.skill.name}
isExpanded={!!expanded[`${state.skill.source}:${state.skill.name}`]}
onToggleExpand={() =>
setExpanded((prev) => ({
...prev,
[`${state.skill.source}:${state.skill.name}`]:
!prev[`${state.skill.source}:${state.skill.name}`],
}))
}
onScopeChange={(scope) => setScopes((prev) => ({ ...prev, [state.skill.name]: scope }))}
onModeChange={(mode) => void setMode(state, scopeOf(state), mode)}
/>
))}
</div>
)}
</section>
);
})}
{grouped.length === 0 && !error && (
<div className={styles.emptyBox}>
<T>
No skills found in .agents/skills, .openidea/skills, ~/.agents/skills, or the CLI folders of Claude Code,
GitHub Copilot, Codex, and Cursor.
</T>
</div>
)}
</div>
</div>
);
}
function SkillCard({
state,
scope,
hasProject,
busy,
isExpanded,
onToggleExpand,
onScopeChange,
onModeChange,
}: {
state: AgentSkillState;
scope: McpScope;
hasProject: boolean;
busy: boolean;
isExpanded: boolean;
onToggleExpand: () => void;
onScopeChange: (scope: McpScope) => void;
onModeChange: (mode: AgentSkillMode) => void;
}) {
const tx = useTx();
const { skill } = state;
const group = SKILL_SOURCE_GROUPS[skill.source];
return (
<div role="listitem" className={styles.card}>
<div className={styles.cardHeader}>
<button type="button" className={styles.cardExpandBtn} aria-expanded={isExpanded} onClick={onToggleExpand}>
<Icon name={isExpanded ? "chevron-down" : "chevron-right"} size={13} className={styles.chevron} />
<div className={styles.cardMain}>
<div className={styles.cardTitleRow}>
<span className={styles.skillName}>{skill.name}</span>
{state.mode === "off" ? (
<span className={styles.tag}>
<T>Off</T>
</span>
) : state.mode === "slashOnly" ? (
<span className={styles.tag}>
<T>Slash only</T>
</span>
) : (
<span className={styles.tag}>
<T>Auto</T>
</span>
)}
{state.origin === "user" && (
<span className={styles.tag}>
<T>Global</T>
</span>
)}
{state.origin === "workspace" && (
<span className={clsx(styles.tag, styles.tagAccent)}>
<T>Workspace</T>
</span>
)}
{state.origin === "trust" && (
<span className={clsx(styles.tag, styles.tagWarning)}>
<T>Untrusted workspace</T>
</span>
)}
{isDiscoveredSource(skill.source) && (
<span className={styles.tag}>
<T>CLI-discovered</T>
</span>
)}
{!skill.valid && (
<span className={clsx(styles.tag, styles.tagWarning)}>
<T>Invalid SKILL.md</T>
</span>
)}
</div>
{skill.description && (
<span className={styles.subtitle} title={skill.description}>
{skill.description}
</span>
)}
</div>
</button>
<div className={styles.rowActions}>
<div className={styles.modeControls}>
<Select
className={styles.scopeSelect}
variant="framed"
aria-label={tx`Scope for ${skill.name}`}
value={scope}
disabled={busy}
options={[
{ value: "user", label: tx("Global") },
...(hasProject ? [{ value: "workspace" as McpScope, label: tx("Workspace") }] : []),
]}
onChange={onScopeChange}
/>
<Select
className={styles.modeSelect}
variant="framed"
aria-label={tx`Mode for ${skill.name}`}
value={state.mode}
disabled={busy}
options={MODE_OPTIONS.map((o) => ({ value: o.value, label: tx(o.label) }))}
onChange={onModeChange}
/>
</div>
<span
className={clsx(styles.statusDot, state.mode !== "off" && styles.statusOn)}
title={state.mode === "off" ? tx("Off") : tx("Active")}
/>
</div>
</div>
{isExpanded && (
<div className={styles.cardDrawer}>
<div className={styles.metaGrid}>
<span className={styles.metaLabel}>
<T>Path</T>
</span>
<span className={styles.metaValue}>{skill.path}</span>
<span className={styles.metaLabel}>
<T>Validation</T>
</span>
<span className={styles.metaValue}>
{skill.valid
? tx("SKILL.md is valid")
: (skill.warnings.length > 0 ? skill.warnings : [tx("SKILL.md failed validation")]).join("; ")}
</span>
</div>
{isDiscoveredSource(skill.source) && group.agent && (
<span className={styles.hint}>
<Icon name={providerIcon(group.agent)} size={12} />{" "}
<T>
This CLI discovers the folder itself: off hides the skill from OpenIDEA's / menu and applies only where
the CLI supports disabling.
</T>
</span>
)}
<div className={styles.drawerFooter}>
<div className={styles.drawerButtons}>
<Button
variant="secondary"
onClick={() => void editorService().openFile(`${skill.path}/SKILL.md`, { focus: true })}
>
<Icon name="file" size={12} /> <T>Open SKILL.md</T>
</Button>
<Button variant="secondary" onClick={() => void revealInFileManager(skill.path)}>
<Icon name="folder" size={12} /> {tx(revealInFileManagerLabel())}
</Button>
</div>
<IconButton
icon="copy"
size="small"
title={tx("Copy path")}
aria-label={formatMessage(tx("Copy the path of {name}"), { name: skill.name })}
onClick={() => void navigator.clipboard.writeText(skill.path)}
/>
</div>
</div>
)}
</div>
);
}
+225
View File
@@ -0,0 +1,225 @@
.trigger {
display: inline-flex;
align-items: center;
gap: var(--space-1);
height: var(--h-control);
min-width: 0;
padding: 0 6px;
border: 0;
border-radius: var(--radius-control);
background: transparent;
color: var(--fg-secondary);
font: inherit;
white-space: nowrap;
cursor: pointer;
transition: background var(--dur-fast) var(--ease);
}
.trigger:hover,
.trigger[aria-expanded="true"] {
background: var(--bg-toolbar-hover);
color: var(--fg-strong);
}
.triggerLabel {
font-size: var(--fs-ui);
}
.triggerCount {
color: var(--fg-subtle);
font-size: var(--fs-small);
}
.overrideDot {
width: 6px;
height: 6px;
border-radius: 50%;
background: var(--accent);
flex-shrink: 0;
}
.popup {
width: min(352px, calc(100vw - 24px));
display: flex;
flex-direction: column;
padding: 8px 0 6px;
}
.header {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-2);
padding: 0 10px 6px 12px;
border-bottom: 1px solid var(--border);
}
.title {
font-weight: 600;
color: var(--fg-strong);
}
.headerActions {
display: flex;
align-items: center;
gap: var(--space-1);
}
.resetBtn {
padding: 2px 6px;
border: 0;
border-radius: var(--radius-small, 3px);
background: transparent;
color: var(--link);
font: inherit;
font-size: var(--fs-small);
cursor: pointer;
}
.resetBtn:hover {
background: var(--bg-hover);
}
.searchWrap {
padding: 6px 10px 2px;
}
.list {
display: flex;
flex-direction: column;
max-height: 340px;
overflow-y: auto;
padding: 4px 0;
}
.groupLabel {
padding: 6px 12px 2px;
color: var(--fg-muted);
font-size: var(--fs-tiny);
font-weight: 600;
letter-spacing: 0.03em;
text-transform: uppercase;
}
.row {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-2);
padding: 5px 10px 5px 12px;
}
.row:hover {
background: var(--bg-hover);
}
.rowInfo {
display: flex;
flex-direction: column;
gap: 1px;
min-width: 0;
flex: 1;
}
.rowTitle {
display: flex;
align-items: center;
gap: var(--space-1);
min-width: 0;
flex-wrap: wrap;
}
.name {
font-weight: 500;
color: var(--fg-strong);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.sub {
color: var(--fg-muted);
font-size: var(--fs-tiny);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.pill {
display: inline-flex;
align-items: center;
height: 16px;
padding: 0 5px;
border-radius: var(--radius-small, 3px);
background: var(--bg-floating-toolbar);
color: var(--fg-secondary);
font-size: 10px;
font-weight: 500;
}
.pillSession {
background: color-mix(in srgb, var(--accent) 20%, var(--bg-elev));
color: var(--link);
}
.rowControls {
display: flex;
align-items: center;
gap: var(--space-1-5);
flex-shrink: 0;
}
.dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--control-off);
flex-shrink: 0;
}
.dotOn {
background: var(--success);
}
.empty {
padding: 12px;
color: var(--fg-muted);
font-size: var(--fs-small);
text-align: center;
}
.inlineLink {
padding: 2px 6px;
border: 0;
border-radius: var(--radius-small, 3px);
background: var(--bg-elev);
box-shadow: inset 0 0 0 1px var(--border-button);
color: var(--fg-secondary);
font: inherit;
font-size: var(--fs-tiny);
cursor: pointer;
}
.inlineLink:hover {
background: var(--bg-hover);
color: var(--fg-strong);
}
.footer {
display: flex;
flex-direction: column;
gap: var(--space-1);
padding: 6px 12px 2px;
border-top: 1px solid var(--border);
color: var(--fg-muted);
font-size: var(--fs-tiny);
}
/* The composer is the nearest positioned box: its bottom-right corner. */
.hiddenAnchor {
position: absolute;
right: 0;
bottom: 0;
width: 0;
height: 0;
}
+141
View File
@@ -0,0 +1,141 @@
import { useState } from "react";
import { describe, expect, it, vi } from "vitest";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import type { AgentSkillMode, AgentSkillSource, AgentSkillState } from "@/bindings";
import { SkillsPicker } from "./SkillsPicker";
import type { SkillsBackend } from "./skillsModel";
const state = (name: string, source: AgentSkillSource, mode: AgentSkillMode): AgentSkillState => ({
skill: {
name,
description: `${name} helps with ${name} things`,
path: `/skills/${name}`,
source,
valid: true,
warnings: [],
},
mode,
origin: mode === "off" ? "user" : "none",
});
const SKILLS: AgentSkillState[] = [
state("tdd", "workspace", "auto"),
state("verify", "workspace", "slashOnly"),
state("impeccable", "user", "off"),
state("playwright", "copilotUser", "auto"),
];
function Harness({
provider = "copilot",
backend,
skills = SKILLS,
}: {
provider?: string;
backend?: SkillsBackend;
skills?: AgentSkillState[];
}) {
const [overrides, setOverrides] = useState<Record<string, AgentSkillMode>>({});
return (
<SkillsPicker
provider={provider}
overrides={overrides}
onChange={setOverrides}
backend={backend}
testData={{ skills }}
/>
);
}
describe("SkillsPicker", () => {
it("shows active counts, groups skills by source, and marks slash-only modes", async () => {
render(<Harness />);
const trigger = screen.getByRole("button", { name: "Skills" });
expect(trigger).toHaveTextContent("Skills3/4");
fireEvent.click(trigger);
expect(await screen.findByText("Session Skills")).toBeInTheDocument();
expect(screen.getByText("Workspace")).toBeInTheDocument();
expect(screen.getByText("User")).toBeInTheDocument();
expect(screen.getByText("GitHub Copilot")).toBeInTheDocument();
expect(screen.getByText("/Slash")).toBeInTheDocument();
expect(screen.getByText("playwright helps with playwright things")).toBeInTheDocument();
});
it("turns a skill off for the session, shows the Session pill, and resets", async () => {
const backend: SkillsBackend = { list: vi.fn(async () => SKILLS), setMode: vi.fn(async () => SKILLS) };
render(<Harness backend={backend} />);
fireEvent.click(screen.getByRole("button", { name: "Skills" }));
const playwright = await screen.findByRole("switch", { name: "Enable playwright for this session" });
expect(playwright).toHaveAttribute("aria-checked", "true");
fireEvent.click(playwright);
await waitFor(() => expect(screen.getByRole("button", { name: "Skills" })).toHaveTextContent("Skills2/4"));
expect(screen.getAllByText("Session")).toHaveLength(1);
fireEvent.click(screen.getByRole("button", { name: "Reset" }));
await waitFor(() => expect(screen.getByRole("button", { name: "Skills" })).toHaveTextContent("Skills3/4"));
expect(screen.queryByText("Session")).not.toBeInTheDocument();
});
it("leaves a skill the settings keep off to the settings page", async () => {
render(<Harness />);
fireEvent.click(screen.getByRole("button", { name: "Skills" }));
expect(screen.queryByRole("switch", { name: "Enable impeccable for this session" })).not.toBeInTheDocument();
expect(await screen.findByRole("button", { name: "Enable in Settings" })).toBeInTheDocument();
});
it("brings a session-off skill back with its toggle", async () => {
render(<Harness />);
fireEvent.click(screen.getByRole("button", { name: "Skills" }));
const tdd = await screen.findByRole("switch", { name: "Enable tdd for this session" });
fireEvent.click(tdd);
expect(screen.getByRole("button", { name: "Skills" })).toHaveTextContent("Skills2/4");
fireEvent.click(tdd);
expect(screen.getByRole("button", { name: "Skills" })).toHaveTextContent("Skills3/4");
expect(screen.queryByText("Session")).not.toBeInTheDocument();
});
it("filters skills by name, description, and path", async () => {
const more = [...SKILLS, state("hex-review", "codexUser", "auto"), state("release-notes", "cursorUser", "auto")];
render(<Harness skills={more} />);
fireEvent.click(screen.getByRole("button", { name: "Skills" }));
fireEvent.change(await screen.findByPlaceholderText("Filter skills…"), { target: { value: "playwright" } });
expect(screen.getByText("playwright")).toBeInTheDocument();
expect(screen.queryByText("tdd")).not.toBeInTheDocument();
fireEvent.change(screen.getByPlaceholderText("Filter skills…"), { target: { value: "/skills/tdd" } });
expect(screen.getByText("tdd")).toBeInTheDocument();
expect(screen.queryByText("playwright")).not.toBeInTheDocument();
});
it("stays honest about ACP agents, whose / menu OpenIDEA only filters", async () => {
render(<Harness provider="cursor-acp" />);
fireEvent.click(screen.getByRole("button", { name: "Skills" }));
expect(
await screen.findByText("This agent keeps its own / menu: off only stops OpenIDEA offering the skill."),
).toBeInTheDocument();
});
it("says nothing special for non-ACP agents", async () => {
render(<Harness provider="claude" />);
fireEvent.click(screen.getByRole("button", { name: "Skills" }));
expect(
screen.queryByText("This agent keeps its own / menu: off only stops OpenIDEA offering the skill."),
).not.toBeInTheDocument();
});
it("shows an empty state without skills", async () => {
render(<Harness skills={[]} />);
fireEvent.click(screen.getByRole("button", { name: "Skills" }));
expect(await screen.findByText("No skills found.")).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Skills" })).toHaveTextContent("Skills0");
});
});
+314
View File
@@ -0,0 +1,314 @@
/**
* Per-session skills picker for the New Task and Session composers: shows every discovered skill
* grouped by the folder it came from, lets the user turn skills off for this session only, reset
* session overrides, or jump to Settings › Agents › Skills.
*/
import clsx from "clsx";
import { useEffect, useMemo, useRef, useState } from "react";
import type { AgentSkillMode, AgentSkillState } from "@/bindings";
import { executeAction } from "@/platform/actions";
import { formatMessage, useTx } from "@/platform/i18n";
import { Icon, IconButton, Popup, SearchField, T, Toggle } from "@/ui";
import { SKILLS_PAGE } from "./model";
import { normalizeProviderId } from "./mcpModel";
import {
SKILL_SOURCE_GROUPS,
defaultSkillsBackend,
nextSkillOverrides,
refreshSkillsCatalog,
resolveSessionSkills,
useSkillsCatalog,
useSkillsCatalogSync,
type ResolvedSessionSkills,
type SessionSkillItem,
type SkillsBackend,
} from "./skillsModel";
import styles from "./SkillsPicker.module.css";
export interface SkillsPickerProps {
provider: string;
overrides: Readonly<Record<string, AgentSkillMode>> | undefined;
onChange: (nextOverrides: Record<string, AgentSkillMode>) => void;
disabled?: boolean;
/** True while the session is actively running a turn (changes apply on the next turn). */
busy?: boolean;
/** Bumped when `/skills` is invoked from the composer to open this popover. */
openRequest?: number;
/** No button of its own: opened only through `openRequest`, above the composer. */
hideTrigger?: boolean;
/** Optional overrides for unit tests. */
backend?: SkillsBackend;
testData?: {
skills: readonly AgentSkillState[];
};
}
/** The mode pill a row shows: what the session runs the skill as. */
function ModePill({ mode }: { mode: AgentSkillMode }) {
if (mode === "off") return null;
return <span className={styles.pill}>{mode === "slashOnly" ? <T>/Slash</T> : <T>Auto</T>}</span>;
}
export function SkillsPicker({
provider,
overrides,
onChange,
disabled = false,
busy = false,
openRequest = 0,
hideTrigger = false,
backend = defaultSkillsBackend,
testData,
}: SkillsPickerProps) {
const tx = useTx();
useSkillsCatalogSync(backend);
const catalogSkills = useSkillsCatalog((s) => s.skills);
const skills = testData?.skills ?? catalogSkills;
const [open, setOpen] = useState(false);
const [seenOpenRequest, setSeenOpenRequest] = useState(openRequest);
const [query, setQuery] = useState("");
const anchor = useRef<HTMLElement | null>(null);
const setAnchor = (el: HTMLElement | null) => {
anchor.current = el;
};
if (openRequest !== seenOpenRequest) {
setSeenOpenRequest(openRequest);
if (openRequest > 0 && !disabled) setOpen(true);
}
useEffect(() => {
if (openRequest > 0 && !disabled && !testData) {
void refreshSkillsCatalog(backend);
}
}, [openRequest, disabled, testData, backend]);
const toggleOpen = () => {
const next = !open;
if (next && !testData) void refreshSkillsCatalog(backend);
if (!next) setQuery("");
setOpen(next);
};
const resolved = useMemo(() => resolveSessionSkills(skills, overrides ?? {}), [skills, overrides]);
const q = query.trim().toLowerCase();
const matchesQuery = (item: SessionSkillItem) =>
!q ||
item.name.toLowerCase().includes(q) ||
item.state.skill.description.toLowerCase().includes(q) ||
item.state.skill.path.toLowerCase().includes(q);
const groups = resolved.groups
.map((group) => ({ ...group, items: group.items.filter(matchesQuery) }))
.filter((group) => group.items.length > 0);
const countLabel =
resolved.totalCount === 0
? "0"
: resolved.activeCount === resolved.totalCount
? String(resolved.activeCount)
: `${resolved.activeCount}/${resolved.totalCount}`;
const handleToggleItem = (item: Pick<SessionSkillItem, "name" | "defaultMode">, nextEnabled: boolean) => {
onChange(nextSkillOverrides(overrides, item, nextEnabled));
};
return (
<>
{hideTrigger ? (
// Pinned to the composer's bottom-right corner: the popover opens under the box, like its other pickers.
<span ref={setAnchor} className={styles.hiddenAnchor} aria-hidden />
) : (
<button
ref={setAnchor}
type="button"
disabled={disabled}
className={styles.trigger}
title={
resolved.overrideCount > 0
? formatMessage(tx("Skills ({active}/{total} active · {overrides} session overrides)"), {
active: resolved.activeCount,
total: resolved.totalCount,
overrides: resolved.overrideCount,
})
: formatMessage(tx("Skills ({active}/{total} active)"), {
active: resolved.activeCount,
total: resolved.totalCount,
})
}
aria-label={tx("Skills")}
aria-haspopup="dialog"
aria-expanded={open}
onClick={toggleOpen}
>
<Icon name="bulb" size={13} />
<span className={styles.triggerLabel}>Skills</span>
<span className={styles.triggerCount}>{countLabel}</span>
{resolved.overrideCount > 0 && <span className={styles.overrideDot} aria-hidden />}
</button>
)}
<Popup
open={open}
anchor={anchor}
placement={hideTrigger ? "bottom-end" : "top-start"}
offset={6}
onClose={() => {
setOpen(false);
setQuery("");
}}
aria-label={tx("Session Skills")}
className={styles.popup}
>
<div className={styles.header}>
<span className={styles.title}>
<T>Session Skills</T>
</span>
<div className={styles.headerActions}>
{resolved.overrideCount > 0 && (
<button type="button" className={styles.resetBtn} onClick={() => onChange({})}>
<T>Reset</T>
</button>
)}
<IconButton
icon="settings"
size="small"
title={tx("Skills…")}
aria-label={tx("Skills…")}
onClick={() => {
setOpen(false);
void executeAction("file.settings", SKILLS_PAGE);
}}
/>
</div>
</div>
{resolved.totalCount > 5 && (
<div className={styles.searchWrap}>
<SearchField
value={query}
onChange={setQuery}
placeholder={tx("Filter skills…")}
aria-label={tx("Filter skills")}
/>
</div>
)}
<div className={styles.list}>
{groups.map((group) => (
<GroupRows
key={group.source}
source={group.source}
items={group.items}
onToggle={(item, on) => handleToggleItem(item, on)}
onOpenSettings={() => {
setOpen(false);
void executeAction("file.settings", SKILLS_PAGE);
}}
/>
))}
{groups.length === 0 && (
<div className={styles.empty}>
{resolved.totalCount === 0 ? <T>No skills found.</T> : <T>No matching skills.</T>}
</div>
)}
</div>
<div className={styles.footer}>
<span>
{busy ? <T>Changes apply on the next message.</T> : <T>Toggles here apply to this session only.</T>}
</span>
{provider !== normalizeProviderId(provider) && (
<span>
<T>This agent keeps its own / menu: off only stops OpenIDEA offering the skill.</T>
</span>
)}
</div>
</Popup>
</>
);
}
function GroupRows({
source,
items,
onToggle,
onOpenSettings,
}: {
source: ResolvedSessionSkills["groups"][number]["source"];
items: readonly SessionSkillItem[];
onToggle: (item: SessionSkillItem, enabled: boolean) => void;
onOpenSettings: () => void;
}) {
const tx = useTx();
const group = SKILL_SOURCE_GROUPS[source];
return (
<>
<div className={styles.groupLabel} title={group.paths}>
{tx(group.label)}
</div>
{items.map((item) => (
<SessionSkillRow
key={item.name}
item={item}
onToggle={(on) => onToggle(item, on)}
onOpenSettings={onOpenSettings}
/>
))}
</>
);
}
function SessionSkillRow({
item,
onToggle,
onOpenSettings,
}: {
item: SessionSkillItem;
onToggle: (enabled: boolean) => void;
onOpenSettings: () => void;
}) {
const tx = useTx();
// The settings decide a skill that is off by default; the session only ever turns active skills off.
const locked = item.defaultMode === "off";
const enabled = item.mode !== "off";
return (
<div className={styles.row}>
<div className={styles.rowInfo}>
<div className={styles.rowTitle}>
<span className={styles.name}>{item.name}</span>
<ModePill mode={item.mode} />
{item.overridden && (
<span className={clsx(styles.pill, styles.pillSession)}>
<T>Session</T>
</span>
)}
</div>
{item.state.skill.description && (
<span className={styles.sub} title={item.state.skill.description}>
{item.state.skill.description}
</span>
)}
</div>
<div className={styles.rowControls}>
{locked ? (
<button type="button" className={styles.inlineLink} onClick={onOpenSettings}>
<T>Enable in Settings</T>
</button>
) : (
<>
<Toggle
checked={enabled}
aria-label={formatMessage(tx("Enable {name} for this session"), { name: item.name })}
onChange={onToggle}
/>
<span className={clsx(styles.dot, enabled && styles.dotOn)} aria-hidden />
</>
)}
</div>
</div>
);
}
+1
View File
@@ -21,6 +21,7 @@ export const AGENT_SETTINGS_DEFAULTS: ResolvedAgentSettings = {
newTaskApprovals: "bypass",
defaults: {},
mcpServers: {},
skills: {},
};
export function resolveAgentSettings(s: AgentSettings | null | undefined): ResolvedAgentSettings {
@@ -182,6 +182,18 @@ describe("New Task composer commands", () => {
expect(await screen.findByText("Session MCP Servers")).toBeInTheDocument();
});
it("opens the per-session skills picker when /skills is completed in the composer", async () => {
agentCommands.mockResolvedValue({ status: "ok", data: [] });
render(<HomeEditor />);
const box = screen.getByRole("textbox");
typeIn(box, "/sk");
const list = await screen.findByRole("listbox", { name: "Commands" });
expect(within(list).getByRole("option", { selected: true })).toHaveTextContent("/skills");
fireEvent.keyDown(box, { key: "Enter" });
expect(textOf(box)).toBe("");
expect(await screen.findByText("Session Skills")).toBeInTheDocument();
});
it("names the icon-only Start action and disables it while starting", async () => {
agentCommands.mockResolvedValue({ status: "ok", data: [] });
let finish!: (value: unknown) => void;
+2
View File
@@ -13,6 +13,8 @@ export const REGISTRY_PAGE = "agents.list";
export const AGENTS_GROUP = "Agents";
/** Settings › Agents › External MCP Servers: User and Workspace MCP configurations. */
export const MCP_PAGE = "agents.mcpServers";
/** Settings › Agents › Skills: every CLI's SKILL.md folders and their modes. */
export const SKILLS_PAGE = "agents.skills";
/** Settings › Agents › Command Permissions. */
export const POLICY_PAGE = "agents.policy";
+4 -2
View File
@@ -202,7 +202,8 @@ it("refreshes an existing chat's searchable model choices and switches through i
const modelButton = screen.getByRole("button", { name: "Model" });
fireEvent.click(modelButton);
expect(await screen.findByRole("alert")).toHaveTextContent("discovery offline");
expect(screen.getByRole("option", { name: "session-only" })).toBeVisible();
expect(screen.queryByRole("option", { name: "session-only" })).not.toBeInTheDocument();
expect(screen.getByRole("option", { name: /^old/ })).toBeVisible();
expect(screen.getByRole("option", { name: "second-cached" })).toBeVisible();
expect(backend.refresh.mock.calls).toEqual([["second", false, null]]);
expect(screen.queryByRole("option", { name: "big" })).not.toBeInTheDocument();
@@ -219,7 +220,8 @@ it("refreshes an existing chat's searchable model choices and switches through i
await act(async () => pending.resolve(ok(fresh)));
expect(modelButton).toHaveTextContent("old");
expect(screen.getByRole("option", { name: "session-only" })).toBeVisible();
expect(screen.queryByRole("option", { name: "session-only" })).not.toBeInTheDocument();
expect(screen.getByRole("option", { name: "fresh" })).toBeVisible();
expect(screen.getByRole("button", { name: /^Model settings:/ })).toHaveTextContent("low");
expect(screen.getByRole("button", { name: "Mode" })).toHaveTextContent("plan");
expect(screen.getByText("Earlier message")).toBeVisible();
+73 -24
View File
@@ -3,7 +3,7 @@ import { commitFileDiffData, openDiff, withChain, type DiffData } from "@/featur
import { repositoryPath } from "@/features/vcs/repositoryPaths";
import { tx } from "@/platform/i18n";
import { call, commands, onIdeEvent } from "@/platform/ipc";
import { basename, relativeDir } from "@/platform/project";
import { basename, dirname, relativeDir } from "@/platform/project";
import { fileIconName, Icon, IconButton, showContextMenu, Spinner, T, Tree } from "@/ui";
import { notifications } from "@/workbench/contributions";
import { confirm } from "@/workbench/messages";
@@ -97,7 +97,7 @@ export function useChangesOpen(
const NO_SELECTION: ReadonlySet<string> = new Set();
/** A row of the Changes pane: a group, a commit, or a file. */
/** A row of the Changes pane: a group, a commit, a repository, or a file. */
type ChangeRow =
| {
key: string;
@@ -109,8 +109,33 @@ type ChangeRow =
children: ChangeRow[];
}
| { key: string; type: "commit"; commit: AgentCommit; children: ChangeRow[] }
| { key: string; type: "repo"; root: string; children: ChangeRow[] }
| { key: string; type: "file"; change: AgentChange; commit?: AgentCommit };
/** `files` under a row per repository, when the task changed files in several. */
function byRepository(files: ChangeRow[], prefix: string): ChangeRow[] {
const roots = new Map<string, ChangeRow[]>();
for (const f of files) {
const root = f.type === "file" ? f.change.repo : null;
if (!root) return files;
roots.set(root, [...(roots.get(root) ?? []), f]);
}
if (roots.size < 2) return files;
return [...roots].map(([root, children]) => ({
key: `${prefix}repo:${root}`,
type: "repo" as const,
root,
children,
}));
}
/** The keys of the repository rows, at the top or in a group: shown open. */
function repositoryKeys(rows: readonly ChangeRow[]): string[] {
return rows
.flatMap((r) => (r.type === "group" ? r.children : [r]))
.flatMap((r) => (r.type === "repo" ? [r.key] : []));
}
function statsOf(changes: readonly AgentChange[]) {
return changes.reduce((n, c) => ({ added: n.added + c.added, removed: n.removed + c.removed }), {
added: 0,
@@ -124,11 +149,10 @@ function changeRows(
grouped: boolean,
): ChangeRow[] {
if (!grouped)
return uncommitted.map((change) => ({
key: change.path,
type: "file" as const,
change,
}));
return byRepository(
uncommitted.map((change) => ({ key: change.path, type: "file" as const, change })),
"",
);
const roots: ChangeRow[] = [];
if (uncommitted.length) {
roots.push({
@@ -137,11 +161,10 @@ function changeRows(
label: "Uncommitted",
count: uncommitted.length,
...statsOf(uncommitted),
children: uncommitted.map((change) => ({
key: `uncommitted:${change.path}`,
type: "file",
change,
})),
children: byRepository(
uncommitted.map((change) => ({ key: `uncommitted:${change.path}`, type: "file" as const, change })),
"uncommitted:",
),
});
}
if (commits.length) {
@@ -202,15 +225,12 @@ export function ChangesPane({
// Only the working files roll back; a commit's files are history.
const rollbackable = useMemo(() => {
const out = new Map<string, AgentChange>();
for (const root of rows) {
if (root.type === "file") {
if (!root.commit) out.set(root.key, root.change);
continue;
}
for (const child of root.children) {
if (child.type === "file" && !child.commit) out.set(child.key, child.change);
}
}
const walk = (row: ChangeRow) => {
if (row.type === "file") {
if (!row.commit) out.set(row.key, row.change);
} else if (row.type !== "commit") row.children.forEach(walk);
};
rows.forEach(walk);
return out;
}, [rows]);
// Selection keys that no longer name a working file (a commit's file, a stale row) don't count.
@@ -407,11 +427,17 @@ export function ChangesPane({
roots={rows}
getKey={(n) => n.key}
getLabel={(n) =>
n.type === "file" ? basename(n.change.path) : n.type === "commit" ? n.commit.summary : n.label
n.type === "file"
? basename(n.change.path)
: n.type === "commit"
? n.commit.summary
: n.type === "repo"
? basename(n.root)
: n.label
}
getChildren={(n) => (n.type === "file" ? undefined : n.children)}
isExpandable={(n) => n.type !== "file" && n.children.length > 0}
defaultExpanded={grouped ? ["group:uncommitted", "group:committed"] : undefined}
defaultExpanded={[...(grouped ? ["group:uncommitted", "group:committed"] : []), ...repositoryKeys(rows)]}
activateExpandable={(n) => n.type === "commit"}
selected={selected}
onSelectionChange={(sel, lead) => {
@@ -445,6 +471,23 @@ export function ChangesPane({
</span>
);
}
if (n.type === "repo") {
const files = n.children.flatMap((c) => (c.type === "file" ? [c.change] : []));
const stats = statsOf(files);
return (
<span className={styles.changeGroup} title={n.root}>
<Icon name="folder" size={14} />
<span className={styles.changeGroupName}>{basename(n.root)}</span>
<span
className={styles.muted}
>{`${files.length} ${tx(files.length === 1 ? "file" : "files")}`}</span>
<span className={styles.changeStat}>
{stats.added > 0 && <span className={styles.added}>+{stats.added}</span>}{" "}
{stats.removed > 0 && <span className={styles.removed}>−{stats.removed}</span>}
</span>
</span>
);
}
if (n.type === "commit") {
const stats = statsOf(n.commit.files);
return (
@@ -468,7 +511,13 @@ export function ChangesPane({
<span className={styles.changeName} style={{ color: KIND_COLOR[n.change.kind] }}>
{basename(n.change.path)}
</span>
<span className={styles.changeDir}>{relativeDir(task.cwd, n.change.path)}</span>
<span className={styles.changeDir}>
{n.change.repo
? n.change.relPath.includes("/")
? dirname(n.change.relPath)
: ""
: relativeDir(task.cwd, n.change.path)}
</span>
<span className={styles.changeStat}>
{n.change.added > 0 && <span className={styles.added}>+{n.change.added}</span>}{" "}
{n.change.removed > 0 && <span className={styles.removed}>−{n.change.removed}</span>}
@@ -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,
@@ -185,18 +187,20 @@ export function SessionComposer({
: { ...catalogModel, current: task.model ?? catalogModel.current };
return [...task.config, recovered];
}
const candidateModels = catalogModel?.values;
if (!candidateModels?.length) return task.config;
const sessionModels = new Set(model.values.map((v) => v.value));
const extra = candidateModels.filter((v) => !sessionModels.has(v.value));
if (!extra.length) return task.config;
const pickerModel = { ...model, values: [...model.values, ...extra] };
return task.config.map((o) => (o === model ? pickerModel : o));
}, [task.config, task.model, model, catalogModel, canRefreshModels]);
// The agent's current catalog is what a chat can switch to. The session's own list only
// keeps the model it runs selectable when the catalog no longer offers it.
const offered = catalogModel?.values;
if (!offered?.length) return task.config;
const kept = model.values.filter(
(v) => (v.value === model.current || v.value === task.model) && !offered.some((o) => o.value === v.value),
);
return task.config.map((o) => (o === model ? { ...model, values: [...offered, ...kept] } : o));
}, [task.config, task.model, model, model?.current, catalogModel, canRefreshModels]);
const [sending, setSending] = useState(false);
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 +267,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 +312,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 +359,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={
+47 -1
View File
@@ -1935,6 +1935,7 @@ describe("session state across tasks and hosts", () => {
added: 8,
removed: 2,
oldPath: null,
repo: null,
},
];
localStorage.setItem("openidea.agents.changesOpen.v1", JSON.stringify({ A: true }));
@@ -2056,7 +2057,9 @@ describe("session state across tasks and hosts", () => {
entries.set(id, [{ type: "agent", text: `Reply ${id}` }]);
entries.set(`${id}/sub`, [{ type: "agent", text: `Sub ${id}` }]);
entryLoads.set(id, { error: "err" });
changes.set(id, [{ path: "a.ts", relPath: "a.ts", oldPath: null, kind: "modified", added: 1, removed: 0 }]);
changes.set(id, [
{ path: "a.ts", relPath: "a.ts", oldPath: null, repo: null, kind: "modified", added: 1, removed: 0 },
]);
scrollPositions.set(id, { top: 10, stick: false });
}
entries.set("gone", [{ type: "agent", text: "Deleted reply" }]);
@@ -2090,6 +2093,7 @@ describe("session state across tasks and hosts", () => {
added: 1,
removed: 0,
oldPath: null,
repo: null,
},
];
localStorage.setItem("openidea.agents.changesOpen.v1", JSON.stringify({ A: true }));
@@ -2868,6 +2872,7 @@ describe("accept changes", () => {
added: 8,
removed: 2,
oldPath: null,
repo: null,
},
];
localStorage.setItem("openidea.agents.changesOpen.v1", JSON.stringify({ A: true }));
@@ -2904,6 +2909,7 @@ describe("accept changes", () => {
added: 8,
removed: 2,
oldPath: null,
repo: null,
},
];
localStorage.setItem("openidea.agents.changesOpen.v1", JSON.stringify({ A: true }));
@@ -2922,6 +2928,7 @@ describe("last turn changes", () => {
added: 1,
removed: 0,
oldPath: null,
repo: null,
});
it("lists and rolls back only what the last turn changed, the session still counting the whole task", async () => {
@@ -2969,6 +2976,7 @@ describe("grouped changes", () => {
added: 1,
removed: 1,
oldPath: null,
repo: null,
});
const worktreeTask = () => {
useChangesOptions.setState({ groupByCommit: true });
@@ -3018,6 +3026,44 @@ describe("grouped changes", () => {
expect(screen.getByRole("button", { name: /1 commit/ })).toBeInTheDocument();
});
it("puts the files of a task across nested repositories under a row per repository", async () => {
const inRepo = (repo: string, rel: string): AgentChange => ({
...change(rel),
path: `/${repo}/${rel.slice(rel.indexOf("/") + 1)}`,
repo: `/${repo}`,
});
backend.changes = [inRepo("api", "api/src/a.ts"), inRepo("api", "api/b.ts"), inRepo("web", "web/c.ts")];
useAgents.setState({ tasks: new Map([["A", task("A")]]) });
localStorage.setItem("openidea.agents.changesOpen.v1", JSON.stringify({ A: true }));
render(<SessionEditor input={input("A")} />);
const pane = await screen.findByRole("complementary", { name: "Changes" });
await within(pane).findByText("a.ts");
// Open from the start, each repository leads its files, which show their folder as the agent names it.
const rows = [...pane.querySelectorAll("[data-row]")].map((r) => r.textContent);
expect(rows).toEqual(["api2 files+2 −2", "a.tsapi/src+1 −1", "b.tsapi+1 −1", "web1 file+1 −1", "c.tsweb+1 −1"]);
expect(within(pane).getByTitle("/api")).toBeInTheDocument();
fireEvent.mouseDown(within(pane).getByText("c.ts"));
fireEvent.click(within(pane).getByRole("button", { name: "Rollback Selected Changes…" }));
await waitFor(() => expect(backend.rolledBack).toEqual([["A", ["web/c.ts"], "sinceStart"]]));
});
it("lists a task's files without repository rows when they are all in one", async () => {
backend.changes = [
{ ...change("a.ts"), repo: "/project" },
{ ...change("b.ts"), repo: "/project" },
];
useAgents.setState({ tasks: new Map([["A", task("A")]]) });
localStorage.setItem("openidea.agents.changesOpen.v1", JSON.stringify({ A: true }));
render(<SessionEditor input={input("A")} />);
const pane = await screen.findByRole("complementary", { name: "Changes" });
expect(await within(pane).findByText("a.ts")).toBeInTheDocument();
expect(within(pane).queryByText("project")).toBeNull();
// A file at the top of the project names no folder.
expect([...pane.querySelectorAll("[data-row]")].map((r) => r.textContent)).toEqual(["a.ts+1 −1", "b.ts+1 −1"]);
});
it("accepts the task's committed work too, not only the uncommitted files", async () => {
backend.grouped = {
uncommitted: [],
+10 -2
View File
@@ -1,8 +1,8 @@
import { lazyComponent } from "@/ui";
import { registerSettingsPages } from "@/workbench/contributions";
import { AGENTS_GROUP, MCP_PAGE, POLICY_PAGE, REGISTRY_PAGE } from "./model";
import { AGENTS_GROUP, MCP_PAGE, POLICY_PAGE, REGISTRY_PAGE, SKILLS_PAGE } from "./model";
/** Settings › Agents › Coding Agents and Settings › Agents › External MCP Servers (also used by the Settings window). */
/** Settings › Agents › Coding Agents, External MCP Servers, Skills, and Command Permissions (also used by the Settings window). */
export function activateSettingsPages(): () => void {
return registerSettingsPages([
{
@@ -22,6 +22,14 @@ export function activateSettingsPages(): () => void {
keywords: ["mcp", "model context protocol", "servers", "tools", "agent"],
component: lazyComponent(() => import("./McpServersPage").then((m) => m.McpServersPage)),
},
{
id: SKILLS_PAGE,
title: "Skills",
group: AGENTS_GROUP,
order: 480,
keywords: ["skills", "skill", "skill.md", "agents", "slash commands", "auto", "slash only"],
component: lazyComponent(() => import("./SkillsPage").then((m) => m.SkillsPage)),
},
{
id: POLICY_PAGE,
title: "Command Permissions",
+140
View File
@@ -0,0 +1,140 @@
/**
* Shared agent-skills model behind Settings › Agents › Skills and the composer Skills picker:
* the discovered skills of every CLI with their resolved modes, and the per-session overrides
* (`AgentTask.skill_overrides`) on top of them.
*/
import { useEffect } from "react";
import { create } from "zustand";
import type { AgentSkillMode, AgentSkillSource, AgentSkillState, McpScope } from "@/bindings";
import { call, commands, isTauri, onIdeEvent } from "@/platform/ipc";
import { useProject } from "@/platform/project";
export interface SkillsBackend {
list(): Promise<AgentSkillState[]>;
setMode(name: string, scope: McpScope, mode: AgentSkillMode): Promise<AgentSkillState[]>;
}
export const defaultSkillsBackend: SkillsBackend = {
list: () => (typeof commands.agentSkillsList === "function" ? call(commands.agentSkillsList()) : Promise.resolve([])),
setMode: (name, scope, mode) => call(commands.agentSkillsSetMode(name, scope, mode)),
};
/** Which folder family a skill came from, with the paths it is discovered in. */
export const SKILL_SOURCE_GROUPS: Record<AgentSkillSource, { label: string; paths: string; agent: string | null }> = {
workspace: { label: "Workspace", paths: ".agents/skills · .openidea/skills", agent: null },
user: { label: "User", paths: "~/.agents/skills", agent: null },
claudeWorkspace: { label: "Claude Code", paths: ".claude/skills", agent: "claude" },
claudeUser: { label: "Claude Code", paths: "~/.claude/skills", agent: "claude" },
githubWorkspace: { label: "GitHub Copilot", paths: ".github/skills", agent: "copilot" },
copilotUser: { label: "GitHub Copilot", paths: "~/.copilot/skills · installed plugins", agent: "copilot" },
codexWorkspace: { label: "Codex", paths: ".codex/skills", agent: "codex" },
codexUser: { label: "Codex", paths: "~/.codex/skills", agent: "codex" },
cursorWorkspace: { label: "Cursor", paths: ".cursor/skills", agent: "cursor" },
cursorUser: { label: "Cursor", paths: "~/.cursor/skills", agent: "cursor" },
};
/** Skill folders the CLI discovers itself: OpenIDEA only reads them, and its "off" holds only where the CLI supports it. */
export function isDiscoveredSource(source: AgentSkillSource): boolean {
return source !== "workspace" && source !== "user";
}
export interface SessionSkillItem {
name: string;
state: AgentSkillState;
/** The mode the settings resolve to for this session, before any override. */
defaultMode: AgentSkillMode;
/** Effective mode for this session after applying `overrides`. */
mode: AgentSkillMode;
/** True when `overrides` explicitly diverges from the resolved policy. */
overridden: boolean;
}
export interface ResolvedSessionSkills {
groups: Array<{ source: AgentSkillSource; items: SessionSkillItem[] }>;
activeCount: number;
totalCount: number;
overrideCount: number;
}
/** Resolves the session's skills: the discovered list with its modes, then the session's overrides. */
export function resolveSessionSkills(
skills: readonly AgentSkillState[],
overrides: Readonly<Record<string, AgentSkillMode>> = {},
): ResolvedSessionSkills {
const items = skills.map<SessionSkillItem>((state) => {
const explicit = overrides[state.skill.name];
return {
name: state.skill.name,
state,
defaultMode: state.mode,
mode: explicit ?? state.mode,
overridden: explicit !== undefined && explicit !== state.mode,
};
});
const groups: ResolvedSessionSkills["groups"] = [];
const seen = new Set<AgentSkillSource>();
for (const item of items) {
if (seen.has(item.state.skill.source)) continue;
seen.add(item.state.skill.source);
groups.push({
source: item.state.skill.source,
items: items.filter((i) => i.state.skill.source === item.state.skill.source),
});
}
const activeCount = items.filter((i) => i.mode !== "off").length;
const overrideCount = items.filter((i) => i.overridden).length;
return { groups, activeCount, totalCount: items.length, overrideCount };
}
/** Computes the minimal `skillOverrides` map after toggling `name`: off pins `off`, on returns to the policy. */
export function nextSkillOverrides(
current: Readonly<Record<string, AgentSkillMode>> | undefined,
item: Pick<SessionSkillItem, "name" | "defaultMode">,
nextEnabled: boolean,
): Record<string, AgentSkillMode> {
const next = { ...(current ?? {}) };
if (nextEnabled) {
delete next[item.name];
} else {
next[item.name] = "off";
}
return next;
}
/** Shared window-level cache of the skills every CLI exposes, with their resolved modes. */
interface SkillsCatalogState {
skills: AgentSkillState[];
loaded: boolean;
}
export const useSkillsCatalog = create<SkillsCatalogState>(() => ({
skills: [],
loaded: false,
}));
let listenerAttached = false;
export async function refreshSkillsCatalog(backend: SkillsBackend = defaultSkillsBackend): Promise<void> {
if (!isTauri()) return;
const skills = await backend.list().catch(() => null);
if (skills) useSkillsCatalog.setState({ skills, loaded: true });
}
export function useSkillsCatalogSync(backend: SkillsBackend = defaultSkillsBackend): void {
const root = useProject((s) => s.project?.root);
useEffect(() => {
if (!isTauri()) return;
void refreshSkillsCatalog(backend);
const onFocus = () => void refreshSkillsCatalog(backend);
window.addEventListener("focus", onFocus);
if (!listenerAttached && typeof onIdeEvent === "function") {
listenerAttached = true;
onIdeEvent("settingsChanged", (e) => {
if (!e.key || e.key.startsWith("agents.skills")) {
void refreshSkillsCatalog(backend);
}
});
}
return () => window.removeEventListener("focus", onFocus);
}, [root, backend]);
}
+21
View File
@@ -16,6 +16,7 @@ import type {
AgentModelCatalog,
AgentPrompt,
AgentProvider,
AgentSkillMode,
AgentTask,
ExternalSession,
Isolation,
@@ -84,6 +85,8 @@ export interface Draft {
base: string | null;
/** Per-session MCP server enable/disable overrides (`server_name` -> `enabled`) for the next task. */
mcpOverrides?: Record<string, boolean>;
/** Per-session skill modes (`skill name` -> mode) for the next task. */
skillOverrides?: Record<string, AgentSkillMode>;
}
/** Composer key of the New Task page; sessions use their task id. */
@@ -1228,6 +1231,7 @@ export async function startTask(
isolation,
base: isolation === "worktree" ? draft.base : null,
mcpOverrides: draft.mcpOverrides ?? {},
skillOverrides: draft.skillOverrides ?? {},
// A `!` command runs in the new task before the agent hears anything.
idle: command !== null,
}),
@@ -1562,6 +1566,10 @@ export function setDraftMcpOverrides(mcpOverrides: Record<string, boolean>) {
updateDraft({ mcpOverrides });
}
export function setDraftSkillOverrides(skillOverrides: Record<string, AgentSkillMode>) {
updateDraft({ skillOverrides });
}
export async function setTaskMcpOverrides(task: string, overrides: Record<string, boolean>): Promise<void> {
const prev = useAgents.getState().tasks.get(task);
if (prev) {
@@ -1575,6 +1583,19 @@ export async function setTaskMcpOverrides(task: string, overrides: Record<string
}));
}
export async function setTaskSkillOverrides(task: string, overrides: Record<string, AgentSkillMode>): Promise<void> {
const prev = useAgents.getState().tasks.get(task);
if (prev) {
useAgents.setState((s) => ({
tasks: new Map(s.tasks).set(task, { ...prev, skillOverrides: overrides }),
}));
}
const updated = await call(commands.agentSetSkillOverrides(task, overrides));
useAgents.setState((s) => ({
tasks: new Map(s.tasks).set(task, updated),
}));
}
/** The composer the user is looking at: the Agents surface on show, else the one typed in last. */
function activeComposerKey(): string {
const s = useAgents.getState();
+7 -2
View File
@@ -287,8 +287,12 @@ describe("agent unread activity", () => {
.set("two", [{ type: "agent", text: "Answer two" }])
.set("open", [{ type: "agent", text: "Answer open" }]),
changes: new Map(s.changes)
.set("one", [{ path: "a.ts", relPath: "a.ts", oldPath: null, kind: "modified", added: 1, removed: 0 }])
.set("two", [{ path: "b.ts", relPath: "b.ts", oldPath: null, kind: "modified", added: 1, removed: 0 }]),
.set("one", [
{ path: "a.ts", relPath: "a.ts", oldPath: null, repo: null, kind: "modified", added: 1, removed: 0 },
])
.set("two", [
{ path: "b.ts", relPath: "b.ts", oldPath: null, repo: null, kind: "modified", added: 1, removed: 0 },
]),
groupedChanges: new Map(s.groupedChanges)
.set("one", { uncommitted: [], commits: [] })
.set("two", { uncommitted: [], commits: [] }),
@@ -513,6 +517,7 @@ describe("the diff of an agent change", () => {
added: 1,
removed: 1,
oldPath: null,
repo: null,
});
it("lists the task's other changed files, so F7 moves on to the next one", async () => {
@@ -16,22 +16,28 @@
border-bottom: 1px solid var(--border);
}
.module {
min-width: 160px;
max-width: 260px;
min-width: min(136px, 100%);
max-width: min(260px, 100%);
}
.search {
flex: 1 1 140px;
min-width: 140px;
min-width: min(140px, 100%);
max-width: 360px;
}
.scope {
min-width: 110px;
min-width: min(96px, 100%);
max-width: min(240px, 100%);
}
.sep {
width: 1px;
height: 16px;
margin: 0 2px;
background: var(--border);
.toolbarActions,
.viewActions {
display: flex;
align-items: center;
gap: var(--space-1);
flex: none;
}
.toolbarActions {
padding-inline-start: var(--space-1);
border-inline-start: 1px solid var(--border);
}
.banner {
flex: none;
@@ -60,13 +66,7 @@
flex: 1;
min-width: 0;
}
.panel {
display: flex;
flex-direction: column;
min-width: 0;
min-height: 0;
}
.panel > * {
.tree {
flex: 1;
min-height: 0;
}
@@ -94,7 +94,6 @@
}
.version {
flex: none;
font-family: var(--font-mono);
font-size: var(--fs-small);
color: var(--fg-secondary);
}
@@ -120,22 +119,24 @@
min-height: 0;
height: 100%;
}
.usagesHeader {
.paneHeader {
flex: none;
display: flex;
align-items: center;
gap: var(--space-1-5);
min-height: 32px;
min-height: calc(var(--h-field) + var(--space-1));
padding: 0 10px;
border-bottom: 1px solid var(--border);
}
.usagesTitle {
.paneTitle {
flex: 1;
min-width: 0;
margin: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-family: var(--font-mono);
font-size: var(--fs-ui);
font-weight: 500;
color: var(--fg-strong);
}
.conflictNote {
@@ -167,7 +168,6 @@
}
.usageVersion {
flex: none;
font-family: var(--font-mono);
color: var(--fg);
}
.usageStatus {
Loaded 100 of 159 files, more files were not shown because too many files have changed in this diff. Show more