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

..
Автор SHA1 Повідомлення Дата
l0ng-aiтаCursor bd37494ee8 fix(agents): keep composer toolbar on one row with dynamic overflow
Co-authored-by: Cursor <[email protected]>
2026-11-25 16:17:20 +08:00
guiqingle520 f597ae8c81 fix(project-tree): keep the error wavy underline from being clipped (#5820)
The Project view's label and label group hide overflow for the ellipsis, and the error label reserved only 2px below its text for an underline offset by 3px, so WebView2 clipped the wave into faint dots. The label group and the error label now reserve 4px above and below with a matching negative margin, which leaves the row height unchanged.

Closes #5802

Co-authored-by: guiqingle520 <[email protected]>
2026-11-25 16:11:42 +08:00
l0ng-ai eb036f2b67 fix(mcp): ask agents to read the workspace roots before their first project task (#5822)
The MCP server's instructions and get_workspace_roots only asked for the
roots when the user asked about directories or a change looked like it might
span projects. An agent that took its working directory for the whole
workspace never got there, and missed the projects attached in the IDE.

Both now say to call get_workspace_roots before the first project-related
operation in a session, and spell out what the answer means: projectRoot is
the project the connection serves and the default base for paths, roots is
the workspace scope to search and read rather than a list of projects to
change, and neither changes the agent's working directory or permissions.
The instructions also say to ask again after the user switches or attaches
a project. Clients that load tool descriptions lazily still see the rule in
the initialize instructions.

Fixes #5751
2026-11-25 16:10:45 +08:00
l0ng-ai ad95695588 fix(new-project): name a .NET project's top folder after its solution (#5819)
With "Create solution" checked and a solution name that differs from the
project name, the new project's top folder was still named after the project
(MyProject/MySolution.slnx, MyProject/MyProject/MyProject.csproj).

Generators can now give the project folder its own name with a `directory`
template; .NET uses the solution name, so the result is
MySolution/MySolution.slnx and MySolution/MyProject/MyProject.csproj. Without
a solution, or with an empty name, the folder is the project's as before. The
New Project dialog shows that folder in its path hint and checks it for an
existing non-empty folder.

Fixes #5732
2026-11-25 16:08:44 +08:00
l0ng-ai 9e6c29a7b7 fix(editor): highlight <style lang="less"> in Vue files with the Less grammar (#5818)
A Vue file's <style> block switched grammar only for lang="scss" and
lang="sass"; lang="less" was parsed as plain CSS, so Less variables,
nested rules and mixin calls lost their highlighting. It now uses
@codemirror/lang-less, which was already in the lockfile through
@codemirror/language-data and is now a direct dependency.

Fixes #5745
2026-11-25 16:03:55 +08:00
l0ng-ai 89fa6cb02c fix(maven): run the IDE's own Maven goals by plugin coordinates (#5814)
Offline, Maven resolves a plugin prefix (help:, dependency:) only from the
org.apache.maven.plugins group metadata in the local repository. A repository
filled from a private mirror often lacks it even when the plugin jar is there,
so every offline reload failed with "No plugin found for prefix 'help'".

The sync's effective POM and dependency tree, the resource and web build
probes (help:evaluate) and the single-file classpath probe
(dependency:build-classpath) now name the plugin by its coordinates: the
newest 3.x version already in the local repository the run resolves into
(-Dmaven.repo.local, then the -s settings, then the user's default), else a
pinned version. Offline with no cached dependency plugin, the tree still
falls back to the project's own version.

Fixes #5757
2026-11-25 15:57:02 +08:00
l0ng-ai 6f284741b3 fix(index): reconcile a changed folder one level deep and throttle snapshot refreshes (#5813)
A file changing at the project root put the root on the reconcile list, and the
reconcile walked it whole: every couple of seconds while a program wrote a log
there, the index re-read the entire project and rewrote its snapshot.

A reported folder the index already has files below is now listed one level
deep: its own files, plus subfolders that appeared (walked whole) or are gone
(their files dropped). Unknown folders are still walked whole. Snapshot
refreshes keep at least 10s apart; any index write drops the snapshot anyway,
so this only affects how fast the next startup is.

Fixes #5749
2026-11-25 15:51:23 +08:00
l0ng-ai 4b253d368e fix(index): don't show Indexing while a program writes its log in the project (#5812)
Every change the watcher reports queues its folder for a reconcile scan two seconds later, and every scan raised the Indexing flag and task. A debugged app writing to logs/ inside the project therefore kept Indexing in the status bar for as long as it ran. Subtree scans now run quietly and only show Indexing once they find 200 or more files to parse; full scans show it as before.

Part of #5792
2026-11-25 15:44:47 +08:00
l0ng-ai f274189c92 fix(plugins): keep the applied plugin theme over an older plugin list (#5811)
refreshPlugins' generation guard drops a list answered after a newer refresh, but not one answered after a themeChanged event. Opening a project refreshes the list while the plugin theme is being re-applied: the event set the plugin theme, then the earlier list arrived without an active theme and the editor fell back to the built-in dark theme while the menu still showed the plugin theme checked. Theme events and theme choices now go through setActivePluginTheme, which stamps them; a list requested before the latest stamp keeps the current active theme.

Fixes #5793
2026-11-25 15:42:36 +08:00
l0ng-aiтаCursor 5f17748295 fix(agents): unify per-model defaults and model settings list UI (#5806)
Co-authored-by: Cursor <[email protected]>
2026-11-25 15:40:42 +08:00
l0ng-ai 2d94628d1d fix(editor): Enter in an empty find bar no longer opens a second one (#5809)
CodeMirror's findNext / replaceNext / replaceAll open its own search panel when the query is empty or invalid. The find bar's Enter, F3, arrows and Replace buttons call them, so pressing Enter before typing showed CodeMirror's panel under ours. The wrappers in cm/find.ts now do nothing without a usable query, as findPrevious already did.

Fixes #5800
2026-11-25 15:40:38 +08:00
l0ng-ai 26aabf5229 fix(project): copy absolute Windows paths with backslashes (#5808)
Copy Absolute Path returned the UI's /-separated form, so C:/work/a.md went to the clipboard and cmd, robocopy and the Explorer address bar rejected it. pathToCopy now writes absolute drive and UNC paths with backslashes (new nativePath, the inverse of ipcPath); paths relative to a content or source root keep /. The editor's Absolute Path action and Search Everywhere's Copy Path go through the same conversion.

Fixes #5805
2026-11-25 15:38:15 +08:00
53 змінених файлів з 1635 додано та 497 видалено

No files matched your search

+2 -2
Переглянути файл
@@ -196,11 +196,11 @@ fn levels_for_model_from_slice(options: &[AgentConfigOption]) -> Vec<AgentConfig
.filter(|o| config::is_per_model_option(o))
.cloned()
.map(|mut o| {
if config::is_context_option(&o.id) {
if config::is_context_option(&o.id) || config::is_fast_option(&o.id) {
if o.category.is_none() {
o.category = Some("model_config".into());
}
} else if o.category.as_deref() != Some("thought_level") {
} else if o.category.is_none() {
o.category = Some("thought_level".into());
}
o
+4 -3
Переглянути файл
@@ -168,11 +168,12 @@ async fn discovery_reads_effort_and_fast_from_session_new_then_stops_the_agent()
assert_eq!(calls.iter().map(|(m, _)| m.as_str()).collect::<Vec<_>>(), ["initialize", "session/new"]);
assert_eq!(calls[1].1["mcpServers"], json!([]));
let cursor = mgr.providers().into_iter().find(|p| p.id == "cursor").unwrap();
let fast = cursor.config.iter().find(|o| o.id == "fast").expect("fast option");
// Per-model options (`effort`, `fast`, `context`) belong to the session's model, not provider-wide config.
assert!(!cursor.config.iter().any(|o| o.id == "fast"));
assert_eq!(cursor.thought_levels.keys().collect::<Vec<_>>(), ["m1"]);
let fast = cursor.thought_levels["m1"].iter().find(|o| o.id == "fast").expect("fast option");
assert_eq!(fast.category.as_deref(), Some("model_config"));
assert_eq!(fast.current.as_deref(), Some("false"));
// The effort option belongs to the session's model; m2 may offer other levels.
assert_eq!(cursor.thought_levels.keys().collect::<Vec<_>>(), ["m1"]);
assert!(cursor.thought_levels["m1"].iter().any(|o| o.category.as_deref() == Some("thought_level")));
}
+24 -6
Переглянути файл
@@ -15,6 +15,8 @@ use tokio::time::Instant;
const FRESH_FOR: Duration = Duration::from_secs(15 * 60);
const COOLDOWN: Duration = Duration::from_secs(30);
/// Persisted catalog layout version; bump when option classification changes so stale per-model entries re-discover.
const CATALOG_SCHEMA: u8 = 2;
type Store = Arc<Mutex<HashMap<String, Known>>>;
type Key = (PathBuf, PathBuf, String);
@@ -80,6 +82,8 @@ impl CatalogData {
pub(crate) struct SavedCatalog {
/// An opaque cryptographic digest, never raw launch arguments or credentials.
fingerprint: String,
#[serde(default)]
schema: u8,
#[serde(flatten)]
catalog: CatalogData,
}
@@ -111,7 +115,7 @@ impl LaunchContext {
hash.update(&(value.len() as u64).to_le_bytes());
hash.update(value);
}
field(&mut hash, b"openidea-model-catalog-v1");
field(&mut hash, b"openidea-model-catalog-v2");
field(
&mut hash,
match self.spec.driver {
@@ -200,7 +204,14 @@ impl AgentCatalogs {
cache
.get(provider)
.and_then(|known| known.catalogs.get(&shared.root_key()))
.map(|saved| saved.catalog.clone())
.map(|saved| {
let mut catalog = saved.catalog.clone();
if saved.schema < CATALOG_SCHEMA {
catalog.refreshed_at_ms = None;
catalog.thought_levels.clear();
}
catalog
})
.unwrap_or_default()
}
@@ -228,7 +239,8 @@ impl AgentCatalogs {
}
drop(state);
let cache = shared.known.lock();
cache.get(provider)?.catalogs.get(&shared.root_key())?.catalog.thought_levels.get(model).cloned()
let saved = cache.get(provider)?.catalogs.get(&shared.root_key())?;
(saved.schema >= CATALOG_SCHEMA).then(|| saved.catalog.thought_levels.get(model).cloned()).flatten()
}
pub(super) async fn load_levels(
@@ -281,7 +293,7 @@ impl AgentCatalogs {
AgentModelCatalog {
provider: provider.to_owned(),
config: shared.config_for_new_task(catalog.config, provider),
thought_levels: catalog.thought_levels,
thought_levels: shared.thought_levels_for_new_task(catalog.thought_levels, provider),
refreshing: entry.flight.is_some(),
refreshed_at_ms: catalog.refreshed_at_ms,
retry_at_ms: model_failure
@@ -318,7 +330,9 @@ impl AgentCatalogs {
let generation = state.generation;
let saved =
shared.known.lock().get(&spec.id).and_then(|known| known.catalogs.get(&shared.root_key())).cloned();
let matching = saved.as_ref().is_some_and(|saved| saved.fingerprint == context.fingerprint());
let matching = saved
.as_ref()
.is_some_and(|saved| saved.schema >= CATALOG_SCHEMA && saved.fingerprint == context.fingerprint());
let age = saved
.as_ref()
.filter(|_| matching)
@@ -489,7 +503,11 @@ impl AgentCatalogs {
}
known.catalogs.insert(
shared.root_key(),
SavedCatalog { fingerprint: entry.context.fingerprint(), catalog: catalog.clone() },
SavedCatalog {
fingerprint: entry.context.fingerprint(),
schema: CATALOG_SCHEMA,
catalog: catalog.clone(),
},
);
entry.catalog = Some(catalog);
shared.persist_known(&cache);
+99 -27
Переглянути файл
@@ -65,7 +65,7 @@ fn bypass_value(category: &str) -> Option<fn(&str) -> bool> {
}
/// Moves options that approve everything without asking to a value that asks: the agent's
/// default or ask mode, else its first one that asks.
/// own default (when it asks), else `default` or `ask`, else its first one that asks.
pub(crate) fn ask_for_approvals(config: &mut [AgentConfigOption]) {
for option in config {
let Some(bypass) = option.category.as_deref().and_then(bypass_value) else { continue };
@@ -73,9 +73,15 @@ pub(crate) fn ask_for_approvals(config: &mut [AgentConfigOption]) {
continue;
}
let asks = |v: &&AgentConfigValue| !bypass(&v.value);
let value = ["default", "ask"]
.iter()
.find_map(|preferred| option.values.iter().filter(asks).find(|v| v.value == *preferred))
let value = option
.default_value
.as_deref()
.and_then(|def| option.values.iter().filter(asks).find(|v| v.value == def))
.or_else(|| {
["default", "ask"]
.iter()
.find_map(|preferred| option.values.iter().filter(asks).find(|v| v.value == *preferred))
})
.or_else(|| option.values.iter().find(asks));
if let Some(value) = value {
option.current = Some(value.value.clone());
@@ -83,11 +89,26 @@ pub(crate) fn ask_for_approvals(config: &mut [AgentConfigOption]) {
}
}
/// The mode that approves everything without asking (`bypassPermissions`, `yolo`, `full-access`…), if the agent has one.
pub(crate) fn bypass_mode(options: &[AgentConfigOption]) -> Option<(&AgentConfigOption, &AgentConfigValue)> {
let option = options.iter().find(|o| o.category.as_deref() == Some("mode"))?;
let value = option.values.iter().find(|v| is_bypass_mode(&v.value))?;
Some((option, value))
/// Moves approval-bearing options (`mode`, `permissions`, `approval`) to their approving value.
pub(crate) fn apply_bypass_approvals(config: &mut [AgentConfigOption]) {
for option in config {
let Some(bypass) = option.category.as_deref().and_then(bypass_value) else { continue };
if let Some(value) = option.values.iter().find(|v| bypass(&v.value)) {
option.current = Some(value.value.clone());
}
}
}
/// Applies provider-specific defaults to per-model options for new tasks without altering `default_value`.
pub(crate) fn apply_model_defaults(provider: &str, options: &mut [AgentConfigOption]) {
if provider != "cursor" {
return;
}
if let Some(fast) = options.iter_mut().find(|o| is_fast_option(&o.id))
&& fast.values.iter().any(|v| v.value == "false")
{
fast.current = Some("false".into());
}
}
fn is_bypass_mode(mode: &str) -> bool {
@@ -126,14 +147,20 @@ pub(crate) fn options_of(result: &Value) -> Vec<AgentConfigOption> {
}
pub(crate) fn is_context_option(id: &str) -> bool {
matches!(id, "context_tier" | "contextTier")
matches!(id, "context" | "context_tier" | "contextTier")
}
pub(crate) fn is_fast_option(id: &str) -> bool {
id == "fast"
}
/// Whether an option's available values and default belong to the selected model
/// (`thought_level` and model context-tier options) rather than the provider as a whole.
/// (`thought_level`, `context_tier`, and `model_config` options like `context` and `fast`)
/// rather than the provider as a whole.
pub(crate) fn is_per_model_option(o: &AgentConfigOption) -> bool {
matches!(o.category.as_deref(), Some("thought_level" | "context_tier"))
matches!(o.category.as_deref(), Some("thought_level" | "context_tier" | "model_config"))
|| matches!(o.id.as_str(), "effort" | "reasoning_effort" | "thinking" | "reasoning")
|| is_fast_option(&o.id)
|| is_context_option(&o.id)
}
@@ -164,7 +191,7 @@ pub(crate) fn parse_options(options: &Value) -> Vec<AgentConfigOption> {
matches!(id.as_str(), "effort" | "reasoning_effort" | "thinking" | "reasoning")
.then(|| "thought_level".into())
})
.or_else(|| (id == "fast" || is_context_option(&id)).then(|| "model_config".into()))
.or_else(|| (is_fast_option(&id) || is_context_option(&id)).then(|| "model_config".into()))
}),
current,
default_value,
@@ -337,6 +364,11 @@ fn legacy(
}
}
fn clean_label(s: String, fallback: &str) -> String {
let trimmed = s.trim_matches(|c: char| c.is_whitespace() || matches!(c, '\u{200B}'..='\u{200D}' | '\u{FEFF}'));
if trimmed.is_empty() { fallback.to_owned() } else { trimmed.to_owned() }
}
fn value_of(v: &Value) -> Option<AgentConfigValue> {
let value = v.get("value")?.as_str()?.to_owned();
let meta = v.get("_meta");
@@ -352,7 +384,7 @@ fn value_of(v: &Value) -> Option<AgentConfigValue> {
.filter(|s| !s.is_empty())
.map(str::to_owned);
Some(AgentConfigValue {
name: str_of(v, "name").unwrap_or_else(|| value.clone()),
name: str_of(v, "name").map(|n| clean_label(n, &value)).unwrap_or_else(|| value.clone()),
description: str_of(v, "description"),
cost_category,
usage_multiplier,
@@ -434,19 +466,16 @@ mod tests {
]}
}));
assert!(bypass_approvals(&full_access));
assert_eq!(bypass_mode(&full_access).map(|(_, v)| v.value.as_str()), Some("full-access"));
let asking = options_of(&json!({
let mut asking = options_of(&json!({
"modes": {"currentModeId": "ask", "availableModes": [
{"id": "ask", "name": "Ask"}, {"id": "full-access", "name": "Full Access"}
]}
}));
assert!(!bypass_approvals(&asking));
assert_eq!(
bypass_mode(&asking).map(|(_, v)| v.value.as_str()),
Some("full-access"),
"the offered bypass mode stays available"
);
apply_bypass_approvals(&mut asking);
assert_eq!(asking[0].current.as_deref(), Some("full-access"));
assert!(bypass_approvals(&asking));
let permissions = |current: &str| {
options_of(&json!({"configOptions": [{
@@ -503,7 +532,7 @@ mod tests {
}
#[test]
fn effort_and_fast_categories_are_inferred_from_ids() {
fn effort_context_and_fast_are_per_model_options() {
let mut c = options_of(&json!({
"configOptions": [
{"id": "model", "type": "select", "currentValue": "gemini-4-carbon",
@@ -512,19 +541,39 @@ mod tests {
"_meta": {"copilotPriceCategory": "Medium", "copilotUsage": "1x"}}]},
{"id": "effort", "type": "select", "currentValue": "medium",
"options": [{"value": "low"}, {"value": "medium"}, {"value": "high"}]},
{"id": "context", "type": "select", "currentValue": "256k",
"options": [{"value": "256k", "name": "256K"}, {"value": "500k", "name": "500K"}]},
{"id": "contextTier", "type": "select", "currentValue": "default",
"options": [{"value": "default", "name": "200K"}, {"value": "long_context", "name": "1M"}]},
{"id": "fast", "type": "select", "currentValue": "false",
"options": [{"value": "false", "name": "Off"}, {"value": "true", "name": "On"}]}
{"id": "fast", "type": "select", "currentValue": "true",
"options": [{"value": "false", "name": "Off"}, {"value": "true", "name": "Fast\u{200b}\u{200b}"}]}
]
}));
assert_eq!(c.len(), 4);
assert_eq!(c.len(), 5);
assert_eq!(c[0].values[0].cost_category.as_deref(), Some("medium"));
assert_eq!(c[0].values[0].usage_multiplier.as_deref(), Some("1x"));
assert_eq!(c[1].category.as_deref(), Some("thought_level"));
assert_eq!(c[1].default_value.as_deref(), Some("medium"));
assert_eq!(c[2].category.as_deref(), Some("model_config"));
assert!(is_per_model_option(&c[1]) && is_per_model_option(&c[2]) && !is_per_model_option(&c[3]));
assert_eq!(c[3].category.as_deref(), Some("model_config"));
assert_eq!(c[4].category.as_deref(), Some("model_config"));
assert_eq!(c[4].values[1].name, "Fast");
assert!(
is_per_model_option(&c[1])
&& is_per_model_option(&c[2])
&& is_per_model_option(&c[3])
&& is_per_model_option(&c[4])
);
assert!(!is_per_model_option(&c[0]));
// Cursor defaults fast off for new tasks while preserving the agent's own default_value.
let mut cursor_opts = c.clone();
apply_model_defaults("cursor", &mut cursor_opts);
let fast = cursor_opts.iter().find(|o| o.id == "fast").unwrap();
assert_eq!((fast.current.as_deref(), fast.default_value.as_deref()), (Some("false"), Some("true")));
let mut other_opts = c.clone();
apply_model_defaults("claude", &mut other_opts);
assert_eq!(other_opts.iter().find(|o| o.id == "fast").unwrap().current.as_deref(), Some("true"));
// Editing effort on the same model preserves its initial `default_value` for Reset.
merge_update(
@@ -546,11 +595,34 @@ mod tests {
{"id": "model", "type": "select", "currentValue": "gpt-6-sol",
"options": [{"value": "gemini-4-carbon"}, {"value": "gpt-6-sol"}]},
{"id": "effort", "type": "select", "currentValue": "low",
"options": [{"value": "low"}, {"value": "medium"}, {"value": "high"}]}
"options": [{"value": "low"}, {"value": "medium"}, {"value": "high"}]},
{"id": "context", "type": "select", "currentValue": "1m",
"options": [{"value": "300k", "name": "300K"}, {"value": "1m", "name": "1M"}]}
]),
);
let effort = c.iter().find(|o| o.id == "effort").unwrap();
assert_eq!((effort.current.as_deref(), effort.default_value.as_deref()), (Some("low"), Some("low")));
let context = c.iter().find(|o| o.id == "context").unwrap();
assert_eq!((context.current.as_deref(), context.default_value.as_deref()), (Some("1m"), Some("1m")));
}
#[test]
fn apply_bypass_approvals_covers_mode_permissions_and_approval() {
let mut c = options_of(&json!({"configOptions": [
{"id": "mode", "category": "mode", "type": "select", "currentValue": "ask",
"options": [{"value": "ask"}, {"value": "full-access"}]},
{"id": "allow_all", "category": "permissions", "type": "select", "currentValue": "off",
"options": [{"value": "off"}, {"value": "on"}]},
{"id": "approval", "category": "approval", "type": "select", "currentValue": "ask",
"options": [{"value": "ask"}, {"value": "bypass"}]}
]}));
apply_bypass_approvals(&mut c);
assert_eq!(ids(&c), [("mode", Some("full-access")), ("allow_all", Some("on")), ("approval", Some("bypass"))]);
// Original agent default_values stay intact.
assert_eq!(
c.iter().map(|o| o.default_value.as_deref()).collect::<Vec<_>>(),
[Some("ask"), Some("off"), Some("ask")]
);
}
#[test]
+27 -12
Переглянути файл
@@ -331,19 +331,23 @@ impl Shared {
let hook = self.new_task_approvals.read().clone();
if hook.is_some_and(|ask| ask() == ide_core::settings::NewTaskApprovals::Ask) {
config::ask_for_approvals(&mut config);
return config;
}
if let Some((o, v)) = config::bypass_mode(&config).map(|(o, v)| (o.id.clone(), v.value.clone()))
&& let Some(o) = config.iter_mut().find(|c| c.id == o)
{
o.current = Some(v);
}
if let Some(o) = config.iter_mut().find(|o| o.id == config::CURSOR_APPROVAL) {
o.current = Some("bypass".into());
} else {
config::apply_bypass_approvals(&mut config);
}
config
}
pub(crate) fn thought_levels_for_new_task(
&self,
mut levels: BTreeMap<String, Vec<AgentConfigOption>>,
provider: &str,
) -> BTreeMap<String, Vec<AgentConfigOption>> {
for options in levels.values_mut() {
config::apply_model_defaults(provider, options);
}
levels
}
/// The commands the agent offered last time in this project.
fn known_commands(&self, provider: &str) -> Vec<AgentCommand> {
let cache = self.known.lock();
@@ -375,8 +379,19 @@ impl Shared {
}
}
// Discovery reads one model's options; a session on another model reports that model's.
// Restore each option's agent default so a session's manual overrides never pollute the catalog.
if acp && let Some((model, config)) = model.zip(config) {
let levels: Vec<_> = config.iter().filter(|o| config::is_per_model_option(o)).cloned().collect();
let levels: Vec<_> = config
.iter()
.filter(|o| config::is_per_model_option(o))
.cloned()
.map(|mut o| {
if let Some(def) = o.default_value.clone().filter(|d| o.values.iter().any(|v| v.value == *d)) {
o.current = Some(def);
}
o
})
.collect();
if !levels.is_empty() {
self.paths.catalogs.learn_levels(self, provider, model, levels);
}
@@ -736,7 +751,7 @@ impl AgentManager {
let mut info = provider::describe(p);
let catalog = self.shared.paths.catalogs.cached(&self.shared, &p.id);
info.config = self.shared.config_for_new_task(catalog.config, &p.id);
info.thought_levels = catalog.thought_levels;
info.thought_levels = self.shared.thought_levels_for_new_task(catalog.thought_levels, &p.id);
info.commands = self.shared.known_commands(&p.id);
info
})
@@ -1059,7 +1074,7 @@ impl AgentManager {
};
// Until the session reports its own, show what the agent offered last time with the choices applied.
let catalog = self.shared.paths.catalogs.cached(&self.shared, &spec.id);
let mut levels = catalog.thought_levels;
let mut levels = self.shared.thought_levels_for_new_task(catalog.thought_levels, &spec.id);
let mut config = self.shared.config_for_new_task(catalog.config, &spec.id);
for choice in &req.config {
if let Some(o) = config.iter_mut().find(|o| o.id == choice.id) {
+4 -8
Переглянути файл
@@ -3942,14 +3942,10 @@ async fn composer_commands_discover_cursor_effort_and_fast() {
assert!(calls.iter().any(|m| m.as_str() == "session/new"));
assert_eq!(calls.iter().filter(|m| m.as_str() == "initialize").count(), 1);
let cursor = mgr.providers().into_iter().find(|p| p.id == "cursor").unwrap();
assert_eq!(cursor.config.iter().find(|o| o.id == "fast").unwrap().current.as_deref(), Some("false"));
assert!(
cursor
.thought_levels
.values()
.next()
.is_some_and(|levels| { levels.iter().any(|o| o.category.as_deref() == Some("thought_level")) })
);
assert!(!cursor.config.iter().any(|o| o.id == "fast"));
let levels = cursor.thought_levels.values().next().expect("discovered model options");
assert_eq!(levels.iter().find(|o| o.id == "fast").unwrap().current.as_deref(), Some("false"));
assert!(levels.iter().any(|o| o.category.as_deref() == Some("thought_level")));
}
#[tokio::test(flavor = "multi_thread")]
+2 -1
Переглянути файл
@@ -26,9 +26,10 @@ pub fn plan(root: &Path, model: &BuildModel, module: &Path, cache: &Path) -> Ide
let module = dunce::canonicalize(root.join(module))?;
if let Some(p) = model.maven.as_ref().and_then(|m| m.projects.iter().find(|p| root.join(&p.dir) == module)) {
let mut args = p.options.clone();
let repo = crate::maven::local_repository_for(&p.options);
args.extend([
"process-resources".into(),
"help:evaluate".into(),
crate::maven::plugin_goal("help:evaluate", repo.as_deref()),
"-Dexpression=project.build.outputDirectory".into(),
format!("-Doutput={}", manifest.display()),
]);
+3 -1
Переглянути файл
@@ -361,7 +361,9 @@ fn classpaths(
if compile_first {
args.push("compile");
}
args.extend(["dependency:build-classpath", output_arg.as_str(), scope_arg.as_str(), "-q"]);
let build_classpath =
maven::plugin_goal("dependency:build-classpath", maven::local_repository_for(&top.options).as_deref());
args.extend([build_classpath.as_str(), output_arg.as_str(), scope_arg.as_str(), "-q"]);
let top_dir = subdir(root, &top.dir);
let owned_args: Vec<String> = args.into_iter().map(str::to_owned).collect();
let out = process::run_bounded(&top.command, &owned_args, &top_dir, &top.env, cancel, |_, _| {}).map_err(|e| {
+71
Переглянути файл
@@ -517,6 +517,59 @@ pub fn local_repository_of(settings: &Path) -> Option<PathBuf> {
Some(PathBuf::from(repo.replace("${user.home}", &home)))
}
/// The local repository a Maven run with these options resolves into: `-Dmaven.repo.local=`
/// first, then `<localRepository>` of the `-s` settings, then the user's default.
pub fn local_repository_for(options: &[String]) -> Option<PathBuf> {
if let Some(repo) = options.iter().find_map(|a| a.strip_prefix("-Dmaven.repo.local=")) {
return Some(PathBuf::from(repo));
}
let mut args = options.iter();
while let Some(arg) = args.next() {
let path = match arg.as_str() {
"-s" | "--settings" => args.next().map(String::as_str),
_ => arg.strip_prefix("-s=").or_else(|| arg.strip_prefix("--settings=")),
};
if let Some(path) = path {
return local_repository_of(Path::new(path)).or_else(default_local_repo);
}
}
default_local_repo()
}
/// A goal of the IDE's own (`help:evaluate`, `dependency:build-classpath`, …) by its plugin's
/// coordinates rather than its prefix: offline, Maven resolves a prefix only from group metadata
/// in the local repository, which a repository filled from a private mirror often lacks even when
/// the plugin itself is there. Uses the newest 3.x version already in `repo`, so nothing is
/// downloaded, else a pinned one.
pub fn plugin_goal(goal: &str, repo: Option<&Path>) -> String {
let (prefix, goal) = goal.split_once(':').expect("prefix:goal");
let (artifact, pinned) = match prefix {
"help" => ("maven-help-plugin", "3.5.1"),
"dependency" => ("maven-dependency-plugin", "3.8.1"),
_ => unreachable!("not a goal of the IDE's own: {prefix}"),
};
let version = repo.and_then(|repo| newest_local_plugin(repo, artifact, 3)).unwrap_or_else(|| pinned.to_owned());
format!("org.apache.maven.plugins:{artifact}:{version}:{goal}")
}
/// The newest release of `org.apache.maven.plugins:<artifact>` whose jar is in `repo`,
/// from major version `min_major` up.
pub(crate) fn newest_local_plugin(repo: &Path, artifact: &str, min_major: u64) -> Option<String> {
let dir = repo.join("org/apache/maven/plugins").join(artifact);
let parse = |v: &str| v.split('.').map(|n| n.parse::<u64>().ok()).collect::<Option<Vec<u64>>>();
std::fs::read_dir(&dir)
.ok()?
.flatten()
.filter_map(|e| e.file_name().into_string().ok())
.filter_map(|v| parse(&v).map(|n| (n, v)))
.filter(|(n, v)| {
n.first().is_some_and(|&major| major >= min_major)
&& dir.join(v).join(format!("{artifact}-{v}.jar")).is_file()
})
.max()
.map(|(_, v)| v)
}
impl Resolver {
fn new(local_repo: Option<PathBuf>, profiles: &[String]) -> Self {
Self::new_with_jdk(local_repo, profiles, None)
@@ -2557,6 +2610,24 @@ mod tests {
assert!(local_repository_of(&tmp.path().join("missing.xml")).is_none());
}
#[test]
fn ide_goals_resolve_from_the_repository_the_run_uses() {
let tmp = tempfile::tempdir().unwrap();
let settings = tmp.path().join("settings.xml");
std::fs::write(&settings, "<settings><localRepository>/srv/m2</localRepository></settings>").unwrap();
let s = settings.to_string_lossy().into_owned();
let opts = |a: &[&str]| a.iter().map(|s| s.to_string()).collect::<Vec<_>>();
assert_eq!(local_repository_for(&opts(&["-s", &s])), Some(PathBuf::from("/srv/m2")));
assert_eq!(local_repository_for(&opts(&[&format!("--settings={s}")])), Some(PathBuf::from("/srv/m2")));
let explicit = opts(&["-s", &s, "-Dmaven.repo.local=/tmp/r"]);
assert_eq!(local_repository_for(&explicit), Some(PathBuf::from("/tmp/r")));
// No repository known: a pinned version, still by coordinates.
assert_eq!(
plugin_goal("dependency:build-classpath", None),
"org.apache.maven.plugins:maven-dependency-plugin:3.8.1:build-classpath"
);
}
#[test]
fn effective_pom_goals_come_from_the_local_repository_it_is_given() {
let tmp = tempfile::tempdir().unwrap();
+39 -32
Переглянути файл
@@ -86,20 +86,29 @@ const MAVEN_CACHE_VERSION: u32 = 1;
/// `dependency:tree` of a plugin version whose `-Dverbose` lists the occurrences Maven
/// omitted (conflicts, duplicates): verbose output was dropped in 3.0 and is back since 3.2.
/// Offline, it is used only when an earlier sync downloaded it; otherwise the project's own
/// plugin version is, which may be cached instead.
/// Offline, it is used only when an earlier sync downloaded it; otherwise the newest version
/// in the local repository is.
const DEPENDENCY_TREE: &str = "org.apache.maven.plugins:maven-dependency-plugin:3.8.1:tree";
const DEPENDENCY_TREE_JAR: &str =
"org/apache/maven/plugins/maven-dependency-plugin/3.8.1/maven-dependency-plugin-3.8.1.jar";
/// The goals that read the effective POM into `effective` and the verbose dependency trees;
/// `repo` is the local repository the build resolves from.
/// `repo` is the local repository the build resolves from. Both goals name their plugin by
/// coordinates: offline, a prefix resolves only from group metadata the repository may lack.
fn maven_sync_goals(effective: &Path, offline: bool, repo: Option<&Path>) -> Vec<String> {
let pinned = !offline || repo.is_some_and(|repo| repo.join(DEPENDENCY_TREE_JAR).is_file());
let tree = if pinned {
DEPENDENCY_TREE.to_owned()
} else {
repo.and_then(|repo| maven::newest_local_plugin(repo, "maven-dependency-plugin", 2)).map_or_else(
|| "dependency:tree".to_owned(),
|v| format!("org.apache.maven.plugins:maven-dependency-plugin:{v}:tree"),
)
};
vec![
"help:effective-pom".into(),
maven::plugin_goal("help:effective-pom", repo),
format!("-Doutput={}", effective.to_string_lossy()),
if pinned { DEPENDENCY_TREE.into() } else { "dependency:tree".into() },
tree,
"-Dverbose".into(),
]
}
@@ -367,25 +376,8 @@ pub fn sync_maven(
verbose: true,
..MavenCache::default()
};
// Where the build resolves its jars, and therefore where the plugin goals are read
// from: `-Dmaven.repo.local=` first, then `<localRepository>` of the `-s` settings,
// then the user's default repository (which `plugin()` resolves itself).
let local_repo: Option<PathBuf> =
options.maven_options.iter().find_map(|a| a.strip_prefix("-Dmaven.repo.local=")).map(PathBuf::from).or_else(
|| {
let mut args = options.maven_options.iter();
while let Some(arg) = args.next() {
let path = match arg.as_str() {
"-s" | "--settings" => args.next().map(String::as_str),
_ => arg.strip_prefix("-s=").or_else(|| arg.strip_prefix("--settings=")),
};
if let Some(path) = path {
return maven::local_repository_of(Path::new(path));
}
}
None
},
);
// Where the build resolves its jars, and therefore where the plugin goals are read from.
let repo = maven::local_repository_for(&options.maven_options);
let mut errors: Vec<String> = Vec::new();
for (n, top) in model.projects.iter().filter(|p| !p.aggregated).enumerate() {
let effective = cache_dir.join(format!("effective-pom-{n}.xml"));
@@ -407,7 +399,6 @@ pub fn sync_maven(
if !options.profiles.is_empty() {
args.push(format!("-P{}", options.profiles.join(",")));
}
let repo = local_repo.clone().or_else(maven::default_local_repo);
args.extend(maven_sync_goals(&effective, options.offline, repo.as_deref()));
progress(SyncProgress { message: format!("Reading {}", top.display_name), fraction: None });
let command = options.maven_command.as_deref().unwrap_or(&top.command);
@@ -425,7 +416,7 @@ pub fn sync_maven(
}
})?;
let effective_projects = std::fs::read_to_string(&effective)
.map(|t| maven::parse_effective_pom_in(&t, local_repo.as_deref()))
.map(|t| maven::parse_effective_pom_in(&t, repo.as_deref()))
.unwrap_or_default();
let trees = maven::parse_dependency_tree(&out.text);
for (key, plugins, deps) in effective_projects {
@@ -953,11 +944,27 @@ mod tests {
#[test]
fn sync_reads_verbose_trees_with_a_pinned_plugin_unless_offline_without_it() {
let tmp = tempfile::tempdir().unwrap();
let online = maven_sync_goals(Path::new("e.xml"), false, None);
assert_eq!(online, ["help:effective-pom", "-Doutput=e.xml", DEPENDENCY_TREE, "-Dverbose"]);
let help = "org.apache.maven.plugins:maven-help-plugin:3.5.1:effective-pom";
let online = maven_sync_goals(Path::new("e.xml"), false, Some(tmp.path()));
assert_eq!(online, [help, "-Doutput=e.xml", DEPENDENCY_TREE, "-Dverbose"]);
// Offline with neither plugin cached: the tree falls back to the project's own version.
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()));
assert_eq!(offline[2], "dependency:tree");
assert!(offline.contains(&"-Dverbose".to_owned()));
assert_eq!(offline, [help, "-Doutput=e.xml", "dependency:tree", "-Dverbose"]);
// #5757: offline, plugins in the local repository are named by their coordinates, since
// the prefix needs group metadata a repository filled from a private mirror may lack.
for (artifact, version) in
[("maven-help-plugin", "3.4.0"), ("maven-help-plugin", "2.2"), ("maven-dependency-plugin", "3.6.1")]
{
let jar =
tmp.path().join(format!("org/apache/maven/plugins/{artifact}/{version}/{artifact}-{version}.jar"));
std::fs::create_dir_all(jar.parent().unwrap()).unwrap();
std::fs::write(&jar, "").unwrap();
}
// A version folder without its jar (only the POM was fetched) doesn't count.
std::fs::create_dir_all(tmp.path().join("org/apache/maven/plugins/maven-help-plugin/3.10.0")).unwrap();
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()));
assert_eq!(offline[0], "org.apache.maven.plugins:maven-help-plugin:3.4.0:effective-pom");
assert_eq!(offline[2], "org.apache.maven.plugins:maven-dependency-plugin:3.6.1:tree");
// Downloaded by an online sync: offline keeps using it, the project's version may be missing.
let jar = tmp.path().join(DEPENDENCY_TREE_JAR);
std::fs::create_dir_all(jar.parent().unwrap()).unwrap();
@@ -1029,7 +1036,7 @@ mod tests {
let cache = tmp.path().join("cache");
sync_maven(&root, &cache, &SyncOptions::default(), &CancellationToken::new(), &|_| {}).unwrap();
let args = std::fs::read_to_string(root.join("mvnw-args")).unwrap();
assert!(args.contains("help:effective-pom"), "args: {args}");
assert!(args.contains("maven-help-plugin:"), "args: {args}");
let loaded = crate::load_linked(&root, &cache, None, &Default::default(), &Default::default());
let maven = loaded.maven.unwrap();
assert!(maven.synced_at.is_some() && maven.sync_error.is_none(), "{:?}", maven.sync_error);
@@ -1054,6 +1061,6 @@ mod tests {
let args = std::fs::read_to_string(root.join("mvnd-args")).unwrap();
// `-T1` pins the daemon serial so the dependency trees stay parseable.
assert!(args.contains("-T1"), "args: {args}");
assert!(args.contains("help:effective-pom"), "args: {args}");
assert!(args.contains("maven-help-plugin:"), "args: {args}");
}
}
+4 -7
Переглянути файл
@@ -137,19 +137,16 @@ pub fn build(root: &Path, model: &BuildModel, id: &str, cache: &Path) -> IdeResu
// POM's effective identity first; profiles and -D options can change its GAV.
let output = cache.join("artifact-project.txt");
let mut probe = top.options.clone();
let evaluate =
crate::maven::plugin_goal("help:evaluate", crate::maven::local_repository_for(&top.options).as_deref());
probe.extend([
"-f".into(),
root.join(&p.pom).to_string_lossy().into_owned(),
"help:evaluate".into(),
evaluate.clone(),
"-Dexpression=project.id".into(),
format!("-Doutput={}", output.display()),
]);
args.extend([
"-DskipTests".into(),
"package".into(),
"help:evaluate".into(),
format!("-Doutput={}", manifest.display()),
]);
args.extend(["-DskipTests".into(), "package".into(), evaluate, format!("-Doutput={}", manifest.display())]);
return Ok(WebBuild {
command: top.command.clone(),
args,
+4 -2
Переглянути файл
@@ -33,8 +33,10 @@ fn get_workspace_roots() -> Tool {
"get_workspace_roots",
"Returns the root directories of the IDE workspace: this project and the trusted projects attached to it
in the same window, as absolute paths. A task works in one directory, but its workspace can hold several projects.
Call this when asked about the workspace, project or working directories, and before planning a change that may span
projects. Other tools reach an attached project by its root as `projectPath`.",
Call this before the first project-related operation in a session, and when asked about the workspace, project or
working directories. `projectRoot` is the project this connection serves, the default base for paths; `roots` is
every project in the workspace, the scope to search and read, not a list of projects to change. It doesn't change the
working directory or permissions. Other tools reach an attached project by its root as `projectPath`.",
|call| async move {
let root = call.root().to_path_buf();
let mut roots = vec![root.clone()];
+1 -1
Переглянути файл
@@ -112,7 +112,7 @@ done
let calls = fs::read_to_string(root.join("calls")).unwrap();
assert!(calls.lines().next().unwrap().contains("-pl app -am"), "{calls}");
assert!(calls.lines().all(|line| line.contains(&format!("-P member-{index}"))), "{calls}");
assert!(calls.contains("dependency:build-classpath"), "{calls}");
assert!(calls.contains(":build-classpath"), "{calls}");
}
}
+12
Переглянути файл
@@ -305,6 +305,18 @@ impl PathFilter {
builder.build().flatten().filter(|e| e.file_type().is_some_and(|t| t.is_dir())).map(|e| e.into_path()).collect()
}
/// The folders directly in `dir` that the index would walk.
pub(crate) fn child_dirs(&self, dir: &Path) -> Vec<PathBuf> {
let Some(mut builder) = self.walker(dir) else { return Vec::new() };
builder
.max_depth(Some(1))
.build()
.flatten()
.filter(|e| e.depth() == 1 && e.file_type().is_some_and(|t| t.is_dir()))
.map(|e| e.into_path())
.collect()
}
pub(crate) fn directories_with_names(&self, names: &HashSet<&OsStr>) -> Vec<PathBuf> {
let matches = parking_lot::Mutex::new(Vec::new());
for root in self.roots() {
+63
Переглянути файл
@@ -1246,3 +1246,66 @@ fn queries_during_streaming_scan_do_not_deadlock() {
done_rx.recv_timeout(Duration::from_secs(60)).expect("concurrent index queries deadlocked with streaming scan");
}
#[test]
fn reconciling_a_few_changed_files_does_not_show_indexing() {
let fx = sample();
let events = Arc::new(Mutex::new(Vec::new()));
let sink: SharedSink = {
let events = events.clone();
Arc::new(move |e: IdeEvent| events.lock().push(e))
};
let idx = fx.open_with(sink);
let announced = |events: &Mutex<Vec<IdeEvent>>| {
events
.lock()
.iter()
.filter(|e| matches!(e, IdeEvent::IndexState { indexing: true, .. } | IdeEvent::Task { done: false, .. }))
.count()
};
let settle = || {
assert!(idx.wait_idle(WAIT));
// The touched folders are reconciled once the snapshot delay has passed.
std::thread::sleep(Duration::from_millis(300));
assert!(idx.wait_idle(WAIT));
};
// A program appending to its log in the project, as a debugged Spring app does.
events.lock().clear();
let log = fx.write("logs/app.log", "start\n");
for i in 0..3 {
std::fs::write(&log, format!("line {i}\n").repeat(i + 1)).unwrap();
idx.update(std::slice::from_ref(&log), &[]);
settle();
}
assert_eq!(announced(&events), 0, "a log being written must not show Indexing");
assert!(files(&idx, "app.log").contains(&"logs/app.log".to_owned()), "the log is still indexed");
}
/// #5749: a file at the project root changing must not re-walk the whole project when the
/// touched folders are reconciled, yet folders that appear or vanish there are still picked up.
#[test]
fn reconciling_a_root_change_lists_only_that_folder() {
let fx = sample();
let idx = fx.open();
// Written behind the index's back, deep in a folder it already knows.
fx.write("src/order/Unreported.java", "class Unreported {}\n");
// A new folder, a vanished one and an unreported file next to the changed root file.
fx.write("fresh/deep/Fresh.java", "class Fresh {}\n");
std::fs::remove_dir_all(fx.root.join("docs")).unwrap();
fx.write("Unlisted.txt", "x\n");
let log = fx.write("app.log", "line\n");
idx.update(std::slice::from_ref(&log), &[]);
assert!(idx.wait_idle(WAIT));
// The touched folders are reconciled once the snapshot delay has passed.
std::thread::sleep(Duration::from_millis(300));
assert!(idx.wait_idle(WAIT));
assert!(files(&idx, "app.log").contains(&"app.log".to_owned()), "the changed file is indexed");
assert!(files(&idx, "Unlisted").contains(&"Unlisted.txt".to_owned()), "the root folder is listed");
assert!(files(&idx, "Fresh").contains(&"fresh/deep/Fresh.java".to_owned()), "a new folder is walked");
assert!(files(&idx, "maintenance").is_empty(), "a vanished folder's files are dropped");
assert!(files(&idx, "main.rs").contains(&"src/main.rs".to_owned()), "other folders keep their files");
assert!(files(&idx, "Unreported").is_empty(), "known subfolders are not re-walked");
}
+127 -32
Переглянути файл
@@ -36,6 +36,15 @@ const PROGRESS_EVERY: Duration = Duration::from_millis(250);
const SNAPSHOT_DELAY: Duration = Duration::from_secs(2);
#[cfg(test)]
const SNAPSHOT_DELAY: Duration = Duration::from_millis(50);
/// The shortest gap between two snapshot refreshes. Any index write drops the snapshot (see
/// `Store::apply`), so a later refresh only makes the next startup faster; a project whose files
/// keep changing (a log written inside it) would otherwise rewrite it every couple of seconds.
#[cfg(not(test))]
const SNAPSHOT_EVERY: Duration = Duration::from_secs(10);
#[cfg(test)]
const SNAPSHOT_EVERY: Duration = Duration::ZERO;
/// A subtree scan with fewer files to parse runs without showing "Indexing" (see `scan`).
const QUIET_SCAN_FILES: usize = 200;
pub(crate) const MAX_RECENT: usize = 50;
pub(crate) enum Job {
@@ -75,6 +84,8 @@ pub(crate) struct Shared {
idle: Condvar,
/// Coalesced post-update snapshot refresh.
snapshot_due: Mutex<Option<Instant>>,
/// When the snapshot was last refreshed (see [`SNAPSHOT_EVERY`]).
snapshot_saved: Mutex<Option<Instant>>,
/// Directories whose watcher events still need reconciliation before a
/// refreshed snapshot can be trusted.
pending_dirs: Mutex<HashSet<PathBuf>>,
@@ -103,6 +114,7 @@ impl Shared {
wake: Condvar::new(),
idle: Condvar::new(),
snapshot_due: Mutex::default(),
snapshot_saved: Mutex::default(),
pending_dirs: Mutex::default(),
}
}
@@ -444,7 +456,8 @@ impl Shared {
}
/// A cancelled scan (project closed) still ends its progress task and the indexing state.
fn end_scan(&self, task: TaskId) {
fn end_scan(&self, task: Option<TaskId>) {
let Some(task) = task else { return };
self.indexing.store(false, Ordering::SeqCst);
self.sink.emit(IdeEvent::Task {
id: task,
@@ -471,13 +484,13 @@ impl Shared {
}
fn full_scan(&self, found: Option<Vec<Found>>, guard: SystemTime) {
self.scan(None, found, guard);
self.scan(None, &[], found, guard);
// Parsing every file churns through far more memory than the index keeps.
ide_core::memory::release_free_pages();
}
fn scan(&self, dirs: Option<&[PathBuf]>, prewalked: Option<Vec<Found>>, guard: SystemTime) -> Option<ScanCounts> {
let started = Instant::now();
/// Shows "Indexing" (the status flag and a background task) for a scan.
fn start_scan(&self) -> TaskId {
self.indexing.store(true, Ordering::SeqCst);
self.emit_state();
let task = TaskId::next();
@@ -489,6 +502,25 @@ impl Shared {
done: false,
cancellable: false,
});
task
}
/// A full scan shows "Indexing" from the start. A subtree scan (folders the watcher reported,
/// reconciled after each burst of changes) shows it only once it has
/// [`QUIET_SCAN_FILES`] or more files to parse: a program writing its log inside the project
/// would otherwise keep "Indexing" in the status bar for as long as it runs.
///
/// Indexed files the walk didn't see are dropped when they are below one of `dirs` (all of
/// them for a full scan) or directly in one of `shallow`.
fn scan(
&self,
dirs: Option<&[PathBuf]>,
shallow: &[PathBuf],
prewalked: Option<Vec<Found>>,
guard: SystemTime,
) -> Option<ScanCounts> {
let started = Instant::now();
let mut task = dirs.is_none().then(|| self.start_scan());
let filter = self.filter();
let walk_started = Instant::now();
@@ -507,7 +539,10 @@ impl Shared {
found.iter().filter_map(|f| prev_hash_if_stale(&d, f).map(|h| (f, h))).collect();
let stale: Vec<PathBuf> = d
.paths()
.filter(|p| dirs.is_none_or(|dirs| dirs.iter().any(|dir| p.starts_with(dir))))
.filter(|p| {
dirs.is_none_or(|dirs| dirs.iter().any(|dir| p.starts_with(dir)))
|| p.parent().is_some_and(|parent| shallow.iter().any(|dir| dir == parent))
})
.filter(|p| !seen.contains(p.as_path()))
.cloned()
.collect();
@@ -524,6 +559,9 @@ impl Shared {
self.persist(&[], &stale, false);
let total = todo.len();
if task.is_none() && total >= QUIET_SCAN_FILES {
task = Some(self.start_scan());
}
let update_started = Instant::now();
let mut laps = ChunkLaps::default();
{
@@ -564,7 +602,9 @@ impl Shared {
}
done += batch.len();
laps.add(self.publish(batch.drain(..)));
if last_progress.elapsed() >= PROGRESS_EVERY {
if let Some(task) = task
&& last_progress.elapsed() >= PROGRESS_EVERY
{
last_progress = Instant::now();
self.sink.emit(IdeEvent::Task {
id: task,
@@ -606,15 +646,19 @@ impl Shared {
}
let snapshot_elapsed = snapshot_started.elapsed();
*self.snapshot_due.lock() = None;
self.indexing.store(false, Ordering::SeqCst);
self.sink.emit(IdeEvent::Task {
id: task,
title: "Indexing".into(),
message: None,
fraction: Some(1.0),
done: true,
cancellable: false,
});
*self.snapshot_saved.lock() = Some(Instant::now());
if let Some(task) = task {
self.indexing.store(false, Ordering::SeqCst);
self.sink.emit(IdeEvent::Task {
id: task,
title: "Indexing".into(),
message: None,
fraction: Some(1.0),
done: true,
cancellable: false,
});
}
// The counts may have changed either way.
self.emit_state();
if self.is_cancelled() {
return None;
@@ -757,17 +801,67 @@ impl Shared {
}
let mut due = self.snapshot_due.lock();
if due.is_none() {
*due = Some(Instant::now() + SNAPSHOT_DELAY);
let soonest = self.snapshot_saved.lock().map(|saved| saved + SNAPSHOT_EVERY);
*due = Some((Instant::now() + SNAPSHOT_DELAY).max(soonest.unwrap_or(Instant::now())));
}
}
/// Reconciles the folders the watcher reported since the last snapshot, then refreshes it.
/// A folder the index already has files below is listed one level deep: its own files, plus
/// any subfolder that appeared (walked whole) or is gone (its files dropped). A folder it
/// knows nothing below is walked whole. Walking known folders whole would re-read the entire
/// project after every change to a file at its root.
fn reconcile(&self, dirs: &[PathBuf]) {
let filter = self.filter();
// The subfolders each reported folder has indexed files in; absent when it has none.
let mut known: HashMap<&Path, HashSet<PathBuf>> = HashMap::new();
{
let d = self.data.read();
for path in d.paths() {
for dir in dirs {
let Ok(rest) = path.strip_prefix(dir) else { continue };
let subdirs = known.entry(dir.as_path()).or_default();
let mut parts = rest.components();
if let (Some(first), Some(_)) = (parts.next(), parts.next()) {
subdirs.insert(dir.join(first));
}
}
}
}
let mut found = Vec::new();
let mut trees = Vec::new();
let mut shallow = Vec::new();
for dir in dirs {
let Some(indexed) = known.get(dir.as_path()) else {
found.extend(filter.walk(dir, &self.cancelled));
trees.push(dir.clone());
continue;
};
found.extend(filter.list_dir(dir));
shallow.push(dir.clone());
for sub in filter.child_dirs(dir) {
if !indexed.contains(&sub) {
found.extend(filter.walk(&sub, &self.cancelled));
trees.push(sub);
}
}
// Gone from disk; a subfolder only hidden from the listing (an extra content root
// or a newly excluded folder) is handled by its own root or the rule-change rescan.
trees.extend(indexed.iter().filter(|sub| std::fs::symlink_metadata(sub).is_err()).cloned());
}
// Reported folders may nest; parse each file once.
let mut unique = HashSet::new();
found.retain(|f| unique.insert(f.path.clone()));
self.scan(Some(&trees), &shallow, Some(found), SystemTime::now());
}
fn save_snapshot_now(&self) {
let dirs: Vec<PathBuf> = self.pending_dirs.lock().drain().collect();
if !dirs.is_empty() {
// Reconcile the directories touched since the last scan before
// recording their mtimes; otherwise a missed watcher event could be
// blessed into the manifest.
self.scan(Some(&dirs), None, SystemTime::now());
self.reconcile(&dirs);
return;
}
if let Some(store) = &self.store {
@@ -779,6 +873,7 @@ impl Shared {
}
}
*self.snapshot_due.lock() = None;
*self.snapshot_saved.lock() = Some(Instant::now());
}
fn persist(&self, puts: &[(String, FileRecord)], deletes: &[String], durable: bool) {
@@ -884,7 +979,7 @@ impl Shared {
}
}
if !rescan {
self.scan(Some(&roots), None, SystemTime::now());
self.scan(Some(&roots), &[], None, SystemTime::now());
changed.retain(|p| !roots.iter().any(|root| p.starts_with(root)));
removed.retain(|p| !roots.iter().any(|root| p.starts_with(root)));
}
@@ -1174,7 +1269,7 @@ mod metric_tests {
batch.extend([sub.join(format!("f{i}.txt")), sub, root.join("gone")]);
}
std::fs::write(root.join("keep.txt"), "x").unwrap();
shared.scan(None, None, SystemTime::now()).unwrap();
shared.scan(None, &[], None, SystemTime::now()).unwrap();
assert_eq!(shared.data.read().file_count, 41);
std::fs::remove_dir_all(root.join("gone")).unwrap();
@@ -1198,7 +1293,7 @@ mod metric_tests {
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
std::fs::write(p, "x").unwrap();
}
shared.scan(None, None, SystemTime::now()).unwrap();
shared.scan(None, &[], None, SystemTime::now()).unwrap();
assert_eq!(shared.data.read().file_count, 7);
std::fs::remove_dir_all(root.join("gone")).unwrap();
@@ -1233,11 +1328,11 @@ mod metric_tests {
for i in 0..count {
std::fs::write(root.join(format!("file_{i}.unknown")), "plain").unwrap();
}
let cold = shared.scan(None, None, SystemTime::now()).unwrap();
let cold = shared.scan(None, &[], None, SystemTime::now()).unwrap();
assert_eq!((cold.discovered, cold.metadata_reused, cold.scheduled), (count, 0, count));
assert_eq!(cold.outcomes, ExtractionCounts { unsupported: count, ..Default::default() });
assert_eq!(shared.data.read().file_count as usize, count);
let hot = shared.scan(None, None, SystemTime::now()).unwrap();
let hot = shared.scan(None, &[], None, SystemTime::now()).unwrap();
assert_eq!((hot.discovered, hot.metadata_reused, hot.scheduled), (count, count, 0));
assert_eq!(hot.outcomes.total(), 0);
}
@@ -1249,7 +1344,7 @@ mod metric_tests {
let shared = shared(&root);
let path = root.join("main.rs");
std::fs::write(&path, "fn main() {}").unwrap();
shared.scan(None, None, SystemTime::now()).unwrap();
shared.scan(None, &[], None, SystemTime::now()).unwrap();
let (found, hash) = {
let data = shared.data.read();
let e = data.get(&path).unwrap();
@@ -1269,10 +1364,10 @@ mod metric_tests {
let path = root.join("main.rs");
std::fs::write(&path, "fn main() {}\n").unwrap();
let shared = shared(&root);
let cold = shared.scan(None, None, SystemTime::now()).unwrap();
let cold = shared.scan(None, &[], None, SystemTime::now()).unwrap();
assert_eq!((cold.discovered, cold.metadata_reused, cold.scheduled), (1, 0, 1));
assert_eq!(cold.outcomes, ExtractionCounts { symbol_extractions: 1, ..Default::default() });
let hot = shared.scan(None, None, SystemTime::now()).unwrap();
let hot = shared.scan(None, &[], None, SystemTime::now()).unwrap();
assert_eq!((hot.discovered, hot.metadata_reused, hot.scheduled), (1, 1, 0));
assert_eq!(hot.outcomes, ExtractionCounts::default());
// Force a metadata mismatch without a timestamp-resolution-dependent sleep.
@@ -1283,7 +1378,7 @@ mod metric_tests {
rec.mtime = rec.mtime.wrapping_add(1);
let (entry, symbols) = FileEntry::new(path.clone(), "main.rs".into(), rec);
shared.data.write().insert(entry, symbols);
let touched = shared.scan(None, None, SystemTime::now()).unwrap();
let touched = shared.scan(None, &[], None, SystemTime::now()).unwrap();
assert_eq!((touched.discovered, touched.metadata_reused, touched.scheduled), (1, 0, 1));
assert_eq!(touched.outcomes, ExtractionCounts { hash_reused: 1, ..Default::default() });
assert_eq!(shared.data.read().symbol_count, 1);
@@ -1339,13 +1434,13 @@ mod metric_tests {
{
let mut index = shared(&root);
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
assert_eq!(index.scan(None, None, SystemTime::now()).unwrap().outcomes.symbol_extractions, 1);
assert_eq!(index.scan(None, &[], None, SystemTime::now()).unwrap().outcomes.symbol_extractions, 1);
}
let mut index = shared(&root);
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
let found = index.walk_roots(None);
index.load_persisted(&found);
let counts = index.scan(None, Some(found), SystemTime::now()).unwrap();
let counts = index.scan(None, &[], Some(found), SystemTime::now()).unwrap();
assert_eq!((counts.discovered, counts.metadata_reused, counts.scheduled), (1, 1, 0));
assert_eq!(counts.outcomes, ExtractionCounts::default());
assert_eq!(index.data.read().symbol_count, 1);
@@ -1362,7 +1457,7 @@ mod metric_tests {
{
let mut index = shared(&root);
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
assert_eq!(index.scan(None, None, SystemTime::now()).unwrap().outcomes.symbol_extractions, 1);
assert_eq!(index.scan(None, &[], None, SystemTime::now()).unwrap().outcomes.symbol_extractions, 1);
}
let mut index = shared(&root);
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
@@ -1411,7 +1506,7 @@ mod metric_tests {
{
let mut index = shared(&root);
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
index.scan(None, None, SystemTime::now()).unwrap();
index.scan(None, &[], None, SystemTime::now()).unwrap();
}
let mut index = shared(&root);
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
@@ -1462,7 +1557,7 @@ mod metric_tests {
});
index
});
assert!(index.scan(None, None, SystemTime::now()).is_none());
assert!(index.scan(None, &[], None, SystemTime::now()).is_none());
assert!(index.is_cancelled());
assert!(!index.indexing.load(Ordering::Relaxed));
assert_eq!(index.data.read().file_count, 1);
@@ -1473,7 +1568,7 @@ mod metric_tests {
let dir = tempfile::tempdir().unwrap();
let shared = shared(dir.path());
shared.cancel();
assert!(shared.scan(None, None, SystemTime::now()).is_none());
assert!(shared.scan(None, &[], None, SystemTime::now()).is_none());
assert!(!shared.indexing.load(Ordering::Relaxed));
}
}
+7 -2
Переглянути файл
@@ -168,8 +168,13 @@ impl Session<'_> {
"instructions": format!(
"Built-in OpenIDEA tools for {about}: they see the files as the IDE has them and, \
for a project open in a window, its editors. The project's workspace can include other \
projects attached to it: call `get_workspace_roots` to list them before answering about \
workspace directories or planning a change across projects."
projects attached to it, which a session's working directory doesn't show. Before the \
first project-related operation in a session, call `get_workspace_roots`: its \
`projectRoot` is the project this connection serves and the default base for paths, and \
its `roots` are every project in the IDE workspace. That is the scope to search and read, \
not a list of projects to change; it doesn't change your working directory or \
permissions. Pass another root as `projectPath` to reach that project. Call it again \
when the user switches projects or attaches one."
),
})
}
+2
Переглянути файл
@@ -282,6 +282,8 @@ async fn a_folder_served_in_the_background_answers_initialize_list_and_call() {
let init = rpc_for(&s, &inside, "initialize", json!({})).await;
let instructions = init["result"]["instructions"].as_str().unwrap();
assert!(instructions.contains(inventory.to_str().unwrap()), "{instructions}");
// Clients that load tool descriptions lazily still learn to establish the workspace first (#5751).
assert!(instructions.contains("first project-related operation in a session, call `get_workspace_roots`"));
let list = rpc_for(&s, &inside, "tools/list", json!({})).await;
assert_eq!(list["result"]["tools"][0]["description"], format!("Names {}", inventory.display()), "{list}");
let call = rpc_for(&s, &inside, "tools/call", json!({ "name": "where" })).await;
+1
Переглянути файл
@@ -127,6 +127,7 @@ pub(crate) fn info(def: &Def) -> GeneratorInfo {
description: def.description.clone(),
git: def.git,
fields: def.fields.iter().map(field).collect(),
directory: def.directory.clone(),
dynamic: def.service.is_some(),
}
}
+18 -4
Переглянути файл
@@ -57,6 +57,16 @@ fn with_defaults(def: &Def, name: &str, values: &Values) -> Values {
out
}
/// The project folder's name: the generator's `directory` template (the solution name of a
/// .NET project with a solution), or the project name.
fn project_folder(def: &Def, name: &str, values: &Values) -> String {
def.directory
.as_deref()
.map(|t| render(t, values).trim().to_owned())
.filter(|folder| !folder.is_empty())
.unwrap_or_else(|| name.to_owned())
}
/// The fields a project service adds to the form (its metadata); empty for other generators.
pub fn options(id: &str, values: &Values, cancel: &CancellationToken) -> IdeResult<Vec<Field>> {
let def = def(id).ok_or_else(|| unknown(id))?;
@@ -398,15 +408,19 @@ pub(crate) fn create_with(
if let Some(e) = name_error(name) {
return Err(IdeError::invalid(e));
}
let values = with_defaults(def, name, &req.values);
let folder = project_folder(def, name, &values);
if let Some(e) = name_error(&folder) {
return Err(IdeError::invalid(e));
}
let location = req.location.to_path_buf();
if !location.is_dir() {
std::fs::create_dir_all(&location)?;
}
let target = location.join(name);
let target = location.join(&folder);
if target_taken(&target) {
return Err(IdeError::invalid(format!("{} already exists and is not empty", target.display())));
}
let values = with_defaults(def, name, &req.values);
let search = search_path();
let mut missing = def
@@ -420,10 +434,10 @@ pub(crate) fn create_with(
return Err(IdeError::unavailable(format!("`{}`{need} is required to create this project", r.program)));
}
let staging = Staging(location.join(format!(".{name}.openidea-new-{}", std::process::id())));
let staging = Staging(location.join(format!(".{folder}.openidea-new-{}", std::process::id())));
let _ = std::fs::remove_dir_all(&staging.0);
std::fs::create_dir_all(&staging.0)?;
let project = staging.0.join(name);
let project = staging.0.join(&folder);
download_service(def, &values, &staging.0, &project, cancel, emit)?;
let creates_dir = def.steps.iter().any(|s| s.cwd == Cwd::Parent && s.applies(&values));
+16
Переглянути файл
@@ -169,6 +169,17 @@ fn dotnet_pins_the_sdk_and_creates_a_solution() {
let (pin, lines) = render(&[("solution", "false")]);
assert_eq!(pin, None);
assert_eq!(lines, ["dotnet new console --name Shop --output . --language C#", "dotnet new gitignore"]);
// #5732: the top folder is the solution's (Store/Store.slnx, Store/Shop/Shop.csproj), as in
// Rider and Visual Studio; without a solution `solution-name` isn't sent and it is the project's.
let folder = |pairs: &[(&str, &str)]| {
let given = pairs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect();
project_folder(def, "Shop", &with_defaults(def, "Shop", &given))
};
assert_eq!(folder(&[("solution-name", "Store")]), "Store");
assert_eq!(folder(&[]), "Shop");
assert_eq!(folder(&[("solution", "false")]), "Shop");
assert_eq!(folder(&[("solution-name", " ")]), "Shop");
}
#[cfg(unix)]
@@ -198,6 +209,11 @@ fn dotnet_templates_see_the_selected_sdk_before_running() {
let pin: serde_json::Value = serde_json::from_slice(&std::fs::read(project.join("global.json")).unwrap()).unwrap();
assert_eq!(pin["sdk"]["version"], "10.0.400");
assert_eq!(std::fs::read_to_string(parent_pin).unwrap(), inherited);
// A solution named apart from the project names the folder.
let req = request("dotnet", tmp.path(), "Api", &[("sdk", "10.0.400"), ("solution-name", "Store")]);
let project = create_with(&def, &req, &CancellationToken::new(), &|_| {}).unwrap();
assert_eq!(project, tmp.path().join("Store"));
assert!(project.join("global.json").is_file());
}
/// `dotnet` of a runtime-only install: `--version` fails ("No .NET SDKs were found").
+8
Переглянути файл
@@ -30,6 +30,11 @@ pub(crate) struct Def {
pub requires: Vec<RequireDef>,
#[serde(default)]
pub fields: Vec<FieldDef>,
/// The project folder's name, when it isn't the project name: a template over the fields
/// (.NET's solution name). Steps that create the folder themselves (`cwd = "parent"`) can't
/// use it.
#[serde(default)]
pub directory: Option<String>,
#[serde(default)]
pub service: Option<ServiceDef>,
/// Generation runs: the service's zip, `steps`, `files`, then `after`.
@@ -280,6 +285,9 @@ pub struct GeneratorInfo {
/// Offer "Create Git repository".
pub git: bool,
pub fields: Vec<Field>,
/// The project folder's name when it isn't the project name: a template over the fields
/// shown (a hidden field has its default), like [`Field::default`]; empty renders the name.
pub directory: Option<String>,
/// More fields come from `scaffold_options` (a project service's metadata).
pub dynamic: bool,
}
+1
Переглянути файл
@@ -9,6 +9,7 @@ const java: GeneratorInfo = {
order: 1,
description: "A plain Java application built with Maven or Gradle.",
git: true,
directory: null,
dynamic: false,
fields: [
{
+4
Переглянути файл
@@ -3,6 +3,9 @@ name = ".NET"
group = ".NET"
icon = "project-dotnet"
description = "A .NET project from dotnet new."
# With a solution, the top folder is named after it (MySolution/MyProject/MyProject.csproj).
# `solution-name` is sent only while "Create solution" is checked; otherwise it renders the name.
directory = "{{solution-name}}"
# `dotnet --version` fails without an SDK (a runtime-only install). Blazor Web App and the
# other templates' current options need SDK 8.
@@ -50,6 +53,7 @@ type = "checkbox"
default = "true"
hint = "As in Visual Studio: the solution file at the top, the project in its own folder."
[[fields]]
id = "solution-name"
label = "Solution name:"
+1
Переглянути файл
@@ -52,6 +52,7 @@
"@codemirror/lang-html": "^6.4.12",
"@codemirror/lang-java": "^6.0.2",
"@codemirror/lang-javascript": "^6.2.5",
"@codemirror/lang-less": "^6.0.2",
"@codemirror/lang-markdown": "^6.5.2",
"@codemirror/lang-sass": "^6.0.2",
"@codemirror/lang-sql": "^6.10.0",
Створено
+3
Переглянути файл
@@ -31,6 +31,9 @@ importers:
'@codemirror/lang-javascript':
specifier: ^6.2.5
version: 6.2.5
'@codemirror/lang-less':
specifier: ^6.0.2
version: 6.0.2
'@codemirror/lang-markdown':
specifier: ^6.5.2
version: 6.5.2
+5
Переглянути файл
@@ -7403,6 +7403,11 @@ export type GeneratorInfo = {
/** Offer "Create Git repository". */
git: boolean,
fields: Field[],
/**
* The project folder's name when it isn't the project name: a template over the fields
* shown (a hidden field has its default), like [`Field::default`]; empty renders the name.
*/
directory: string | null,
/** More fields come from `scaffold_options` (a project service's metadata). */
dynamic: boolean,
};
+13 -1
Переглянути файл
@@ -1,7 +1,7 @@
import { afterEach, describe, expect, it } from "vitest";
import { EditorSelection, EditorState, Prec, StateEffect } from "@codemirror/state";
import { Decoration, EditorView, WidgetType } from "@codemirror/view";
import { setSearchQuery } from "@codemirror/search";
import { searchPanelOpen, setSearchQuery } from "@codemirror/search";
import { StreamLanguage } from "@codemirror/language";
import { literalKindAt } from "./literals";
import { selectionMarks } from "./selectionMarks";
@@ -116,6 +116,18 @@ describe("find backgrounds", () => {
});
});
describe("without a usable query", () => {
it("next, previous and replace do nothing instead of opening CodeMirror's search panel", () => {
for (const o of [{ search: "" }, { search: "(", regexp: true }]) {
const v = make("abc abc", { ...o, replace: "x" });
expect([findNext(v), findPrevious(v), replaceNext(v), replaceAll(v)]).toEqual([false, false, false, false]);
expect(searchPanelOpen(v.state)).toBe(false);
expect(v.dom.querySelector(".cm-search")).toBeNull();
expect(v.state.doc.toString()).toBe("abc abc");
}
});
});
describe("find in selection", () => {
const doc = "a1 a2\na3 a4\na5 a6\n";
// Scope: the second line only.
+10 -3
Переглянути файл
@@ -359,8 +359,15 @@ function step(view: EditorView, forward: boolean): boolean {
return true;
}
/**
* CodeMirror's search commands open its own search panel when the query is empty or invalid;
* ours run from the find bar, so without a usable query they do nothing.
*/
const usableQuery = (view: EditorView) => getSearchQuery(view.state).valid;
export function findNext(view: EditorView): boolean {
return view.state.field(findScope, false) ? step(view, true) : cmFindNext(view);
if (view.state.field(findScope, false)) return step(view, true);
return usableQuery(view) && cmFindNext(view);
}
/** The last match in `from`–`to` other than `skip`. */
@@ -466,7 +473,7 @@ const replacePreview = StateField.define<{ preserve: boolean | null; tooltip: To
/** Replaces the selected match (if it is one) and selects the next match. */
export function replaceNext(view: EditorView, preserve = false): boolean {
const { state } = view;
if (!state.field(findScope, false) && !preserve) return cmReplaceNext(view);
if (!state.field(findScope, false) && !preserve) return usableQuery(view) && cmReplaceNext(view);
if (state.readOnly) return false;
const query = getSearchQuery(state);
const ms = matchesIn(state);
@@ -487,7 +494,7 @@ export function replaceNext(view: EditorView, preserve = false): boolean {
export function replaceAll(view: EditorView, preserve = false): boolean {
const { state } = view;
if (!state.field(findScope, false) && !preserve) return cmReplaceAll(view);
if (!state.field(findScope, false) && !preserve) return usableQuery(view) && cmReplaceAll(view);
if (state.readOnly) return false;
const query = getSearchQuery(state);
const changes = matchesIn(state).map((m) => ({
+10
Переглянути файл
@@ -16,6 +16,16 @@ describe("vue language mode", () => {
expect(tree).toMatch(/RuleSet\(ClassSelector.*RuleSet\(ClassSelector/s);
});
it('highlights Less inside <style lang="less">', async () => {
const support = await loadSupport(findLanguageDescription("Vue", "/p/a.vue")!);
const src = `<template><div/></template>\n<style lang="less">\n@c: red;\n.a { .b { color: @c; } .m(); }\n</style>`;
const tree = support!.language.parser.parse(src).toString();
// Less-only syntax: a top-level @-variable declaration, a mixin call and a nested rule.
expect(tree).toContain("StyleSheet(Declaration(AtKeyword");
expect(tree).toContain("Inclusion(ClassSelector");
expect(tree).toMatch(/RuleSet\(ClassSelector.*RuleSet\(ClassSelector/s);
});
it("still parses a plain <style> block as CSS", async () => {
const support = await loadSupport(findLanguageDescription("Vue", "/p/a.vue")!);
const tree = support!.language.parser
+6 -4
Переглянути файл
@@ -1,11 +1,12 @@
/**
* Vue single-file components: `@codemirror/lang-vue`'s parser over an HTML
* base that also highlights `<style lang="scss|sass">` with the Sass grammar —
* stock `vue()` parses every `<style>` as plain CSS, which loses the SCSS
* colours.
* base that also highlights `<style lang="scss|sass">` with the Sass grammar
* and `<style lang="less">` with the Less one — stock `vue()` parses every
* `<style>` as plain CSS, which loses their variables, nesting and mixins.
*/
import { indentNodeProp, LanguageSupport, type LRLanguage, type TreeIndentContext } from "@codemirror/language";
import { html } from "@codemirror/lang-html";
import { lessLanguage } from "@codemirror/lang-less";
import { sassLanguage } from "@codemirror/lang-sass";
import { vue } from "@codemirror/lang-vue";
@@ -27,13 +28,14 @@ export function vueLanguage(): LanguageSupport {
const base = html({
selfClosingTags: true,
// `<style>` without `lang` (or with `lang="css"`) keeps HTML's own CSS
// nesting; only an explicit SCSS/Sass dialect re-parses it.
// nesting; only an explicit SCSS/Sass/Less dialect re-parses it.
nestedLanguages: [
{
tag: "style",
attrs: (a) => a.lang === "scss" || a.lang === "sass",
parser: sassLanguage.parser,
},
{ tag: "style", attrs: (a) => a.lang === "less", parser: lessLanguage.parser },
],
});
const language = (base.language as LRLanguage).configure({ props: [indentNodeProp.add({ Element: elementIndent })] });
+119 -12
Переглянути файл
@@ -8,6 +8,7 @@
import { useCallback, useEffect, useId, useMemo, useState, type ReactNode } from "react";
import type {
AgentConfigOption,
AgentModelCatalog,
AgentProvider,
AgentRegistry,
CustomAgentInput,
@@ -22,8 +23,9 @@ import { Button, Dialog, Icon, IconButton, Input, List, ProgressBar, SearchField
import { useSettingsForm } from "@/workbench/contributions";
import { confirm } from "@/workbench/messages";
import { LocalCliUpdate } from "./LocalCliUpdate";
import { isPerModelOption } from "./composerModel";
import { approvalDefaults, cursorModelDefaults, isPerModelOption } from "./composerModel";
import { providerIcon, slugifyId } from "./model";
import { useAgents } from "./store";
import {
DISTRIBUTION_LABEL,
afterInstall,
@@ -866,7 +868,7 @@ function ProviderSettings({
</Section>
)}
<Section title="New Tasks">
<AgentDefaults agent={agent} />
<AgentDefaults agent={agent} backend={backend} />
</Section>
<Section title="Launch">
<div className={styles.form}>
@@ -1014,29 +1016,117 @@ function ExternalLink({ url, label }: { url: string; label: string }) {
);
}
/** The options a new task of `agent` starts with: each the agent's own default unless chosen. */
export function defaultOptions(agent: AgentProvider, chosen: Record<string, string>): AgentConfigOption[] {
const base = agent.config.filter((o) => !isPerModelOption(o) && o.values.length > 1);
/** The options a new task of `agent` starts with: each its effective default unless chosen. */
export function defaultOptions(
agent: AgentProvider,
chosen: Record<string, string>,
newTaskApprovals: "bypass" | "ask" = "bypass",
): AgentConfigOption[] {
const baseRaw = agent.config.filter((o) => !isPerModelOption(o) && o.values.length > 1);
const approvals = approvalDefaults(baseRaw, newTaskApprovals);
const base = baseRaw.map((o) => {
const policy = approvals[o.id];
return {
...o,
defaultValue: o.defaultValue ?? o.current,
current: policy !== undefined && o.values.some((v) => v.value === policy) ? policy : o.current,
};
});
const modelOption = base.find((o) => o.category === "model");
const model = (modelOption && chosen[modelOption.id]) || modelOption?.current;
const levels = (model && agent.thoughtLevels?.[model]) || [];
return [...base, ...levels.filter((o) => o.values.length > 1)];
const rawLevels = (model && agent.thoughtLevels?.[model]) || [];
const modelDefaults = cursorModelDefaults(agent.id, rawLevels);
const levels = rawLevels
.filter((o) => o.values.length > 1)
.map((o) => {
const policy = modelDefaults[o.id];
return {
...o,
defaultValue: o.defaultValue ?? o.current,
current: policy !== undefined && o.values.some((v) => v.value === policy) ? policy : o.current,
};
});
return [...base, ...levels];
}
function AgentDefaults({ agent }: { agent: AgentProvider }) {
const MODEL_SETTINGS_POLL_MS = 600;
function AgentDefaults({ agent, backend }: { agent: AgentProvider; backend: CommandsBackend }) {
const form = useSettingsForm();
const all = (form.useValue("agents.defaults") ?? {}) as Record<string, Record<string, string>>;
const newTaskApprovals = (form.useValue("agents.newTaskApprovals") as "bypass" | "ask" | undefined) ?? "bypass";
const chosen = all[agent.id] ?? {};
const options = defaultOptions(agent, chosen);
const storeCatalog = useAgents((s) => s.modelCatalogs.get(agent.id));
const [fetchedCatalog, setFetchedCatalog] = useState<AgentModelCatalog | null>(null);
const catalog = fetchedCatalog?.provider === agent.id ? fetchedCatalog : storeCatalog;
const effectiveAgent = useMemo<AgentProvider>(() => {
if (!catalog) return agent;
return {
...agent,
config: catalog.config.length ? catalog.config : agent.config,
thoughtLevels: { ...agent.thoughtLevels, ...catalog.thoughtLevels },
};
}, [agent, catalog]);
const options = defaultOptions(effectiveAgent, chosen, newTaskApprovals);
const modelOption = options.find((o) => o.category === "model");
const selectedModel = (modelOption && chosen[modelOption.id]) || modelOption?.current || null;
const unknownModelSettings =
!!selectedModel &&
!!modelOption?.values.some((v) => v.value === selectedModel) &&
!Object.hasOwn(effectiveAgent.thoughtLevels ?? {}, selectedModel);
const refreshModels = backend.refreshModels;
const fetchKey =
agent.installed && refreshModels && selectedModel && unknownModelSettings ? `${agent.id}:${selectedModel}` : null;
const [settledKey, setSettledKey] = useState<string | null>(null);
const loadingModel = fetchKey !== null && settledKey !== fetchKey;
useEffect(() => {
if (!fetchKey || !refreshModels || !selectedModel) return;
let live = true;
let timer: ReturnType<typeof setTimeout> | null = null;
const poll = async () => {
try {
const next = await refreshModels(agent.id, selectedModel);
if (!live) return;
setFetchedCatalog(next);
if (next.refreshing && !Object.hasOwn(next.thoughtLevels ?? {}, selectedModel)) {
timer = setTimeout(() => void poll(), MODEL_SETTINGS_POLL_MS);
} else {
setSettledKey(fetchKey);
}
} catch {
if (live) setSettledKey(fetchKey);
}
};
void poll();
return () => {
live = false;
if (timer) clearTimeout(timer);
};
}, [agent.id, fetchKey, refreshModels, selectedModel]);
if (!options.length)
return (
<p className={styles.text}>
<T>The agent's models and modes can be chosen here after its first session.</T>
</p>
);
const baseIds = new Set(effectiveAgent.config.filter((o) => !isPerModelOption(o)).map((o) => o.id));
const choose = (id: string, value: string) => {
const { [id]: _, ...rest } = chosen;
const next = value ? { ...rest, [id]: value } : rest;
const next: Record<string, string> = value ? { ...rest, [id]: value } : { ...rest };
// Prune stale per-model defaults when switching to a model whose options are already known.
if (modelOption && id === modelOption.id) {
const nextModel = value || modelOption.current;
const nextLevels = nextModel ? effectiveAgent.thoughtLevels?.[nextModel] : undefined;
if (nextLevels) {
for (const key of Object.keys(next)) {
if (baseIds.has(key)) continue;
const matching = nextLevels.find((o) => o.id === key);
if (!matching || !matching.values.some((v) => v.value === next[key])) delete next[key];
}
}
}
const { [agent.id]: __, ...others } = all;
form.set("agents.defaults", Object.keys(next).length ? { ...others, [agent.id]: next } : others);
};
@@ -1044,14 +1134,26 @@ function AgentDefaults({ agent }: { agent: AgentProvider }) {
<div className={styles.form}>
{options.map((o) => {
const fallback = o.values.find((v) => v.value === o.current)?.name;
const agentDefault = o.defaultValue ?? o.current;
const defaultLabel = fallback
? o.current !== agentDefault
? tx`Default (${fallback})`
: tx`Agent's default (${fallback})`
: tx("Agent's default");
const currentChoice = chosen[o.id] ?? "";
const unavailableChoice =
currentChoice && !o.values.some((v) => v.value === currentChoice)
? [{ value: currentChoice, label: tx`${currentChoice} (unavailable)`, verbatim: true, disabled: true }]
: [];
return (
<Row key={o.id} label={o.name} htmlFor={`agent-default-${agent.id}-${o.id}`}>
<div className={styles.select}>
<Select
id={`agent-default-${agent.id}-${o.id}`}
value={chosen[o.id] ?? ""}
value={currentChoice}
options={[
{ value: "", label: fallback ? tx`Agent's default (${fallback})` : tx("Agent's default") },
{ value: "", label: defaultLabel },
...unavailableChoice,
...o.values.map((v) => ({
value: v.value,
label: v.name,
@@ -1065,6 +1167,11 @@ function AgentDefaults({ agent }: { agent: AgentProvider }) {
</Row>
);
})}
{loadingModel && (
<p className={styles.rowHint}>
<T>Loading model settings…</T>
</p>
)}
<p className={styles.rowHint}>
<T>What you pick on the New Task page wins; these apply until then and after switching agents.</T>
</p>
+65 -95
Переглянути файл
@@ -86,26 +86,30 @@
}
.bar {
display: flex;
flex-wrap: wrap;
flex-wrap: nowrap;
align-items: center;
gap: var(--space-0-5);
gap: var(--space-1);
padding: 4px 6px 6px;
cursor: default;
}
.toolbar {
display: flex;
flex: 1;
flex-wrap: wrap;
flex: 1 1 0;
flex-wrap: nowrap;
align-items: center;
min-width: 0;
overflow: hidden;
gap: var(--space-0-5);
}
.toolbar > button {
flex: 0 1 auto;
min-width: 0;
}
.actions {
display: flex;
flex: none;
align-items: center;
gap: var(--space-1);
margin-left: auto;
}
/* Attach/reference buttons share the send button's 24px footprint and chrome. */
/* Plain toolbar icons, framed only on hover like the rest of the IDE's toolbars. */
@@ -114,21 +118,60 @@
height: var(--h-control);
}
.spacer {
flex: 1;
display: none;
}
.configPicker,
.modelControl {
display: flex;
flex: 0 1 auto;
min-width: 0;
}
.modelControl {
align-items: center;
}
.modelControl > .chip {
flex: 0 1 auto;
min-width: 0;
}
.configPicker > button {
min-width: 0;
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.inlineSetting {
flex: none;
}
.collapsed {
display: none;
}
.compactDetail {
display: none;
}
.settingsMenu {
display: none;
flex: none;
}
.settingsMenuVisible {
display: flex;
}
/* Applied only synchronously during JS overflow measurement (never painted). */
.toolbarMeasuring > *,
.toolbarMeasuring .configPicker,
.toolbarMeasuring .modelControl,
.toolbarMeasuring .modelControl > .chip,
.toolbarMeasuring .chip,
.toolbarMeasuring .configPicker > button {
flex: none;
max-width: none;
}
.toolbarMeasuring .collapsed,
.toolbarMeasuring .settingsMenu {
display: flex;
}
.toolbarMeasuring .compactDetail {
display: inline-grid;
}
.settingsPopup {
width: min(320px, calc(100vw - 24px));
@@ -232,19 +275,32 @@
.quickSettings {
display: flex;
flex-direction: column;
gap: var(--space-3);
padding: 4px 12px 10px;
}
.quickRow {
display: flex;
flex-direction: column;
gap: var(--space-1);
}
.quickRow + .quickRow {
margin-top: 6px;
padding-top: 6px;
border-top: 1px solid var(--border);
}
.quickLabel {
padding: 2px 14px 4px;
color: var(--fg-secondary);
font-size: var(--fs-small);
font-weight: 600;
}
.quickToggleRow {
flex-direction: row;
align-items: center;
justify-content: space-between;
gap: var(--space-3);
padding: 2px 14px;
}
.quickToggleRow .quickLabel {
padding: 0;
}
.modelEffortPopup [role="option"] .modelRowConfigure {
opacity: 0;
}
@@ -284,44 +340,6 @@
.pinnedButton {
color: var(--accent);
}
.segmented {
display: flex;
align-items: stretch;
gap: var(--space-0-5);
padding: 2px;
border-radius: var(--radius-toolbar-button);
background: var(--bg-input);
box-shadow: inset 0 0 0 1px var(--border-strong);
}
.segment {
flex: 1 1 0;
min-width: 0;
height: calc(var(--h-button) - 2px);
padding: 0 6px;
border: 0;
border-radius: var(--radius-control);
background: transparent;
color: var(--fg-secondary);
font-size: var(--fs-small);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
transition:
background var(--dur-fast) var(--ease),
color var(--dur-fast) var(--ease);
}
.segment:hover {
color: var(--fg-strong);
}
.segment:focus-visible {
outline: 2px solid var(--focus-ring);
outline-offset: -2px;
}
.segmentActive {
background: var(--bg-toolbar-hover);
color: var(--fg-strong);
font-weight: 600;
}
.modePopup {
min-width: 200px;
padding: 6px 0;
@@ -361,54 +379,6 @@
padding: 8px 14px 2px;
border-top: 1px solid var(--border);
}
@container agent-composer (max-width: 600px) {
/* Narrow: keep one row of icons next to the agent picker. The model/mode pickers
collapse into the settings menu, so nothing has to wrap onto a second line. */
.bar {
flex-direction: row;
align-items: center;
gap: var(--space-1-5);
}
.toolbar {
flex-wrap: nowrap;
}
.toolbar > button,
.toolbar > .configPicker {
flex: 0 1 auto;
min-width: 0;
}
.configPicker > button {
min-width: 0;
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.chipDetail {
display: none;
}
.modelDetail {
flex-shrink: 0;
max-width: 65%;
}
.inlineSetting {
display: none;
}
.settingsMenu {
display: flex;
flex: none;
margin-left: auto;
}
.actions {
width: auto;
flex: none;
margin-left: 0;
justify-content: flex-end;
}
.actions .spacer {
display: none;
}
}
.pickerValue {
display: inline-flex;
align-items: baseline;
+3 -1
Переглянути файл
@@ -1323,7 +1323,9 @@ export function Composer(props: ComposerProps) {
)}
<div ref={hostRef} className={styles.field} />
<div className={styles.bar} onMouseDown={(e) => e.stopPropagation()}>
<div className={styles.toolbar}>{props.toolbar}</div>
<div className={styles.toolbar} data-composer-toolbar="">
{props.toolbar}
</div>
<div className={styles.actions}>
<IconButton
ref={addAnchor}
+144 -25
Переглянути файл
@@ -1,7 +1,7 @@
import { fireEvent, render, screen, within } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { AgentConfigOption } from "@/bindings";
import { ConfigPickers, configPickerOptions } from "./ConfigPickers";
import { ConfigPickers, computeOverflowLayout, configPickerOptions } from "./ConfigPickers";
import { useAgents } from "./store";
beforeEach(() => {
@@ -95,7 +95,7 @@ describe("configPickerOptions", () => {
});
});
it("shows Cursor approvals separately from its execution mode and sends the choice", () => {
it("tucks Cursor approvals into the mode popup as a switch and sends the choice", () => {
const option = (id: string, category: string, values: string[]): AgentConfigOption => ({
id,
category,
@@ -110,19 +110,19 @@ it("shows Cursor approvals separately from its execution mode and sends the choi
})),
});
const onChange = vi.fn();
render(
<ConfigPickers
config={[
option("mode", "mode", ["Agent", "Plan", "Ask"]),
option("openidea.cursor.approval", "approval", ["ask", "bypass"]),
]}
onChange={onChange}
/>,
);
expect(screen.getByText("Agent")).toBeVisible();
fireEvent.click(screen.getByLabelText("Approvals"));
fireEvent.click(screen.getByRole("option", { name: "Bypass approvals" }));
const cfg = [
option("mode", "mode", ["Agent", "Plan", "Ask"]),
option("openidea.cursor.approval", "approval", ["ask", "bypass"]),
];
const { rerender } = render(<ConfigPickers config={cfg} onChange={onChange} />);
expect(screen.getByRole("button", { name: "Mode" })).toHaveTextContent("Agent");
expect(screen.queryByRole("button", { name: "Approvals" })).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Mode" }));
fireEvent.click(screen.getByRole("switch", { name: "Bypass approvals" }));
expect(onChange).toHaveBeenCalledWith("openidea.cursor.approval", "bypass");
rerender(<ConfigPickers config={cfg} values={{ "openidea.cursor.approval": "bypass" }} onChange={onChange} />);
expect(screen.getByRole("button", { name: "Mode" })).toHaveTextContent("AgentBypass");
});
it("shows Allow All as a switch and sends on/off values", () => {
@@ -344,13 +344,15 @@ describe("model settings", () => {
expect(screen.getByRole("button", { name: "Mode" })).toHaveTextContent("AgentAllow All");
fireEvent.click(settings);
const dialog = screen.getByRole("dialog", { name: "Model settings" });
const effort = within(dialog).getByRole("radiogroup", { name: "Effort Level" });
expect(within(effort).getByRole("radio", { name: "medium" })).toHaveAttribute("aria-checked", "true");
fireEvent.click(within(effort).getByRole("radio", { name: "XHigh" }));
const effort = within(dialog).getByRole("listbox", { name: "Effort Level" });
expect(within(effort).getByRole("option", { name: "medium" })).toHaveAttribute("aria-selected", "true");
fireEvent.click(within(effort).getByRole("option", { name: "XHigh" }));
expect(onChange).toHaveBeenCalledExactlyOnceWith("reasoning_effort", "xhigh");
// The only setting: choosing it closes the popup.
expect(screen.queryByRole("dialog", { name: "Model settings" })).not.toBeInTheDocument();
});
it("lists more effort levels than fit the segmented control, one click away", () => {
it("renders effort levels consistently as a vertical list regardless of option count", () => {
const onChange = vi.fn();
const config = copilotConfig().map((o) =>
o.category === "thought_level"
@@ -366,11 +368,18 @@ describe("model settings", () => {
render(<ConfigPickers config={config} onChange={onChange} />);
fireEvent.click(screen.getByRole("button", { name: "Model settings: Max" }));
const dialog = screen.getByRole("dialog", { name: "Model settings" });
expect(within(dialog).queryByRole("radiogroup", { name: "Effort Level" })).not.toBeInTheDocument();
expect(within(dialog).queryByRole("radiogroup")).not.toBeInTheDocument();
expect(within(dialog).queryByRole("button", { name: /Reasoning Effort/ })).not.toBeInTheDocument();
const levels = within(dialog).getByRole("listbox", { name: "Effort Level" });
expect(within(levels).getByRole("option", { name: /Max/ })).toHaveAttribute("aria-selected", "true");
fireEvent.click(within(levels).getByRole("option", { name: /Extra high/ }));
// Clicking the already-selected value in a single-setting popup closes it without emitting a redundant change.
fireEvent.click(within(levels).getByRole("option", { name: /Max/ }));
expect(onChange).not.toHaveBeenCalled();
expect(screen.queryByRole("dialog", { name: "Model settings" })).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Model settings: Max" }));
const reopened = screen.getByRole("dialog", { name: "Model settings" });
fireEvent.click(within(reopened).getByRole("option", { name: /Extra high/ }));
expect(onChange).toHaveBeenCalledExactlyOnceWith("reasoning_effort", "extra-high");
// The only setting: choosing it is done.
expect(screen.queryByRole("dialog", { name: "Model settings" })).not.toBeInTheDocument();
@@ -442,11 +451,11 @@ describe("model settings", () => {
fireEvent.click(settings);
const dialog = screen.getByRole("dialog", { name: "Model settings" });
expect(within(dialog).queryByRole("button", { name: "Back to models" })).not.toBeInTheDocument();
const effortGroup = within(dialog).getByRole("radiogroup", { name: "Effort Level" });
expect(within(effortGroup).getByRole("radio", { name: "medium" })).toHaveAttribute("aria-checked", "true");
const contextGroup = within(dialog).getByRole("radiogroup", { name: "Context Size" });
expect(within(contextGroup).getByRole("radio", { name: "1M" })).toHaveAttribute("aria-checked", "true");
fireEvent.click(within(contextGroup).getByRole("radio", { name: "200K" }));
const effortList = within(dialog).getByRole("listbox", { name: "Effort Level" });
expect(within(effortList).getByRole("option", { name: "medium" })).toHaveAttribute("aria-selected", "true");
const contextList = within(dialog).getByRole("listbox", { name: "Context Size" });
expect(within(contextList).getByRole("option", { name: "1M" })).toHaveAttribute("aria-selected", "true");
fireEvent.click(within(contextList).getByRole("option", { name: "200K" }));
expect(onChange).toHaveBeenCalledExactlyOnceWith("contextTier", "default");
// Several settings: the popup stays for the next one.
expect(screen.getByRole("dialog", { name: "Model settings" })).toBeInTheDocument();
@@ -465,8 +474,118 @@ describe("model settings", () => {
expect(onChange).toHaveBeenLastCalledWith("model", "gpt-6-sol");
});
it("treats Cursor context option id as Context Size in chip summary and popup", () => {
const onChange = vi.fn();
const cfg = copilotConfig();
cfg.push({
id: "context",
name: "Context",
category: "model_config",
description: null,
current: "1m",
defaultValue: "300k",
via: "option",
values: [value("300k", "300K"), value("1m", "1M")],
});
render(<ConfigPickers config={cfg} onChange={onChange} />);
const settings = screen.getByRole("button", { name: /^Model settings:/ });
expect(settings).toHaveTextContent("medium · 1M");
fireEvent.click(settings);
const dialog = screen.getByRole("dialog", { name: "Model settings" });
const contextList = within(dialog).getByRole("listbox", { name: "Context Size" });
fireEvent.click(within(contextList).getByRole("option", { name: "300K" }));
expect(onChange).toHaveBeenCalledExactlyOnceWith("context", "300k");
});
it("keeps a plain model picker when the agent has no effort option", () => {
render(<ConfigPickers config={copilotConfig(null)} onChange={vi.fn()} />);
expect(screen.getByRole("button", { name: "Model" })).toHaveAttribute("aria-haspopup", "listbox");
});
it("omits off switches from multi-setting summaries and shows them concisely when on", () => {
const cfg = copilotConfig();
cfg.push(
{
id: "context",
name: "Context",
category: "model_config",
description: null,
current: "500k",
via: "option",
values: [value("500k", "500K")],
},
{
id: "fast",
name: "Fast",
category: "model_config",
description: null,
current: "false",
via: "option",
values: [value("false", "Off"), value("true", "Fast")],
},
);
const { rerender } = render(<ConfigPickers config={cfg} onChange={vi.fn()} />);
const settings = screen.getByRole("button", { name: /^Model settings:/ });
expect(settings).toHaveTextContent("medium · 500K");
expect(settings).toHaveAttribute("title", expect.stringContaining("Fast: Off"));
rerender(<ConfigPickers config={cfg} values={{ fast: "true" }} onChange={vi.fn()} />);
expect(screen.getByRole("button", { name: /^Model settings:/ })).toHaveTextContent("medium · 500K · Fast");
});
});
describe("computeOverflowLayout", () => {
const base = {
gap: 2,
fixedWidths: [38, 220], // agent icon + model/settings
secondaryWidths: [120, 90], // mode (with detail) + collaboration mode
detailWidth: 45,
detailIndex: 0,
menuWidth: 24,
};
it("keeps everything visible when the toolbar fits", () => {
// 38 + 220 + 120 + 90 + 3*2 = 474
expect(computeOverflowLayout({ ...base, available: 500 })).toEqual({
compactDetail: false,
collapsedCount: 0,
});
});
it("hides chip detail before collapsing any secondary picker", () => {
// 474 - 45 = 429
expect(computeOverflowLayout({ ...base, available: 440 })).toEqual({
compactDetail: true,
collapsedCount: 0,
});
});
it("collapses trailing secondary pickers one by one as space shrinks", () => {
// Keep mode (full 120) + menu (24): 38 + 220 + 120 + 24 + 3*2 = 408
expect(computeOverflowLayout({ ...base, available: 410 })).toEqual({
compactDetail: false,
collapsedCount: 1,
});
// Keep mode (compact 75) + menu (24): 38 + 220 + 75 + 24 + 3*2 = 363
expect(computeOverflowLayout({ ...base, available: 370 })).toEqual({
compactDetail: true,
collapsedCount: 1,
});
// Collapse all secondary pickers into the menu:
expect(computeOverflowLayout({ ...base, available: 320 })).toEqual({
compactDetail: false,
collapsedCount: 2,
});
});
it("does nothing when unmeasured (available <= 0) or when there are no secondary items", () => {
expect(computeOverflowLayout({ ...base, available: 0 })).toEqual({
compactDetail: false,
collapsedCount: 0,
});
expect(computeOverflowLayout({ ...base, available: 100, secondaryWidths: [] })).toEqual({
compactDetail: false,
collapsedCount: 0,
});
});
});
+289 -133
Переглянути файл
@@ -1,7 +1,7 @@
/**
* Model and settings controls shared by the New Task and session composers.
*/
import { useEffect, useRef, useState, type KeyboardEvent } from "react";
import { useEffect, useLayoutEffect, useRef, useState } from "react";
import clsx from "clsx";
import type { AgentConfigOption } from "@/bindings";
import { useTx } from "@/platform/i18n";
@@ -74,6 +74,103 @@ function switchValues(option: AgentConfigOption): { on: string; off: string } |
return on && off ? { on, off } : null;
}
interface ModeApprovalSwitch {
on: string;
off: string;
/** Switch label inside the Mode popup footer (e.g. "Allow All", "Bypass approvals"). */
label: string;
/** Concise detail shown on the Mode chip when enabled (e.g. "Allow All", "Bypass"). */
chipLabel: string;
}
/** A two-state permissions or approval option tucked as a switch inside the Mode popup. */
function modeApprovalSwitch(option: AgentConfigOption): ModeApprovalSwitch | null {
if (option.category === "permissions") {
const sw = switchValues(option);
return sw ? { ...sw, label: option.name, chipLabel: option.name } : null;
}
if (option.category === "approval" && option.values.length === 2) {
const on = option.values.find((v) => v.value.toLowerCase() === "bypass");
const off = option.values.find((v) => v !== on);
if (on && off) {
return { on: on.value, off: off.value, label: on.name || option.name, chipLabel: "Bypass" };
}
}
return null;
}
export interface OverflowInput {
available: number;
gap: number;
fixedWidths: readonly number[];
secondaryWidths: readonly number[];
detailWidth: number;
detailIndex: number;
menuWidth: number;
}
export interface OverflowLayout {
/** Hide secondary detail text inside chips (e.g. "Allow All" / "Bypass") before collapsing items. */
compactDetail: boolean;
/** Number of trailing secondary items moved into the overflow settings menu. */
collapsedCount: number;
}
/**
* Decides how many secondary pickers fit on a single toolbar row before spilling into the
* settings menu: first drops optional chip detail labels, then collapses trailing secondary
* items one by one from right to left.
*/
export function computeOverflowLayout({
available,
gap,
fixedWidths,
secondaryWidths,
detailWidth,
detailIndex,
menuWidth,
}: OverflowInput): OverflowLayout {
if (available <= 0 || secondaryWidths.length === 0) {
return { compactDetail: false, collapsedCount: 0 };
}
const fixedCount = fixedWidths.length;
const fixedTotal = fixedWidths.reduce((sum, w) => sum + w, 0);
const widthFor = (kept: number, compactDetail: boolean): number => {
const hasMenu = kept < secondaryWidths.length;
const itemCount = fixedCount + kept + (hasMenu ? 1 : 0);
if (itemCount === 0) return 0;
let total = fixedTotal;
for (let i = 0; i < kept; i++) total += secondaryWidths[i]!;
if (compactDetail && detailWidth > 0 && detailIndex >= 0 && detailIndex < kept) {
total -= detailWidth;
}
if (hasMenu) total += menuWidth;
return total + gap * (itemCount - 1);
};
if (widthFor(secondaryWidths.length, false) <= available) {
return { compactDetail: false, collapsedCount: 0 };
}
if (detailWidth > 0 && detailIndex >= 0 && widthFor(secondaryWidths.length, true) <= available) {
return { compactDetail: true, collapsedCount: 0 };
}
for (let collapsed = 1; collapsed <= secondaryWidths.length; collapsed++) {
const kept = secondaryWidths.length - collapsed;
if (kept === 0) return { compactDetail: false, collapsedCount: collapsed };
if (widthFor(kept, false) <= available) {
return { compactDetail: false, collapsedCount: collapsed };
}
if (detailWidth > 0 && detailIndex >= 0 && detailIndex < kept && widthFor(kept, true) <= available) {
return { compactDetail: true, collapsedCount: collapsed };
}
}
return { compactDetail: false, collapsedCount: secondaryWidths.length };
}
const selected = (option: AgentConfigOption, value: string | null) =>
option.values.find((v) => v.value === value) ?? null;
@@ -103,7 +200,9 @@ export function ConfigPickers({
}) {
const tx = useTx();
const [open, setOpen] = useState(false);
const [overflow, setOverflow] = useState<OverflowLayout>({ compactDetail: false, collapsedCount: 0 });
const anchor = useRef<HTMLButtonElement>(null);
const menuRef = useRef<HTMLDivElement>(null);
const options = mainOptions(config);
if (modelRefresh?.draft && !options.some((o) => o.category === "model"))
options.unshift({
@@ -124,53 +223,144 @@ export function ConfigPickers({
const tuckedEffort = combinedModel ? (effort ?? null) : null;
const tuckedModelConfig = new Set(modelConfigs.map((o) => o.id));
const mode = options.find((o) => o.category === "mode");
const allowAll = mode && options.find((o) => switchValues(o));
const allowAll = mode && options.find((o) => !!modeApprovalSwitch(o));
const inline = options.filter(
(o) => o !== effort && o !== allowAll && !(combinedModel && tuckedModelConfig.has(o.id)),
);
if (effort && !tuckedEffort) inline.splice(model ? inline.indexOf(model) + 1 : 0, 0, effort);
// The compact menu holds everything but the model, effort, and model-specific parameters.
const collapsible = inline.filter((o) => o.category !== "model" && o !== effort);
// The overflow menu holds everything except the model, effort, and model-specific parameters.
const secondary = options.filter(
(o) => o.category !== "model" && o !== effort && !(combinedModel && tuckedModelConfig.has(o.id)),
);
const signature = [
...inline.map((o) => `${o.id}:${valueOf(o) ?? ""}`),
...(tuckedEffort ? [`${tuckedEffort.id}:${valueOf(tuckedEffort) ?? ""}`] : []),
...modelConfigs.map((o) => `${o.id}:${valueOf(o) ?? ""}`),
allowAll ? `${allowAll.id}:${valueOf(allowAll) ?? ""}` : "",
modelRefresh?.loadingSettings ? "loading" : "",
].join("|");
useLayoutEffect(() => {
const menuEl = menuRef.current;
const toolbar = menuEl?.closest<HTMLElement>("[data-composer-toolbar]");
if (!toolbar) return;
const measure = () => {
const style = getComputedStyle(toolbar);
const padX = (parseFloat(style.paddingLeft) || 0) + (parseFloat(style.paddingRight) || 0);
const available = toolbar.getBoundingClientRect().width - padX;
if (available <= 0) return;
toolbar.classList.add(styles.toolbarMeasuring!);
const gap = parseFloat(style.columnGap) || 0;
const fixedWidths: number[] = [];
const secondaryWidths: number[] = [];
let detailWidth = 0;
let detailIndex = -1;
let menuWidth = 0;
for (const child of Array.from(toolbar.children) as HTMLElement[]) {
if (child.hasAttribute("data-config-menu")) {
menuWidth = child.getBoundingClientRect().width;
continue;
}
if (child.hasAttribute("data-config-secondary")) {
const idx = secondaryWidths.length;
secondaryWidths.push(child.getBoundingClientRect().width);
const detail = child.querySelector<HTMLElement>("[data-chip-detail]");
if (detail) {
const chipGap = parseFloat(getComputedStyle(detail.parentElement!).columnGap) || 0;
detailWidth = detail.getBoundingClientRect().width + chipGap;
detailIndex = idx;
}
continue;
}
const w = child.getBoundingClientRect().width;
if (w > 0) fixedWidths.push(w);
}
toolbar.classList.remove(styles.toolbarMeasuring!);
const next = computeOverflowLayout({
available,
gap,
fixedWidths,
secondaryWidths,
detailWidth,
detailIndex,
menuWidth,
});
setOverflow((prev) => {
if (prev.compactDetail === next.compactDetail && prev.collapsedCount === next.collapsedCount) return prev;
if (prev.collapsedCount > 0 && next.collapsedCount === 0) setOpen(false);
return next;
});
};
measure();
const ro = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(measure);
ro?.observe(toolbar);
const mo = typeof MutationObserver === "undefined" ? null : new MutationObserver(measure);
mo?.observe(toolbar, { childList: true });
return () => {
ro?.disconnect();
mo?.disconnect();
};
}, [signature, tx]);
const collapsedCount = Math.min(overflow.collapsedCount, collapsible.length);
const modeIndex = mode ? collapsible.indexOf(mode) : -1;
const modeVisible = modeIndex >= 0 && modeIndex < collapsible.length - collapsedCount;
const approval = secondary.find((o) => o.category === "approval" || o.category === "mode");
const summary = secondary.map((o) => `${tx(o.name)}: ${selected(o, valueOf(o))?.name ?? tx("Default")}`).join(" · ");
return (
<>
{inline.map((o) => (
<span
key={o.id}
className={clsx(styles.configPicker, o.category !== "model" && o !== effort && styles.inlineSetting)}
>
{o === model && combinedModel ? (
<ModelPicker
model={o}
modelValue={valueOf(o)}
settings={(tuckedEffort ? [tuckedEffort, ...modelConfigs] : modelConfigs)
.filter((opt) => opt.values.length > 0)
.map((opt) => ({ ...opt, current: valueOf(opt) }))}
onChange={onChange}
modelRefresh={modelRefresh}
/>
) : o === mode && allowAll ? (
<ModePicker
mode={o}
modeValue={valueOf(o)}
allowAll={allowAll}
allowAllValue={valueOf(allowAll)}
onChange={onChange}
/>
) : (
<ConfigPicker option={o} value={valueOf(o)} onChange={onChange} />
)}
{o === model && !combinedModel && modelRefresh?.loadingSettings && <LoadingSettingsChip />}
</span>
))}
{inline.map((o) => {
const secondaryIndex = collapsible.indexOf(o);
const isSecondary = secondaryIndex >= 0;
const collapsed = isSecondary && secondaryIndex >= collapsible.length - collapsedCount;
return (
<span
key={o.id}
data-config-secondary={isSecondary ? "" : undefined}
className={clsx(styles.configPicker, isSecondary && styles.inlineSetting, collapsed && styles.collapsed)}
>
{o === model && combinedModel ? (
<ModelPicker
model={o}
modelValue={valueOf(o)}
settings={(tuckedEffort ? [tuckedEffort, ...modelConfigs] : modelConfigs)
.filter((opt) => opt.values.length > 0)
.map((opt) => ({ ...opt, current: valueOf(opt) }))}
onChange={onChange}
modelRefresh={modelRefresh}
/>
) : o === mode && allowAll ? (
<ModePicker
mode={o}
modeValue={valueOf(o)}
allowAll={allowAll}
allowAllValue={valueOf(allowAll)}
compactDetail={overflow.compactDetail}
onChange={onChange}
/>
) : (
<ConfigPicker option={o} value={valueOf(o)} onChange={onChange} />
)}
{o === model && !combinedModel && modelRefresh?.loadingSettings && <LoadingSettingsChip />}
</span>
);
})}
{secondary.length > 0 && (
<div className={styles.settingsMenu}>
<div
ref={menuRef}
data-config-menu=""
className={clsx(styles.settingsMenu, collapsedCount > 0 && styles.settingsMenuVisible)}
>
<IconButton
ref={anchor}
icon={approval ? modeIcon(valueOf(approval) ?? "") : "settings"}
icon={!modeVisible && approval ? modeIcon(valueOf(approval) ?? "") : "settings"}
title={`${tx("Agent settings")}: ${summary}`}
aria-label={tx("Agent settings")}
aria-haspopup="dialog"
@@ -252,9 +442,6 @@ function ConfigPicker({
);
}
/** Values a setting shows as a segmented control; a longer list (Codex has six effort levels) is listed. */
const SEGMENTED_MAX = 5;
function settingName(option: AgentConfigOption) {
return option.category === "thought_level"
? "Effort Level"
@@ -267,13 +454,23 @@ function settingValue(option: AgentConfigOption) {
return selected(option, option.current) ?? option.values[0];
}
function settingsSummary(options: AgentConfigOption[], tx: ReturnType<typeof useTx>) {
return options
.map((o) => {
const label = settingValue(o)?.name ?? tx("Default");
return o.category === "thought_level" || isContextOption(o.id) ? label : `${tx(o.name)}: ${label}`;
})
.join(" · ");
function settingsSummary(options: AgentConfigOption[], tx: ReturnType<typeof useTx>, includeInactiveSwitches = false) {
const format = (o: AgentConfigOption) => {
const current = settingValue(o);
const label = current?.name ?? tx("Default");
const sw = switchValues(o);
if (sw) {
const isOn = current?.value === sw.on;
if (!includeInactiveSwitches && !isOn && options.length > 1) return null;
return isOn ? tx(o.name) : `${tx(o.name)}: ${label}`;
}
return o.category === "thought_level" || o.category === "context_tier" || isContextOption(o.id)
? label
: `${tx(o.name)}: ${label}`;
};
const parts = options.map(format).filter((p): p is string => p !== null);
if (parts.length > 0) return parts.join(" · ");
return options.map((o) => `${tx(o.name)}: ${settingValue(o)?.name ?? tx("Default")}`).join(" · ");
}
function ModelPicker({
@@ -301,6 +498,7 @@ function ModelPicker({
: (selectedModel?.name ?? (modelRefresh ? modelValue : null) ?? tx("Default"));
const shown = settings.filter((o) => o.values.length > 0);
const summary = settingsSummary(shown, tx);
const fullSummary = settingsSummary(shown, tx, true);
const toggle = (which: "models" | "settings") => {
if (open === which) return setOpen(null);
if (which === "models") modelRefresh?.onOpen?.();
@@ -330,7 +528,11 @@ function ModelPicker({
type="button"
className={clsx(styles.chip, styles.modelDetail)}
aria-label={tx`Model settings: ${summary}`}
title={tx`Configure ${modelName}…`}
title={
fullSummary && fullSummary !== summary
? `${tx`Configure ${modelName}…`} (${fullSummary})`
: tx`Configure ${modelName}…`
}
aria-haspopup="dialog"
aria-expanded={open === "settings"}
onClick={() => toggle("settings")}
@@ -402,9 +604,10 @@ function ModelPicker({
}
/**
* The current model's settings (effort, context size, fast mode…), each a click away: an on/off
* setting as a switch, a short list as a segmented control, a longer one listed. A model with
* one setting closes on a choice.
* The current model's settings (effort, context size, fast mode…), each a click away: on/off
* settings as a switch row, and choice settings consistently as a vertical list so every model
* shares the same layout, description display, and close behavior. A model with one setting
* closes on a choice.
*/
function ModelSettings({
settings,
@@ -421,35 +624,31 @@ function ModelSettings({
<div className={styles.quickSettings}>
{settings.map((o) => {
const label = tx(settingName(o));
const control = switchValues(o) ? (
<ConfigPicker option={o} value={o.current} onChange={onChange} framed />
) : o.values.length <= SEGMENTED_MAX ? (
<SegmentedControl
ariaLabel={label}
options={o.values.map((v) => ({ value: v.value, label: v.name, description: v.description ?? undefined }))}
value={settingValue(o)!.value}
onChange={(v) => {
onChange(o.id, v);
if (only) onDone();
}}
/>
) : (
<SelectListbox
aria-label={label}
value={settingValue(o)?.value ?? null}
options={o.values.map((v) => ({ value: v.value, label: v.name, detail: v.description ?? undefined }))}
onChoose={(v) => {
onChange(o.id, v);
if (only) onDone();
}}
/>
);
if (switchValues(o)) {
return (
<div key={o.id} className={clsx(styles.quickRow, styles.quickToggleRow)}>
<span className={styles.quickLabel} title={o.description ?? undefined}>
{label}
</span>
<ConfigPicker option={o} value={o.current} onChange={onChange} framed />
</div>
);
}
const currentValue = settingValue(o)?.value ?? null;
return (
<div key={o.id} className={styles.quickRow}>
<span className={styles.quickLabel} title={o.description ?? undefined}>
{label}
</span>
{control}
<SelectListbox
aria-label={label}
value={currentValue}
options={o.values.map((v) => ({ value: v.value, label: v.name, detail: v.description ?? undefined }))}
onChoose={(v) => {
if (v !== currentValue) onChange(o.id, v);
if (only) onDone();
}}
/>
</div>
);
})}
@@ -513,82 +712,35 @@ function CostBadge({ category }: { category: string | null | undefined }) {
);
}
/** Accessible segmented pill selector (`role="radiogroup"`) with Left/Right arrow navigation. */
export function SegmentedControl({
ariaLabel,
options,
value,
onChange,
}: {
ariaLabel: string;
options: readonly { value: string; label: string; description?: string }[];
value: string;
onChange: (value: string) => void;
}) {
const groupRef = useRef<HTMLDivElement>(null);
const currentIndex = Math.max(
0,
options.findIndex((o) => o.value === value),
);
const onKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {
if (e.key !== "ArrowLeft" && e.key !== "ArrowRight") return;
e.preventDefault();
const delta = e.key === "ArrowRight" ? 1 : -1;
const nextIndex = (currentIndex + delta + options.length) % options.length;
const next = options[nextIndex];
if (!next) return;
onChange(next.value);
const buttons = groupRef.current?.querySelectorAll<HTMLButtonElement>('button[role="radio"]');
buttons?.[nextIndex]?.focus();
};
return (
<div ref={groupRef} role="radiogroup" aria-label={ariaLabel} className={styles.segmented} onKeyDown={onKeyDown}>
{options.map((opt, idx) => {
const active = idx === currentIndex;
return (
<button
key={opt.value}
type="button"
role="radio"
aria-checked={active}
tabIndex={active ? 0 : -1}
title={opt.description}
className={clsx(styles.segment, active && styles.segmentActive)}
onClick={() => {
if (opt.value !== value) onChange(opt.value);
}}
>
{opt.label}
</button>
);
})}
</div>
);
}
/** The mode menu, with the agent's on/off permissions option (Allow All) as a switch under it. */
/** The mode menu, with the agent's two-state permissions or approval option as a switch under it. */
function ModePicker({
mode,
modeValue,
allowAll,
allowAllValue,
compactDetail = false,
onChange,
}: {
mode: AgentConfigOption;
modeValue: string | null;
allowAll: AgentConfigOption;
allowAllValue: string | null;
compactDetail?: boolean;
onChange: (option: string, value: string) => void;
}) {
const tx = useTx();
const [open, setOpen] = useState(false);
const anchor = useRef<HTMLButtonElement>(null);
const toggle = switchValues(allowAll)!;
const toggle = modeApprovalSwitch(allowAll)!;
const current = selected(mode, modeValue);
const on = allowAllValue === toggle.on;
const summary = `${tx(mode.name)}: ${current?.name ?? tx("Default")} · ${tx(allowAll.name)}: ${on ? tx("On") : tx("Off")}`;
const approvalText =
allowAll.category === "approval"
? (selected(allowAll, allowAllValue)?.name ?? (on ? tx("On") : tx("Off")))
: on
? tx("On")
: tx("Off");
const summary = `${tx(mode.name)}: ${current?.name ?? tx("Default")} · ${tx(allowAll.name)}: ${approvalText}`;
return (
<>
<button
@@ -603,7 +755,11 @@ function ModePicker({
>
<Icon name={on ? "unlock" : modeIcon(current?.value ?? "")} size={14} />
<span className={styles.chipValue}>{current?.name ?? tx("Default")}</span>
{on && <span className={styles.chipDetail}>{tx(allowAll.name)}</span>}
{on && (
<span className={clsx(styles.chipDetail, compactDetail && styles.compactDetail)} data-chip-detail="">
{tx(toggle.chipLabel)}
</span>
)}
<Icon name="chevron-down" size={14} className={styles.chipChevron} />
</button>
<Popup
@@ -634,10 +790,10 @@ function ModePicker({
))}
</div>
<div className={styles.modeFooter}>
<span title={allowAll.description ?? undefined}>{tx(allowAll.name)}</span>
<span title={allowAll.description ?? undefined}>{tx(toggle.label)}</span>
<Toggle
checked={on}
aria-label={tx(allowAll.name)}
aria-label={tx(toggle.label)}
onChange={(checked) => onChange(allowAll.id, checked ? toggle.on : toggle.off)}
/>
</div>
+75 -18
Переглянути файл
@@ -102,9 +102,8 @@ async function chooseModel(model: string) {
async function chooseEffort(effort: string) {
fireEvent.click(settingsButton());
const group = screen.getByRole("radiogroup", { name: "Effort Level" });
fireEvent.click(within(group).getByRole("radio", { name: effort }));
fireEvent.keyDown(document, { key: "Escape" });
const list = screen.getByRole("listbox", { name: "Effort Level" });
fireEvent.click(within(list).getByRole("option", { name: effort }));
}
it("switches model-specific levels and restores each draft effort before starting", async () => {
@@ -190,21 +189,79 @@ it("ignores old provider-wide effort choices and refreshes unsupported per-model
});
it.each([
[undefined, "full-access"],
["ask", undefined],
] as const)("with new-task approvals %s, sends mode %s", async (newTaskApprovals, mode) => {
const provider = { ...backend.providers[0]!, config: [option("mode", "mode", ["ask", "full-access"], "ask")] };
useAgents.setState({ providers: [provider] });
const settings = useProject.getState().settings;
useProject.setState({ settings: { ...settings, agents: { ...settings?.agents, newTaskApprovals } } as never });
try {
render(<HomeEditor />);
fireEvent.click(screen.getByRole("button", { name: "Start" }));
await waitFor(() => expect(backend.create).toHaveBeenCalled());
expect(backend.create.mock.calls[0]![0].config.find((c: { id: string }) => c.id === "mode")?.value).toBe(mode);
} finally {
useProject.setState({ settings });
}
[undefined, "ask", "full-access"],
["ask", "ask", "ask"],
["ask", "full-access", "ask"],
] as const)(
"with new-task approvals %s and agent default %s, sends mode %s",
async (newTaskApprovals, agentDefault, mode) => {
const provider = {
...backend.providers[0]!,
config: [option("mode", "mode", ["ask", "full-access"], agentDefault)],
};
useAgents.setState({ providers: [provider] });
const settings = useProject.getState().settings;
useProject.setState({ settings: { ...settings, agents: { ...settings?.agents, newTaskApprovals } } as never });
try {
render(<HomeEditor />);
fireEvent.click(screen.getByRole("button", { name: "Start" }));
await waitFor(() => expect(backend.create).toHaveBeenCalled());
expect(backend.create.mock.calls[0]![0].config.find((c: { id: string }) => c.id === "mode")?.value).toBe(mode);
} finally {
useProject.setState({ settings });
}
},
);
it("switches Cursor per-model context and fast options cleanly without sending stale model params", async () => {
const cursor: AgentProvider = {
...backend.providers[0]!,
id: "cursor",
name: "Cursor",
config: [
option("mode", "mode", ["agent", "plan", "ask"], "agent"),
option("model", "model", ["grok-4.7", "gemini-4-neon"], "grok-4.7"),
option("openidea.cursor.approval", "approval", ["ask", "bypass"], "ask"),
],
thoughtLevels: {
"grok-4.7": [
option("reasoning_effort", "thought_level", ["low", "high"], "high"),
option("context", "model_config", ["256k", "500k"], "256k"),
{
id: "fast",
category: "model_config",
name: "Fast",
description: null,
current: "true",
defaultValue: "true",
via: "option",
values: [
{ value: "false", name: "Off", description: null },
{ value: "true", name: "Fast", description: null },
],
},
],
"gemini-4-neon": [
option("reasoning_effort", "thought_level", ["low", "high"], "high"),
option("context", "model_config", ["300k", "1m"], "300k"),
],
},
};
useAgents.setState({ providers: [cursor], draft: savedDraft({ provider: "cursor", config: {} }) });
render(<HomeEditor />);
// Cursor defaults fast off even though the agent reported true, and omits off switches from multi-setting summaries.
expect(settingsButton()).toHaveTextContent("high · 256k");
await chooseModel("gemini-4-neon");
expect(settingsButton()).toHaveTextContent("high · 300k");
fireEvent.click(screen.getByRole("button", { name: "Start" }));
await waitFor(() => expect(backend.create).toHaveBeenCalled());
expect(backend.create.mock.calls[0]![0].config).toEqual([
{ id: "mode", value: "agent" },
{ id: "model", value: "gemini-4-neon" },
{ id: "openidea.cursor.approval", value: "bypass" },
{ id: "reasoning_effort", value: "high" },
{ id: "context", value: "300k" },
]);
});
it("applies fitWidth on the New Task page only when fitWindowWidth is enabled", () => {
+2 -2
Переглянути файл
@@ -101,9 +101,9 @@ export function HomeEditor({ docked = false, input }: { docked?: boolean; input?
const catalog = useAgents((s) => s.modelCatalogs.get(provider?.id ?? ""));
const requestingModels = useAgents((s) => s.modelRequests.has(provider?.id ?? ""));
const requestTarget = useAgents((s) => s.modelRequestTargets.get(provider?.id ?? ""));
const { defaults, fitWindowWidth } = useAgentSettings();
const { defaults, fitWindowWidth, newTaskApprovals } = useAgentSettings();
const providerDefaults = (provider && defaults[provider.id]) || {};
const config = draftConfig(provider, draft, providerDefaults);
const config = draftConfig(provider, draft, providerDefaults, newTaskApprovals);
const model = config.find((o) => o.category === "model");
const selectedModel = model?.current ?? null;
const selectedModelRef = useRef(selectedModel);
+125 -2
Переглянути файл
@@ -813,7 +813,7 @@ describe("the agent list", () => {
closeSettings();
dispose();
});
const open = async (commands: FakeCommands, backend = new FakeBackend()) => {
const open = async (commands: FakeCommands, backend = new FakeBackend(), regionName = "Claude Code") => {
dispose = registerSettingsPage({
id: REGISTRY_PAGE,
title: "Agents",
@@ -825,7 +825,7 @@ describe("the agent list", () => {
<MessagesHost />
</>,
);
await screen.findByRole("region", { name: "Claude Code" });
await screen.findByRole("region", { name: regionName });
return backend;
};
const model = {
@@ -906,6 +906,129 @@ describe("the agent list", () => {
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("Opus");
});
it("shows Cursor per-model defaults, prunes stale choices on model switch, and fetches unknown models", async () => {
const commands = new FakeCommands();
const refreshModels = vi.fn().mockResolvedValue({
provider: "cursor",
config: [],
thoughtLevels: {
"gemini-4-neon": [
{
id: "context",
name: "Context",
description: null,
category: "model_config",
current: "300k",
defaultValue: "300k",
via: "option",
values: [
{ value: "300k", name: "300K", description: null },
{ value: "1m", name: "1M", description: null },
],
},
],
},
refreshing: false,
refreshedAtMs: Date.now(),
retryAtMs: null,
error: null,
});
Object.assign(commands, { refreshModels });
commands.list = [
{
...claudeProvider("cursor"),
id: "cursor",
name: "Cursor",
config: [
{
id: "model",
name: "Model",
description: null,
category: "model",
current: "grok-4.7",
defaultValue: "grok-4.7",
via: "option",
values: [
{ value: "grok-4.7", name: "Grok 4.7", description: null },
{ value: "gemini-4-neon", name: "Gemini 4 Neon", description: null },
],
},
{
id: "openidea.cursor.approval",
name: "Approvals",
description: null,
category: "approval",
current: "bypass",
defaultValue: "ask",
via: "option",
values: [
{ value: "ask", name: "Ask for approval", description: null },
{ value: "bypass", name: "Bypass approvals", description: null },
],
},
],
thoughtLevels: {
"grok-4.7": [
{
id: "context",
name: "Context",
description: null,
category: "model_config",
current: "256k",
defaultValue: "256k",
via: "option",
values: [
{ value: "256k", name: "256K", description: null },
{ value: "500k", name: "500K", description: null },
],
},
{
id: "fast",
name: "Fast",
description: null,
category: "model_config",
current: "true",
defaultValue: "true",
via: "option",
values: [
{ value: "false", name: "Off", description: null },
{ value: "true", name: "Fast", description: null },
],
},
],
},
},
];
await open(commands, new FakeBackend(), "Cursor");
// Policy-overridden defaults say "Default (...)" rather than claiming to be the agent's own default.
expect(screen.getByRole("button", { name: "Approvals" })).toHaveTextContent("Default (Bypass approvals)");
expect(screen.getByRole("button", { name: "Fast" })).toHaveTextContent("Default (Off)");
expect(screen.getByRole("button", { name: "Context" })).toHaveTextContent("Agent's default (256K)");
// Pick a Grok-only context value and Fast=On, then switch to Gemini 4 Neon.
fireEvent.click(screen.getByRole("button", { name: "Context" }));
fireEvent.click(await screen.findByRole("option", { name: "500K" }));
expect(screen.getByRole("button", { name: "Context" })).toHaveTextContent("500K");
// Switch to a model whose per-model options aren't cached yet: Settings fetches them lazily.
fireEvent.click(screen.getByRole("button", { name: "Model" }));
fireEvent.click(await screen.findByRole("option", { name: "Gemini 4 Neon" }));
await waitFor(() => expect(refreshModels).toHaveBeenCalledWith("cursor", "gemini-4-neon"));
// The stale Grok-only choice (`500k`) is surfaced clearly as unavailable until reset or changed.
await waitFor(() =>
expect(screen.getByRole("button", { name: "Context" })).toHaveTextContent("500k (unavailable)"),
);
expect(screen.queryByRole("button", { name: "Fast" })).toBeNull();
// Switching back to a known model (Grok 4.7) after picking a Gemini-only value (`1m`) prunes the stale choice.
fireEvent.click(screen.getByRole("button", { name: "Context" }));
fireEvent.click(await screen.findByRole("option", { name: "1M" }));
expect(screen.getByRole("button", { name: "Context" })).toHaveTextContent("1M");
fireEvent.click(screen.getByRole("button", { name: "Model" }));
fireEvent.click(await screen.findByRole("option", { name: "Grok 4.7" }));
expect(screen.getByRole("button", { name: "Context" })).toHaveTextContent("Agent's default (256K)");
});
it("says when an agent's settings aren't known yet", async () => {
const commands = new FakeCommands();
commands.list = [claudeProvider("claude")];
+39 -4
Переглянути файл
@@ -2,9 +2,12 @@ import { describe, expect, it } from "vitest";
import type { AgentConfigOption, AgentEntry, AgentStatus, AgentTask } from "@/bindings";
import {
applyCompletion,
approvalDefaults,
atEdgeLine,
bypassDefaults,
cursorModelDefaults,
isContextOption,
isPerModelOption,
modelConfigOptions,
canSend,
completionAt,
@@ -289,13 +292,45 @@ describe("agent composer", () => {
expect(atEdgeLine("a\nb", 1, 1)).toBe(false);
});
it("defaults Cursor fast mode off when available", () => {
it("defaults Cursor fast mode off even when context precedes fast", () => {
const context = option("model_config", ["256k", "500k"], "256k");
context.id = "context";
context.name = "Context";
const fast = option("model_config", ["false", "true"], "true");
fast.id = "fast";
fast.name = "Fast";
expect(cursorModelDefaults("cursor", [fast])).toEqual({ fast: "false" });
expect(cursorModelDefaults("claude", [fast])).toEqual({});
expect(modelConfigOptions([fast]).map((o) => o.id)).toEqual(["fast"]);
expect(isContextOption("context")).toBe(true);
expect(isPerModelOption(context)).toBe(true);
expect(isPerModelOption(fast)).toBe(true);
expect(cursorModelDefaults("cursor", [context, fast])).toEqual({ fast: "false" });
expect(cursorModelDefaults("claude", [context, fast])).toEqual({});
expect(modelConfigOptions([context, fast]).map((o) => o.id)).toEqual(["context", "fast"]);
});
it("resolves bypass and ask approval defaults across mode, permissions, and approval options", () => {
const codexMode: AgentConfigOption = {
...option("mode", ["read-only", "ask", "auto", "full-access"], "full-access"),
defaultValue: "auto",
};
const permissions: AgentConfigOption = {
...option("allow_all", ["off", "on"], "off"),
category: "permissions",
defaultValue: "off",
};
const approval: AgentConfigOption = {
...option("openidea.cursor.approval", ["ask", "bypass"], "bypass"),
category: "approval",
defaultValue: "ask",
};
expect(approvalDefaults([codexMode, permissions, approval], "bypass")).toEqual({
mode: "full-access",
allow_all: "on",
"openidea.cursor.approval": "bypass",
});
expect(approvalDefaults([codexMode, permissions, approval], "ask")).toEqual({
mode: "auto",
"openidea.cursor.approval": "ask",
});
});
it("picks the main settings and cycles the mode", () => {
+45 -8
Переглянути файл
@@ -452,21 +452,28 @@ export function atEdgeLine(text: string, caret: number, dir: -1 | 1): boolean {
return dir < 0 ? !text.slice(0, caret).includes("\n") : !text.slice(caret).includes("\n");
}
export const isContextOption = (id: string) => /^(context_tier|contextTier)$/.test(id);
export const isContextOption = (id: string) => /^(context|context_tier|contextTier)$/.test(id);
export const isFastOption = (id: string) => id === "fast";
/** Whether an option's available values and default belong to the selected model rather than the provider. */
export const isPerModelOption = (o: AgentConfigOption) =>
o.category === "thought_level" || o.category === "context_tier" || isContextOption(o.id);
o.category === "thought_level" ||
o.category === "context_tier" ||
o.category === "model_config" ||
isFastOption(o.id) ||
isContextOption(o.id);
const matchesCategory = (o: AgentConfigOption, category: string) =>
o.category === category ||
(category === "model_config" &&
(o.category === "model_config" || o.category === "context_tier" || o.id === "fast" || isContextOption(o.id)));
(o.category === "model_config" || o.category === "context_tier" || isFastOption(o.id) || isContextOption(o.id)));
/** Cursor / ACP model parameters (`fast`, `contextTier`…), separate from the model id itself. */
/** Cursor / ACP model parameters (`fast`, `context`, `contextTier`…), separate from the model id itself. */
export function modelConfigOptions(config: readonly AgentConfigOption[]): AgentConfigOption[] {
return config.filter(
(o) => o.category === "model_config" || o.category === "context_tier" || o.id === "fast" || isContextOption(o.id),
(o) =>
o.category === "model_config" || o.category === "context_tier" || isFastOption(o.id) || isContextOption(o.id),
);
}
@@ -479,13 +486,13 @@ export function mainOptions(config: readonly AgentConfigOption[]): AgentConfigOp
});
}
/** Cursor defaults to Fast; prefer standard Composer unless the user chose otherwise. */
/** Cursor defaults to Fast; prefer standard speed unless the user chose otherwise. */
export function cursorModelDefaults(
providerId: string | undefined,
config: readonly AgentConfigOption[],
): Record<string, string> {
if (providerId !== "cursor") return {};
const fast = config.find((o) => o.id === "fast" || o.category === "model_config");
const fast = config.find((o) => isFastOption(o.id));
if (fast?.values.some((v) => v.value === "false")) return { [fast.id]: "false" };
return {};
}
@@ -511,7 +518,14 @@ export function modeIcon(mode: string): string {
return "lock";
}
/** The settings that approve everything without asking (a bypass mode, or approvals), by option id. */
const isBypassOptionValue = (category: string | null | undefined, value: string): boolean => {
if (category === "mode") return modeIcon(value) === "unlock";
if (category === "permissions") return /^(on|true)$/i.test(value);
if (category === "approval") return value.toLowerCase() === "bypass";
return false;
};
/** The settings that approve everything without asking (a bypass mode, permissions, or approvals), by option id. */
export function bypassDefaults(config: readonly AgentConfigOption[]): Record<string, string> {
const out: Record<string, string> = {};
const mode = modeOption(config);
@@ -525,6 +539,29 @@ export function bypassDefaults(config: readonly AgentConfigOption[]): Record<str
return out;
}
/** Moves approval-bearing options away from bypass when `agents.newTaskApprovals` is `"ask"`. */
export function askApprovalDefaults(config: readonly AgentConfigOption[]): Record<string, string> {
const out: Record<string, string> = {};
for (const o of config) {
if (o.category !== "mode" && o.category !== "permissions" && o.category !== "approval") continue;
if (o.current !== null && !isBypassOptionValue(o.category, o.current)) continue;
const asking = o.values.filter((v) => !isBypassOptionValue(o.category, v.value));
const agentDefault = o.defaultValue && asking.find((v) => v.value === o.defaultValue);
const picked =
agentDefault ?? asking.find((v) => v.value === "default") ?? asking.find((v) => v.value === "ask") ?? asking[0];
if (picked) out[o.id] = picked.value;
}
return out;
}
/** Effective approval overrides from `agents.newTaskApprovals` (`"bypass"` or `"ask"`), by option id. */
export function approvalDefaults(
config: readonly AgentConfigOption[],
newTaskApprovals: "bypass" | "ask" = "bypass",
): Record<string, string> {
return newTaskApprovals === "ask" ? askApprovalDefaults(config) : bypassDefaults(config);
}
/** Shift+Tab: the mode after the current one. */
export function nextValue(option: AgentConfigOption, current = option.current): string | null {
if (!option.values.length) return null;
+3 -3
Переглянути файл
@@ -533,9 +533,9 @@ it("discovers an uncached model's own settings before its first task and restore
const settings = screen.getByRole("button", { name: /^Model settings:/ });
expect(settings).toHaveTextContent("medium");
fireEvent.click(settings);
fireEvent.click(screen.getByRole("radio", { name: "max" }));
expect(screen.getByRole("radio", { name: "long_context" })).toBeVisible();
fireEvent.click(screen.getByRole("radio", { name: "long_context" }));
fireEvent.click(screen.getByRole("option", { name: "max" }));
expect(screen.getByRole("option", { name: "long_context" })).toBeVisible();
fireEvent.click(screen.getByRole("option", { name: "long_context" }));
fireEvent.click(screen.getByRole("button", { name: "Model" }));
fireEvent.click(screen.getByTitle("big"));
expect(settings).toHaveTextContent("high");
+3
Переглянути файл
@@ -7,6 +7,7 @@ import type {
AcpImportOutcome,
AgentCliOffer,
AgentCliUpdateResult,
AgentModelCatalog,
AgentProvider,
AgentRegistry,
CustomAgentInput,
@@ -31,6 +32,7 @@ export interface CommandsBackend {
updateCli(id: string, offer: AgentCliOffer, request: RequestId): Promise<AgentCliUpdateResult>;
cancel(request: RequestId): void;
providers(): Promise<AgentProvider[]>;
refreshModels?(id: string, model: string | null): Promise<AgentModelCatalog>;
set(id: string, command: string | null): Promise<void>;
setEnv(id: string, env: Record<string, string>): Promise<void>;
chooseExecutable(title: string, current?: string, location?: "desktop"): Promise<string | null>;
@@ -58,6 +60,7 @@ export const tauriCommands: CommandsBackend = {
updateCli: (id, offer, request) => call(commands.agentCliUpdate(id, offer, request)),
cancel: tauriRegistry.cancel,
providers: () => call(commands.agentProviders()),
refreshModels: (id, model) => call(commands.agentRefreshModels(id, false, model)),
chooseExecutable: async (title, current, location) => {
if (location !== "desktop") return choosePath({ title, defaultPath: current, directory: false });
const picked = await open({ title, defaultPath: current || undefined, directory: false, multiple: false });
+32 -32
Переглянути файл
@@ -36,7 +36,7 @@ import { editorService, notifications, notifyTabTitlesChanged, toolWindowService
import { tx } from "@/platform/i18n";
import { confirm, showError } from "@/workbench/messages";
import {
bypassDefaults,
approvalDefaults,
canSend,
shellCommand,
cursorModelDefaults,
@@ -261,6 +261,7 @@ export function draftConfig(
provider: AgentProvider | undefined,
draft: Draft,
defaults: Record<string, string> = providerDefaults(provider?.id),
newTaskApprovals: "bypass" | "ask" = useProject.getState().settings?.agents?.newTaskApprovals ?? "bypass",
): AgentConfigOption[] {
const catalog = provider && useAgents.getState().modelCatalogs.get(provider.id);
const offered = catalog?.config ?? provider?.config ?? [];
@@ -269,27 +270,31 @@ export function draftConfig(
priorModel && draft.config[priorModel.id] !== undefined && !offered.some((o) => o.category === "model")
? [...offered, { ...priorModel, values: [] }]
: offered;
const config = source
.filter((o) => !isPerModelOption(o))
.map((o) => {
const explicit = draft.config[o.id];
const choice = explicit ?? defaults[o.id];
return {
...o,
defaultValue: o.defaultValue ?? o.current,
current:
o.category === "model" && explicit !== undefined
? explicit
: choice !== undefined && o.values.some((v) => v.value === choice)
? choice
: o.current,
};
});
const base = source.filter((o) => !isPerModelOption(o));
const approvals = approvalDefaults(base, newTaskApprovals);
const config = base.map((o) => {
const explicit = draft.config[o.id];
const choice = explicit ?? defaults[o.id] ?? approvals[o.id];
return {
...o,
defaultValue: o.defaultValue ?? o.current,
current:
o.category === "model" && explicit !== undefined
? explicit
: choice !== undefined && o.values.some((v) => v.value === choice)
? choice
: o.current,
};
});
const model = config.find((o) => o.category === "model")?.current;
if (model) {
config.push(
...(draftModelSettings((catalog ?? provider)?.thoughtLevels?.[model], draft.thoughtLevels?.[model], defaults) ??
[]),
...(draftModelSettings(
(catalog ?? provider)?.thoughtLevels?.[model],
draft.thoughtLevels?.[model],
defaults,
provider?.id,
) ?? []),
);
}
return config;
@@ -299,9 +304,12 @@ export function draftModelSettings(
options: AgentConfigOption[] | undefined,
choices: Record<string, string> | undefined,
defaults: Record<string, string>,
providerId?: string,
) {
return options?.map((o) => {
const choice = choices?.[o.id] ?? defaults[o.id];
if (!options) return undefined;
const modelDefaults = cursorModelDefaults(providerId, options);
return options.map((o) => {
const choice = choices?.[o.id] ?? defaults[o.id] ?? modelDefaults[o.id];
return {
...o,
defaultValue: o.defaultValue ?? o.current,
@@ -1285,17 +1293,9 @@ export async function startTask(
)
)
return;
const askForApprovals = useProject.getState().settings?.agents?.newTaskApprovals === "ask";
const defaults = {
...cursorModelDefaults(draft.provider, options),
...(askForApprovals ? {} : bypassDefaults(options)),
...providerDefaults(draft.provider),
};
const config = options.flatMap((o) => {
const value =
o.category === "model" || isPerModelOption(o) ? o.current : (draft.config[o.id] ?? defaults[o.id] ?? null);
return value !== null && o.values.some((v) => v.value === value) ? [{ id: o.id, value }] : [];
});
const config = options.flatMap((o) =>
o.current !== null && o.values.some((v) => v.value === o.current) ? [{ id: o.id, value: o.current }] : [],
);
try {
const task = await call(
commands.agentCreate({
+11 -3
Переглянути файл
@@ -36,7 +36,14 @@ import {
T,
hasIcon,
} from "@/ui";
import { effectiveValues, fieldError, isVisible, versionAtLeast, type Values } from "./newProjectTemplate";
import {
effectiveValues,
fieldError,
isVisible,
projectFolder,
versionAtLeast,
type Values,
} from "./newProjectTemplate";
import { defaultProjectDirectory, openProjectInWindow } from "./windows";
import styles from "./newProject.module.css";
@@ -243,7 +250,8 @@ function NewProjectDialog({ onClose }: { onClose: () => void }) {
setEdited((all) => ({ ...all, [selected]: { ...(all[selected] ?? {}), [id]: value } }));
const syntaxError = projectNameError(name);
const path = location.trim() && !syntaxError ? joinPath(location.trim(), name) : "";
const folder = projectFolder(generator?.directory, fields, name, ownValues);
const path = location.trim() && !syntaxError ? joinPath(location.trim(), folder) : "";
const nameError =
syntaxError ?? (path && takenPath === path ? "A folder with this name already exists and is not empty" : null);
@@ -267,7 +275,7 @@ function NewProjectDialog({ onClose }: { onClose: () => void }) {
let live = true;
const dir = location.trim();
const timer = setTimeout(() => {
call(commands.scaffoldTargetTaken(dir, name.trim()))
call(commands.scaffoldTargetTaken(dir, folder))
.then((taken) => live && setTakenPath(taken ? path : null))
.catch(() => {});
}, 150);
+1
Переглянути файл
@@ -19,6 +19,7 @@ const empty: GeneratorInfo = {
description: "An empty folder to add files to.",
git: true,
fields: [],
directory: null,
dynamic: false,
};
const dotnet: GeneratorInfo = {
+13 -1
Переглянути файл
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import type { Field } from "@/platform/ipc";
import { effectiveValues, fieldError, isVisible, render } from "../newProjectTemplate";
import { effectiveValues, fieldError, isVisible, projectFolder, render } from "../newProjectTemplate";
const text = (id: string, defaultValue: string, pattern: string | null = null): Field => ({
id,
@@ -46,4 +46,16 @@ describe("new project field templates", () => {
expect(fieldError(g, "com.example")).toBeNull();
expect(fieldError(g, "com..example")).not.toBeNull();
});
it("names the project folder after a .NET solution only while one is created", () => {
const solution: Field = { ...text("solution", "true"), kind: { type: "checkbox" } };
const fields = [solution, { ...text("solution-name", "{{name}}"), visible: { solution: ["true"] } }];
const folder = (edited: Record<string, string>) => projectFolder("{{solution-name}}", fields, "Shop", edited);
expect(folder({})).toBe("Shop");
expect(folder({ "solution-name": "Store" })).toBe("Store");
// Unchecked, the hidden name isn't sent and the folder is the project's.
expect(folder({ "solution-name": "Store", solution: "false" })).toBe("Shop");
expect(folder({ "solution-name": " " })).toBe("Shop");
expect(projectFolder(null, fields, " Shop ", { "solution-name": "Store" })).toBe("Shop");
});
});
+22
Переглянути файл
@@ -76,6 +76,28 @@ export function isVisible(field: Field, values: Values): boolean {
return Object.entries(field.visible).every(([id, allowed]) => allowed.includes(values[id] ?? ""));
}
/**
* The project folder's name: the generator's `directory` template (a .NET solution's name) over
* the values the form sends — a hidden field falls back to its default, as `ide-scaffold` does —
* or the project name.
*/
export function projectFolder(
directory: string | null | undefined,
fields: readonly Field[],
name: string,
edited: Values,
): string {
if (!directory) return name.trim();
const shown = effectiveValues(fields, name, edited);
const sent = Object.fromEntries(
Object.entries(edited).filter(([id]) => {
const field = fields.find((f) => f.id === id);
return !field || isVisible(field, shown);
}),
);
return render(directory, effectiveValues(fields, name, sent)).trim() || name.trim();
}
/** `a` ≥ `b`, comparing the numeric parts of dotted versions (`ide-scaffold`'s `version_at_least`). */
export function versionAtLeast(a: string, b: string): boolean {
const parts = (s: string) => {
+20
Переглянути файл
@@ -385,6 +385,26 @@ describe("store", () => {
expect(usePlugins.getState().activeTheme).toBeNull();
});
it("keeps a theme applied by an event over an older plugin list that predates it", async () => {
await refreshPlugins();
const applied = await backend.setTheme("theme-harbor-night", "harbor-night");
await backend.setTheme(null, null);
// The list is read before the theme lands and answers after its event.
let release!: () => void;
const gate = new Promise<void>((r) => (release = r));
const stale = await backend.list();
setPluginsBackend({ ...backend, list: () => gate.then(() => stale) });
const refresh = refreshPlugins();
handlePluginEvent({ type: "themeChanged", theme: applied });
release();
await refresh;
expect(usePlugins.getState().activeTheme?.theme.id).toBe("harbor-night");
// A list requested after the event is taken as it is.
setPluginsBackend(backend);
await refreshPlugins();
expect(usePlugins.getState().activeTheme).toBeNull();
});
it("applies the plugin theme the Appearance setting selects, and clears it for a built-in one", async () => {
const stop = [syncProjection(), followThemeSetting()];
try {
+9 -2
Переглянути файл
@@ -18,7 +18,14 @@ import { pluginsBackend } from "./backend";
import { trackIconTheme } from "./iconThemes";
import { defineBuiltinUiPoints } from "./points";
import { handleRuntimeEvent, refreshEventKinds, startRuntimeUi } from "./runtimeUi";
import { grantPlugin, runPluginCommand, refreshPlugins, updateAllPlugins, usePlugins } from "./store";
import {
grantPlugin,
runPluginCommand,
refreshPlugins,
setActivePluginTheme,
updateAllPlugins,
usePlugins,
} from "./store";
import { followThemeSetting, syncPluginProjection, trackPluginTheme } from "./themeRuntime";
export { pluginActionId } from "./points";
@@ -94,7 +101,7 @@ export function handlePluginEvent(e: PluginEvent) {
break;
}
case "themeChanged":
usePlugins.setState({ activeTheme: e.theme });
setActivePluginTheme(e.theme);
break;
case "consentRequested":
void refreshPlugins().then(() => grantPlugin(e.pluginId, e.capabilities));
+2 -2
Переглянути файл
@@ -15,7 +15,7 @@ import { useIntellijThemesDialog } from "./intellijThemesDialogStore";
import { defineUiPoint } from "./projection";
import { refreshRunTargets, startRunTargets } from "./runTargets";
import { projectSettings, type SettingsDecl } from "./settings";
import { refreshPlugins, SETTINGS_PAGE_ID, usePlugins } from "./store";
import { refreshPlugins, setActivePluginTheme, SETTINGS_PAGE_ID } from "./store";
import { syncPluginProjection, trackPluginTheme } from "./themeRuntime";
export function registerPluginsPage(): () => void {
@@ -92,7 +92,7 @@ function followSettingsPluginChanges(): () => void {
}
break;
case "themeChanged":
usePlugins.setState({ activeTheme: e.theme });
setActivePluginTheme(e.theme);
break;
case "languagesChanged":
languageListChanged();
+16 -5
Переглянути файл
@@ -102,21 +102,33 @@ function askConsent(req: ConsentRequest): Promise<Consent | null> {
// --- loading ------------------------------------------------------------------
let generation = 0;
/** Bumped whenever the active theme arrives on its own (a theme event, a theme choice). */
let themeStamp = 0;
/**
* Sets the active plugin theme from a `themeChanged` event or a theme choice. A plugin list
* requested before it carries the older theme, so its snapshot no longer overrides this one.
*/
export function setActivePluginTheme(activeTheme: ActiveTheme | null) {
themeStamp++;
usePlugins.setState({ activeTheme });
}
export async function refreshPlugins(): Promise<void> {
const gen = ++generation;
const stamp = themeStamp;
usePlugins.setState({ loading: true });
try {
const snapshot = await pluginsBackend().list();
if (gen !== generation) return;
usePlugins.setState({
usePlugins.setState((s) => ({
plugins: snapshot.plugins,
ui: snapshot.ui,
activeTheme: snapshot.activeTheme,
activeTheme: stamp === themeStamp ? snapshot.activeTheme : s.activeTheme,
loaded: true,
loading: false,
error: null,
});
}));
} catch (e) {
if (gen !== generation) return;
usePlugins.setState({ loading: false, loaded: true, error: errorText(e) });
@@ -383,8 +395,7 @@ export async function installFromDisk(
export async function selectPluginTheme(pluginId: string | null, themeId: string | null): Promise<void> {
try {
const activeTheme = await pluginsBackend().setTheme(pluginId, themeId);
usePlugins.setState({ activeTheme });
setActivePluginTheme(await pluginsBackend().setTheme(pluginId, themeId));
} catch (e) {
notifications().notify({ group: "plugins", level: "error", title: "Could not apply theme", body: errorText(e) });
}
+6 -1
Переглянути файл
@@ -47,6 +47,9 @@
gap: var(--space-1);
min-width: 0;
overflow: hidden;
/* Room for the error wavy underline below the line box without changing row layout height. */
padding-block: var(--space-1);
margin-block: calc(-1 * var(--space-1));
}
.labelGroup .label {
flex: none;
@@ -67,7 +70,9 @@
text-decoration-line: line-through;
}
.error {
padding-block: var(--space-0-5);
/* Room for the wave below the line box, which the ellipsis' overflow would clip. */
padding-block: var(--space-1);
margin-block: calc(-1 * var(--space-1));
text-decoration-line: underline;
text-decoration-style: wavy;
text-decoration-color: var(--danger);