Compare commits

..
Author SHA1 Message Date
l0ng-ai 4ec91e91c8 Merge remote-tracking branch 'origin/main' into feat/agent-changes-tab
# Conflicts:
#	src/features/agents/session/SessionStatus.tsx
#	src/platform/locales/text/en.json
#	src/platform/locales/text/es.json
#	src/platform/locales/text/fr.json
#	src/platform/locales/text/ko.json
#	src/platform/locales/text/pl.json
#	src/platform/locales/text/pt.json
#	src/platform/locales/text/tr.json
#	src/platform/locales/text/zh-TW.json
#	src/platform/locales/text/zh.json
2026-11-25 14:15:12 +08:00
l0ng-ai 493bde17a9 feat(agents): open a task's changes in an editor tab
The changed-files chip under the composer opens the task's changes in an
editor tab of their own: the file tree beside one scrolling diff of every
file, with the scope, accept and rollback controls in the diff's toolbar.
The conversation keeps its layout instead of gaining a side pane.

Added and deleted files show their one side alone, and selecting a file
no longer renders every mounted diff again.
2026-11-25 08:50:53 +08:00
206 changed files with 663 additions and 6771 deletions

No files matched your search

+1 -11
View File
@@ -158,17 +158,7 @@
"src/features/run/**/*.ts",
"src/features/run/**/*.tsx",
"src/features/database/**/*.ts",
"src/features/database/**/*.tsx",
"src/features/analysis/**/*.ts",
"src/features/analysis/**/*.tsx",
"src/features/project-tree/**/*.ts",
"src/features/project-tree/**/*.tsx",
"src/features/http-client/**/*.ts",
"src/features/http-client/**/*.tsx",
"src/platform/**/*.ts",
"src/platform/**/*.tsx",
"src/features/debugger/**/*.ts",
"src/features/debugger/**/*.tsx"
"src/features/database/**/*.tsx"
],
"rules": {
"no-await-in-loop": "error"
+2 -2
View File
@@ -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) || config::is_fast_option(&o.id) {
if config::is_context_option(&o.id) {
if o.category.is_none() {
o.category = Some("model_config".into());
}
} else if o.category.is_none() {
} else if o.category.as_deref() != Some("thought_level") {
o.category = Some("thought_level".into());
}
o
+3 -4
View File
@@ -168,12 +168,11 @@ 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();
// 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");
let fast = cursor.config.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")));
}
+6 -24
View File
@@ -15,8 +15,6 @@ 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);
@@ -82,8 +80,6 @@ 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,
}
@@ -115,7 +111,7 @@ impl LaunchContext {
hash.update(&(value.len() as u64).to_le_bytes());
hash.update(value);
}
field(&mut hash, b"openidea-model-catalog-v2");
field(&mut hash, b"openidea-model-catalog-v1");
field(
&mut hash,
match self.spec.driver {
@@ -204,14 +200,7 @@ impl AgentCatalogs {
cache
.get(provider)
.and_then(|known| known.catalogs.get(&shared.root_key()))
.map(|saved| {
let mut catalog = saved.catalog.clone();
if saved.schema < CATALOG_SCHEMA {
catalog.refreshed_at_ms = None;
catalog.thought_levels.clear();
}
catalog
})
.map(|saved| saved.catalog.clone())
.unwrap_or_default()
}
@@ -239,8 +228,7 @@ impl AgentCatalogs {
}
drop(state);
let cache = shared.known.lock();
let saved = cache.get(provider)?.catalogs.get(&shared.root_key())?;
(saved.schema >= CATALOG_SCHEMA).then(|| saved.catalog.thought_levels.get(model).cloned()).flatten()
cache.get(provider)?.catalogs.get(&shared.root_key())?.catalog.thought_levels.get(model).cloned()
}
pub(super) async fn load_levels(
@@ -293,7 +281,7 @@ impl AgentCatalogs {
AgentModelCatalog {
provider: provider.to_owned(),
config: shared.config_for_new_task(catalog.config, provider),
thought_levels: shared.thought_levels_for_new_task(catalog.thought_levels, provider),
thought_levels: catalog.thought_levels,
refreshing: entry.flight.is_some(),
refreshed_at_ms: catalog.refreshed_at_ms,
retry_at_ms: model_failure
@@ -330,9 +318,7 @@ 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.schema >= CATALOG_SCHEMA && saved.fingerprint == context.fingerprint());
let matching = saved.as_ref().is_some_and(|saved| saved.fingerprint == context.fingerprint());
let age = saved
.as_ref()
.filter(|_| matching)
@@ -503,11 +489,7 @@ impl AgentCatalogs {
}
known.catalogs.insert(
shared.root_key(),
SavedCatalog {
fingerprint: entry.context.fingerprint(),
schema: CATALOG_SCHEMA,
catalog: catalog.clone(),
},
SavedCatalog { fingerprint: entry.context.fingerprint(), catalog: catalog.clone() },
);
entry.catalog = Some(catalog);
shared.persist_known(&cache);
+27 -99
View File
@@ -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
/// own default (when it asks), else `default` or `ask`, else its first one that asks.
/// default or ask mode, 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,15 +73,9 @@ pub(crate) fn ask_for_approvals(config: &mut [AgentConfigOption]) {
continue;
}
let asks = |v: &&AgentConfigValue| !bypass(&v.value);
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))
})
let value = ["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());
@@ -89,26 +83,11 @@ pub(crate) fn ask_for_approvals(config: &mut [AgentConfigOption]) {
}
}
/// 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());
}
/// 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))
}
fn is_bypass_mode(mode: &str) -> bool {
@@ -147,20 +126,14 @@ pub(crate) fn options_of(result: &Value) -> Vec<AgentConfigOption> {
}
pub(crate) fn is_context_option(id: &str) -> bool {
matches!(id, "context" | "context_tier" | "contextTier")
}
pub(crate) fn is_fast_option(id: &str) -> bool {
id == "fast"
matches!(id, "context_tier" | "contextTier")
}
/// Whether an option's available values and default belong to the selected model
/// (`thought_level`, `context_tier`, and `model_config` options like `context` and `fast`)
/// rather than the provider as a whole.
/// (`thought_level` and model context-tier options) 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" | "model_config"))
matches!(o.category.as_deref(), Some("thought_level" | "context_tier"))
|| matches!(o.id.as_str(), "effort" | "reasoning_effort" | "thinking" | "reasoning")
|| is_fast_option(&o.id)
|| is_context_option(&o.id)
}
@@ -191,7 +164,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(|| (is_fast_option(&id) || is_context_option(&id)).then(|| "model_config".into()))
.or_else(|| (id == "fast" || is_context_option(&id)).then(|| "model_config".into()))
}),
current,
default_value,
@@ -364,11 +337,6 @@ 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");
@@ -384,7 +352,7 @@ fn value_of(v: &Value) -> Option<AgentConfigValue> {
.filter(|s| !s.is_empty())
.map(str::to_owned);
Some(AgentConfigValue {
name: str_of(v, "name").map(|n| clean_label(n, &value)).unwrap_or_else(|| value.clone()),
name: str_of(v, "name").unwrap_or_else(|| value.clone()),
description: str_of(v, "description"),
cost_category,
usage_multiplier,
@@ -466,16 +434,19 @@ mod tests {
]}
}));
assert!(bypass_approvals(&full_access));
assert_eq!(bypass_mode(&full_access).map(|(_, v)| v.value.as_str()), Some("full-access"));
let mut asking = options_of(&json!({
let asking = options_of(&json!({
"modes": {"currentModeId": "ask", "availableModes": [
{"id": "ask", "name": "Ask"}, {"id": "full-access", "name": "Full Access"}
]}
}));
assert!(!bypass_approvals(&asking));
apply_bypass_approvals(&mut asking);
assert_eq!(asking[0].current.as_deref(), Some("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"
);
let permissions = |current: &str| {
options_of(&json!({"configOptions": [{
@@ -532,7 +503,7 @@ mod tests {
}
#[test]
fn effort_context_and_fast_are_per_model_options() {
fn effort_and_fast_categories_are_inferred_from_ids() {
let mut c = options_of(&json!({
"configOptions": [
{"id": "model", "type": "select", "currentValue": "gemini-4-carbon",
@@ -541,39 +512,19 @@ 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": "true",
"options": [{"value": "false", "name": "Off"}, {"value": "true", "name": "Fast\u{200b}\u{200b}"}]}
{"id": "fast", "type": "select", "currentValue": "false",
"options": [{"value": "false", "name": "Off"}, {"value": "true", "name": "On"}]}
]
}));
assert_eq!(c.len(), 5);
assert_eq!(c.len(), 4);
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_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"));
assert!(is_per_model_option(&c[1]) && is_per_model_option(&c[2]) && !is_per_model_option(&c[3]));
// Editing effort on the same model preserves its initial `default_value` for Reset.
merge_update(
@@ -595,34 +546,11 @@ 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"}]},
{"id": "context", "type": "select", "currentValue": "1m",
"options": [{"value": "300k", "name": "300K"}, {"value": "1m", "name": "1M"}]}
"options": [{"value": "low"}, {"value": "medium"}, {"value": "high"}]}
]),
);
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]
+12 -27
View File
@@ -331,23 +331,19 @@ 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);
} else {
config::apply_bypass_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());
}
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();
@@ -379,19 +375,8 @@ 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()
.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();
let levels: Vec<_> = config.iter().filter(|o| config::is_per_model_option(o)).cloned().collect();
if !levels.is_empty() {
self.paths.catalogs.learn_levels(self, provider, model, levels);
}
@@ -751,7 +736,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 = self.shared.thought_levels_for_new_task(catalog.thought_levels, &p.id);
info.thought_levels = catalog.thought_levels;
info.commands = self.shared.known_commands(&p.id);
info
})
@@ -1074,7 +1059,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 = self.shared.thought_levels_for_new_task(catalog.thought_levels, &spec.id);
let mut levels = catalog.thought_levels;
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) {
+8 -4
View File
@@ -3942,10 +3942,14 @@ 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!(!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")));
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")) })
);
}
#[tokio::test(flavor = "multi_thread")]
+10 -30
View File
@@ -965,7 +965,6 @@ pub struct LaunchBuild {
/// Compiles the module at `module` with its build system before a JVM launch and
/// returns the class directories it wrote, to put ahead of the jdtls classpath.
/// The build's console, messages and progress stream to `on_event` as it runs.
pub fn build_for_launch(
root: &Path,
model: &BuildModel,
@@ -973,9 +972,8 @@ pub fn build_for_launch(
test: bool,
kind: BuildKind,
cancel: &CancellationToken,
on_event: &(dyn Fn(BuildEvent) + Sync),
) -> IdeResult<LaunchBuild> {
let mut built = build_for_launches(root, model, &[module.to_path_buf()], test, kind, cancel, on_event)?;
let mut built = build_for_launches(root, model, &[module.to_path_buf()], test, kind, cancel)?;
Ok(built.pop().unwrap())
}
@@ -988,10 +986,9 @@ pub fn build_for_launches(
test: bool,
kind: BuildKind,
cancel: &CancellationToken,
on_event: &(dyn Fn(BuildEvent) + Sync),
) -> IdeResult<Vec<LaunchBuild>> {
let plan = merged_launch_plan(root, model, modules, test, kind, cancel)?;
let result = run(root, &plan, cancel, on_event)?;
let result = run(root, &plan, cancel, &|_| {})?;
let failure = if !result.success {
let errors: Vec<String> = result
.messages
@@ -1825,16 +1822,8 @@ mod tests {
std::fs::set_permissions(&wrapper, std::fs::Permissions::from_mode(0o755)).unwrap();
let mut model = reactor_model();
model.maven.as_mut().unwrap().projects[0].command = wrapper.to_string_lossy().into_owned();
let dirs = build_for_launch(
root,
&model,
&root.join("app"),
true,
BuildKind::Build,
&CancellationToken::new(),
&|_| {},
)
.unwrap();
let dirs = build_for_launch(root, &model, &root.join("app"), true, BuildKind::Build, &CancellationToken::new())
.unwrap();
assert_eq!(
dirs.class_dirs,
["app/target/test-classes", "app/target/classes", "middle/target/classes", "lib/target/classes"]
@@ -1845,25 +1834,16 @@ mod tests {
"mvnw",
"#!/bin/sh\necho '[ERROR] Kotlin compilation failed: unresolved reference broken' >&2\nexit 1\n",
);
let error = build_for_launch(
root,
&model,
&root.join("app"),
false,
BuildKind::Build,
&CancellationToken::new(),
&|_| {},
)
.unwrap()
.failure
.unwrap();
let error =
build_for_launch(root, &model, &root.join("app"), false, BuildKind::Build, &CancellationToken::new())
.unwrap()
.failure
.unwrap();
assert!(error.contains("Kotlin compilation failed"), "{error}");
let cancel = CancellationToken::new();
cancel.cancel();
assert_eq!(
build_for_launch(root, &model, &root.join("app"), false, BuildKind::Build, &cancel, &|_| {})
.unwrap_err()
.kind,
build_for_launch(root, &model, &root.join("app"), false, BuildKind::Build, &cancel).unwrap_err().kind,
ide_core::error::ErrorKind::Cancelled
);
}
-2
View File
@@ -201,7 +201,6 @@ pub struct FoldingSettings {
pub file_header: bool,
pub imports: bool,
pub doc_comments: bool,
pub go_short_blocks: bool,
}
impl Default for FoldingSettings {
@@ -212,7 +211,6 @@ impl Default for FoldingSettings {
file_header: true,
imports: true,
doc_comments: false,
go_short_blocks: true,
}
}
}
+1 -3
View File
@@ -145,7 +145,7 @@ impl Default for AgentSettings {
show_work_time: true,
show_usage_limits: true,
show_cost: false,
fold_turns: false,
fold_turns: true,
smooth_text: true,
fit_window_width: false,
thinking: ThinkingDisplay::Auto,
@@ -2113,10 +2113,8 @@ mod tests {
assert!(old.agents.show_cost);
assert!(old.agents.show_context_usage && old.agents.show_work_time && old.agents.show_usage_limits);
assert!(!old.agents.fit_window_width);
assert!(!old.agents.fold_turns);
assert!(!Settings::default().agents.show_cost);
assert!(!Settings::default().agents.fit_window_width);
assert!(!Settings::default().agents.fold_turns);
let mut settings = Settings::default();
settings.agents.show_usage_limits = false;
settings.agents.fit_window_width = true;
+1 -1
View File
@@ -30,7 +30,7 @@ pub(crate) use inspect::{fields, instances, referrers, set_inspector, vm_target,
pub(crate) use scan::watch_for_attached_jvm;
pub(crate) use scan::{JvmFinder, attach_target, find_attached_jvm, find_local_jvm, local_jdwp_port};
use snapshot::{AttachProbe, JdkProbe, take_snapshot};
pub use threads::{JvmThreadDump, JvmThreadsResult, JvmThreadsUnavailable, VirtualThreadsNote, run_jvm_thread_dump};
pub use threads::{JvmThreadDump, JvmThreadsResult, JvmThreadsUnavailable, run_jvm_thread_dump};
pub(crate) use threads::{debugged_run_thread_dump, session_thread_dump};
pub const JVM_MEMORY_ADAPTERS: &[&str] = &["java-debug", crate::kotlin::ADAPTER, crate::kotlin_lsp::ADAPTER];
@@ -33,7 +33,6 @@ pub(crate) trait AttachProbe: Send + Sync {
fn ensure_listener(&self, pid: u32) -> Result<(), AttachError>;
/// Confirmed HotSpot and not one of Gradle's own JVMs; asks the JVM nothing.
fn is_application_jvm(&self, pid: u32) -> bool;
fn thread_dump_json(&self, pid: u32, dir: &Path) -> Result<String, AttachError>;
}
pub(super) struct JdkProbe {
@@ -92,10 +91,6 @@ impl AttachProbe for JdkProbe {
fn is_application_jvm(&self, pid: u32) -> bool {
ide_jvm_attach::is_application_jvm(pid)
}
fn thread_dump_json(&self, pid: u32, dir: &Path) -> Result<String, AttachError> {
ide_jvm_attach::thread_dump_json(pid, dir, ide_jvm_attach::THREAD_DUMP_TIMEOUT)
}
}
fn alive(pid: u32) -> bool {
+29 -189
View File
@@ -47,8 +47,6 @@ struct FakeProbe {
application_jvms: Vec<u32>,
/// Pids `ensure_listener` was asked for.
ensured: parking_lot::Mutex<Vec<u32>>,
json_dumps: parking_lot::Mutex<VecDeque<Result<String, AttachError>>>,
json_dirs: parking_lot::Mutex<Vec<PathBuf>>,
}
type StopHook = Box<dyn Fn() + Send + Sync>;
@@ -111,8 +109,6 @@ impl FakeProbe {
listener_starts: parking_lot::Mutex::new(VecDeque::new()),
application_jvms: Vec::new(),
ensured: parking_lot::Mutex::new(Vec::new()),
json_dumps: parking_lot::Mutex::new(VecDeque::new()),
json_dirs: parking_lot::Mutex::new(Vec::new()),
}
}
@@ -197,12 +193,6 @@ impl AttachProbe for FakeProbe {
fn is_application_jvm(&self, pid: u32) -> bool {
self.application_jvms.contains(&pid)
}
fn thread_dump_json(&self, _pid: u32, dir: &Path) -> Result<String, AttachError> {
self.enter("thread_dump_json");
self.json_dirs.lock().push(dir.to_owned());
self.leave();
self.json_dumps.lock().pop_front().expect("unexpected JSON thread dump request")
}
}
const FLAGS: &str = "-XX:+UseCompressedOops -XX:+StartAttachListener";
@@ -1215,95 +1205,10 @@ fn threads_jvm(reason: JvmMemoryUnavailable) -> JvmThreadsUnavailable {
JvmThreadsUnavailable::Jvm { reason }
}
/// The text dump alone: without a directory no JSON dump is asked for.
fn dump_text(fake: &FakeProbe, pid: u32, suspended: bool) -> JvmThreadsResult {
dump_threads(fake, pid, suspended, None, &|| suspended)
}
fn ready_dump(r: JvmThreadsResult) -> JvmThreadDump {
match r {
JvmThreadsResult::Ready { dump } => dump,
other => panic!("{other:?}"),
}
}
const VIRTUAL_JSON: &str = r#"{"threadDump":{"threadContainers":[]}}"#;
fn json_dir() -> &'static Path {
Path::new("/data/cache/heap-snapshots/x")
}
#[test]
fn threads_below_21_ask_for_no_json() {
let mut fake = dumping_threads(99, vec![Ok(THREADS.into())]);
fake.version = Some(JavaVersion { major: 17, text: "17.0.13".into() });
let dump = ready_dump(dump_threads(&fake, 12, false, Some(json_dir()), &|| false));
assert_eq!((dump.virtual_json, dump.virtual_note), (None, None));
assert_eq!(*fake.commands.lock(), ["ensure_listener", "thread_print"]);
}
#[test]
fn threads_on_21_add_the_json_after_the_text() {
let fake = dumping_threads(99, vec![Ok(THREADS.into())]);
*fake.json_dumps.lock() = vec![Ok(VIRTUAL_JSON.into())].into();
let dump = ready_dump(dump_threads(&fake, 12, false, Some(json_dir()), &|| false));
assert_eq!(dump.text, THREADS);
assert_eq!((dump.virtual_json.as_deref(), dump.virtual_note), (Some(VIRTUAL_JSON), None));
assert_eq!(*fake.commands.lock(), ["ensure_listener", "thread_print", "thread_dump_json"]);
assert_eq!(*fake.json_dirs.lock(), [json_dir()]);
}
#[test]
fn a_failed_json_dump_keeps_the_text_dump() {
let cases = [
(AttachError::TooLarge, VirtualThreadsNote::TooLarge),
(AttachError::Timeout, VirtualThreadsNote::Failed),
(AttachError::Protocol("no thread dump file".into()), VirtualThreadsNote::Failed),
];
for (error, note) in cases {
let fake = dumping_threads(99, vec![Ok(THREADS.into())]);
*fake.json_dumps.lock() = vec![Err(error)].into();
let dump = ready_dump(dump_threads(&fake, 12, false, Some(json_dir()), &|| false));
assert_eq!((dump.text.as_str(), dump.virtual_json, dump.virtual_note), (THREADS, None, Some(note)));
}
// No directory to write the file into.
let fake = dumping_threads(99, vec![Ok(THREADS.into())]);
let dump = ready_dump(dump_text(&fake, 12, false));
assert_eq!((dump.virtual_json, dump.virtual_note), (None, Some(VirtualThreadsNote::Failed)));
assert_eq!(*fake.commands.lock(), ["ensure_listener", "thread_print"]);
}
#[test]
fn a_failed_text_dump_asks_for_no_json() {
let fake = dumping_threads(99, vec![Err(AttachError::Timeout)]);
let r = dump_threads(&fake, 12, false, Some(json_dir()), &|| false);
assert_eq!(threads_unavailable(r), threads_jvm(JvmMemoryUnavailable::TimedOut));
assert_eq!(*fake.commands.lock(), ["ensure_listener", "thread_print"]);
}
#[test]
fn threads_while_suspended_on_21_skip_the_json() {
let fake = dumping_threads(12, vec![Ok(THREADS.into())]);
let dump = ready_dump(dump_threads(&fake, 12, true, Some(json_dir()), &|| true));
assert_eq!((dump.virtual_json, dump.virtual_note), (None, Some(VirtualThreadsNote::WhileSuspended)));
assert_eq!(*fake.commands.lock(), ["thread_print"]);
// The program hits a breakpoint while the text dump is taken.
let stopped = Arc::new(AtomicBool::new(false));
let mut fake = dumping_threads(99, vec![Ok(THREADS.into())]);
let stop = stopped.clone();
fake.stops_on = Some(("thread_print", Box::new(move || stop.store(true, Ordering::SeqCst))));
let dump = ready_dump(dump_threads(&fake, 12, false, Some(json_dir()), &|| stopped.load(Ordering::SeqCst)));
assert!(!dump.taken_while_suspended);
assert_eq!((dump.virtual_json, dump.virtual_note), (None, Some(VirtualThreadsNote::WhileSuspended)));
assert_eq!(*fake.commands.lock(), ["ensure_listener", "thread_print"]);
}
#[test]
fn threads_while_running_start_the_listener() {
let fake = dumping_threads(99, vec![Ok(THREADS.into())]);
let r = dump_text(&fake, 12, false);
let r = dump_threads(&fake, 12, false);
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
assert_eq!((dump.text.as_str(), dump.pid, dump.java_version.as_str()), (THREADS, 12, "21.0.5"));
assert!(!dump.taken_while_suspended);
@@ -1313,7 +1218,10 @@ fn threads_while_running_start_the_listener() {
#[test]
fn threads_while_suspended_without_listener_do_not_attach() {
let fake = dumping_threads(99, Vec::new());
assert_eq!(threads_unavailable(dump_text(&fake, 12, true)), threads_jvm(JvmMemoryUnavailable::ListenerNotRunning));
assert_eq!(
threads_unavailable(dump_threads(&fake, 12, true)),
threads_jvm(JvmMemoryUnavailable::ListenerNotRunning)
);
assert!(fake.commands.lock().is_empty());
}
@@ -1322,12 +1230,12 @@ fn threads_while_suspended_on_11_are_refused() {
let mut fake = dumping_threads(12, Vec::new());
fake.version = Some(JavaVersion { major: 11, text: "11.0.25".into() });
assert_eq!(
threads_unavailable(dump_text(&fake, 12, true)),
threads_unavailable(dump_threads(&fake, 12, true)),
threads_jvm(JvmMemoryUnavailable::UnsafeWhileSuspended { java_major: 11 })
);
fake.version = None;
assert_eq!(
threads_unavailable(dump_text(&fake, 12, true)),
threads_unavailable(dump_threads(&fake, 12, true)),
threads_jvm(JvmMemoryUnavailable::UnsafeWhileSuspended { java_major: 0 })
);
assert!(fake.commands.lock().is_empty());
@@ -1337,7 +1245,7 @@ fn threads_while_suspended_on_11_are_refused() {
fn threads_while_suspended_on_17_use_the_running_listener() {
let mut fake = dumping_threads(12, vec![Ok(THREADS.into())]);
fake.version = Some(JavaVersion { major: 17, text: "17.0.13".into() });
let r = dump_text(&fake, 12, true);
let r = dump_threads(&fake, 12, true);
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
assert!(dump.taken_while_suspended);
assert_eq!(dump.java_version, "17.0.13");
@@ -1349,7 +1257,7 @@ fn threads_of_a_tree_without_a_listener_go_to_its_first_application_jvm() {
// A shell (10) started a Gradle client (11) that started the program's JVM (12).
let mut fake = dumping_threads(99, vec![Ok(THREADS.into())]);
fake.application_jvms = vec![12];
let r = dump_tree(&fake, &[10, 11, 12], false, None, &|| false);
let r = dump_tree(&fake, &[10, 11, 12], false);
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
assert_eq!(dump.pid, 12);
assert_eq!(*fake.ensured.lock(), [12]);
@@ -1358,7 +1266,7 @@ fn threads_of_a_tree_without_a_listener_go_to_its_first_application_jvm() {
let fake = dumping_threads(99, Vec::new());
*fake.listener_starts.lock() = vec![Err(AttachError::NotAJvm)].into();
assert_eq!(
threads_unavailable(dump_tree(&fake, &[10, 11], false, None, &|| false)),
threads_unavailable(dump_tree(&fake, &[10, 11], false)),
threads_jvm(JvmMemoryUnavailable::NoJvmProcess)
);
assert_eq!(*fake.ensured.lock(), [10]);
@@ -1382,7 +1290,7 @@ async fn launched_thread_dump_without_a_listener_finds_the_jvm_below_the_reporte
let fake = Arc::new(fake);
let probe: Arc<dyn AttachProbe> = fake.clone();
let target = JvmTarget::Launched(std::process::id() as i32);
let r = thread_dump(&state, || false, |_| probe, target, None).await.unwrap();
let r = thread_dump(&state, || false, |_| probe, target).await.unwrap();
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
assert_eq!(dump.pid, jvm);
assert_eq!(*fake.ensured.lock(), [jvm]);
@@ -1432,7 +1340,7 @@ async fn run_dump_through_a_linked_session_whose_jvm_is_not_located() {
let bare = stopped_attach(0);
let fake = Arc::new(dumping_threads(99, Vec::new()));
let probe: Arc<dyn AttachProbe> = fake.clone();
let r = known_pid_dump(&bare.session, |_| probe, 555, None).await.unwrap();
let r = known_pid_dump(&bare.session, |_| probe, 555).await.unwrap();
assert_eq!(threads_unavailable(r), threads_jvm(JvmMemoryUnavailable::ListenerNotRunning));
assert!(fake.commands.lock().is_empty());
@@ -1440,7 +1348,7 @@ async fn run_dump_through_a_linked_session_whose_jvm_is_not_located() {
let bare = bare_session("attach");
let fake = Arc::new(dumping_threads(99, vec![Ok(THREADS.into())]));
let probe: Arc<dyn AttachProbe> = fake.clone();
let r = known_pid_dump(&bare.session, |_| probe, 555, None).await.unwrap();
let r = known_pid_dump(&bare.session, |_| probe, 555).await.unwrap();
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
assert_eq!((dump.pid, dump.taken_while_suspended), (555, false));
assert_eq!(*fake.ensured.lock(), [555]);
@@ -1461,71 +1369,26 @@ async fn run_dump_of_a_suspended_debugged_jvm_takes_the_suspended_path() {
fake.version = Some(JavaVersion { major: 11, text: "11.0.25".into() });
let fake = Arc::new(fake);
let probe: Arc<dyn AttachProbe> = fake.clone();
let r = known_pid_dump(&bare.session, |_| probe, 4242, None).await.unwrap();
let r = known_pid_dump(&bare.session, |_| probe, 4242).await.unwrap();
assert_eq!(threads_unavailable(r), threads_jvm(JvmMemoryUnavailable::UnsafeWhileSuspended { java_major: 11 }));
assert!(fake.commands.lock().is_empty());
// No listener: none is started, the JVM's Signal Dispatcher being stopped.
let fake = Arc::new(dumping_threads(99, Vec::new()));
let probe: Arc<dyn AttachProbe> = fake.clone();
let r = known_pid_dump(&bare.session, |_| probe, 4242, None).await.unwrap();
let r = known_pid_dump(&bare.session, |_| probe, 4242).await.unwrap();
assert_eq!(threads_unavailable(r), threads_jvm(JvmMemoryUnavailable::ListenerNotRunning));
assert!(fake.commands.lock().is_empty());
let mut fake = dumping_threads(4242, vec![Ok(THREADS.into())]);
fake.version = Some(JavaVersion { major: 17, text: "17.0.13".into() });
let probe: Arc<dyn AttachProbe> = Arc::new(fake);
let r = known_pid_dump(&bare.session, |_| probe, 4242, None).await.unwrap();
let r = known_pid_dump(&bare.session, |_| probe, 4242).await.unwrap();
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
assert!(dump.taken_while_suspended);
assert_eq!(dump.pid, 4242);
}
#[tokio::test]
async fn run_dump_of_a_debugged_jvm_asks_for_no_json_while_the_session_holds_it() {
let bare = stopped_attach(4242);
let fake = Arc::new(dumping_threads(4242, vec![Ok(THREADS.into())]));
let probe: Arc<dyn AttachProbe> = fake.clone();
let dump = ready_dump(known_pid_dump(&bare.session, |_| probe, 4242, Some(json_dir().into())).await.unwrap());
assert!(dump.taken_while_suspended);
assert_eq!((dump.virtual_json, dump.virtual_note), (None, Some(VirtualThreadsNote::WhileSuspended)));
assert_eq!(*fake.commands.lock(), ["thread_print"]);
// Running at first, the program hits a breakpoint while the text dump is taken.
let bare = bare_session("attach");
bare.session.jvm_pid.store(4242, Ordering::Release);
let mut fake = dumping_threads(4242, vec![Ok(THREADS.into())]);
let session = bare.session.clone();
fake.stops_on = Some(("thread_print", Box::new(move || session.suspended.stopped(None, true))));
let fake = Arc::new(fake);
let probe: Arc<dyn AttachProbe> = fake.clone();
let dump = ready_dump(known_pid_dump(&bare.session, |_| probe, 4242, Some(json_dir().into())).await.unwrap());
assert!(!dump.taken_while_suspended);
assert_eq!((dump.virtual_json, dump.virtual_note), (None, Some(VirtualThreadsNote::WhileSuspended)));
assert_eq!(*fake.commands.lock(), ["ensure_listener", "thread_print"]);
}
#[tokio::test]
async fn run_dump_through_a_linked_session_whose_jvm_is_not_located_asks_for_no_json_while_stopped() {
// Gradle bootRun Debug after an earlier run dump opened the listener: the session's pid is still 0.
let bare = stopped_attach(0);
let fake = Arc::new(dumping_threads(555, vec![Ok(THREADS.into())]));
let probe: Arc<dyn AttachProbe> = fake.clone();
let dump = ready_dump(known_pid_dump(&bare.session, |_| probe, 555, Some(json_dir().into())).await.unwrap());
assert_eq!((dump.pid, dump.taken_while_suspended), (555, true));
assert_eq!((dump.virtual_json, dump.virtual_note), (None, Some(VirtualThreadsNote::WhileSuspended)));
assert_eq!(*fake.commands.lock(), ["thread_print"]);
// Running, the same session gets the JSON dump too.
let bare = bare_session("attach");
let fake = Arc::new(dumping_threads(555, vec![Ok(THREADS.into())]));
*fake.json_dumps.lock() = vec![Ok(VIRTUAL_JSON.into())].into();
let probe: Arc<dyn AttachProbe> = fake.clone();
let dump = ready_dump(known_pid_dump(&bare.session, |_| probe, 555, Some(json_dir().into())).await.unwrap());
assert_eq!((dump.virtual_json.as_deref(), dump.virtual_note), (Some(VIRTUAL_JSON), None));
assert_eq!(*fake.commands.lock(), ["ensure_listener", "thread_print", "thread_dump_json"]);
}
#[tokio::test]
async fn run_dump_of_a_debugged_jvm_waits_for_the_session_turn() {
let bare = bare_session("attach");
@@ -1534,7 +1397,7 @@ async fn run_dump_of_a_debugged_jvm_waits_for_the_session_turn() {
let probe: Arc<dyn AttachProbe> = fake.clone();
let histogram = bare.session.jvm_memory.lock().await;
let mut queued = Box::pin(known_pid_dump(&bare.session, |_| probe, 4242, None));
let mut queued = Box::pin(known_pid_dump(&bare.session, |_| probe, 4242));
assert!(tokio::time::timeout(Duration::from_millis(50), &mut queued).await.is_err());
// The program hits a breakpoint while the dump waits behind the session's histogram.
bare.session.suspended.stopped(None, true);
@@ -1548,28 +1411,28 @@ fn threads_of_an_exited_program() {
let mut fake = dumping_threads(99, Vec::new());
fake.alive = false;
*fake.listener_starts.lock() = vec![Err(AttachError::NoListener)].into();
assert_eq!(threads_unavailable(dump_text(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::ProgramExited));
assert_eq!(threads_unavailable(dump_text(&fake, 12, true)), threads_jvm(JvmMemoryUnavailable::ProgramExited));
assert_eq!(threads_unavailable(dump_threads(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::ProgramExited));
assert_eq!(threads_unavailable(dump_threads(&fake, 12, true)), threads_jvm(JvmMemoryUnavailable::ProgramExited));
}
#[test]
fn thread_dump_errors_map_to_reasons() {
let fake = dumping_threads(12, vec![Err(AttachError::Timeout)]);
assert_eq!(threads_unavailable(dump_text(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::TimedOut));
assert_eq!(threads_unavailable(dump_threads(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::TimedOut));
let fake = dumping_threads(99, Vec::new());
*fake.listener_starts.lock() = vec![Err(AttachError::ListenerDidNotStart)].into();
assert_eq!(threads_unavailable(dump_text(&fake, 12, false)), JvmThreadsUnavailable::ListenerDidNotStart);
assert_eq!(threads_unavailable(dump_threads(&fake, 12, false)), JvmThreadsUnavailable::ListenerDidNotStart);
assert_eq!(*fake.commands.lock(), ["ensure_listener"]);
let mut fake = dumping_threads(99, Vec::new());
*fake.listener_starts.lock() = vec![Err(AttachError::NotAJvm), Err(AttachError::NotAJvm)].into();
assert_eq!(threads_unavailable(dump_text(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::NoJvmProcess));
assert_eq!(threads_unavailable(dump_threads(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::NoJvmProcess));
fake.alive = false;
assert_eq!(threads_unavailable(dump_text(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::ProgramExited));
assert_eq!(threads_unavailable(dump_threads(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::ProgramExited));
let fake = dumping_threads(12, vec![Err(AttachError::Command { code: 1, message: "no".into() })]);
let JvmThreadsUnavailable::Failed { message } = threads_unavailable(dump_text(&fake, 12, false)) else {
let JvmThreadsUnavailable::Failed { message } = threads_unavailable(dump_threads(&fake, 12, false)) else {
panic!("not a failure")
};
assert!(message.contains("no"), "{message}");
@@ -1593,20 +1456,14 @@ fn thread_results_serialize_with_camel_case_tags() {
java_version: String::new(),
taken_while_suspended: true,
elapsed_ms: 3,
virtual_json: None,
virtual_note: Some(VirtualThreadsNote::WhileSuspended),
};
assert_eq!(
serde_json::to_value(JvmThreadsResult::Ready { dump }).unwrap(),
serde_json::json!({
"status": "ready",
"dump": {
"text": "t", "pid": 7, "javaVersion": "", "takenWhileSuspended": true, "elapsedMs": 3,
"virtualJson": null, "virtualNote": "whileSuspended"
}
"dump": {"text": "t", "pid": 7, "javaVersion": "", "takenWhileSuspended": true, "elapsedMs": 3}
})
);
assert_eq!(serde_json::to_value(VirtualThreadsNote::TooLarge).unwrap(), serde_json::json!("tooLarge"));
}
#[cfg(unix)]
@@ -1622,7 +1479,7 @@ async fn threads_take_the_memory_lock() {
let running = Suspension::default();
let (classes, threads) = tokio::join!(
snapshot(&state, &running, |_| probe.clone(), JvmTarget::Launched(pid as i32), None),
thread_dump(&state, || false, |_| probe.clone(), JvmTarget::Launched(pid as i32), None)
thread_dump(&state, || false, |_| probe.clone(), JvmTarget::Launched(pid as i32))
);
assert!(matches!(classes.unwrap(), JvmMemoryResult::Ready { .. }));
let threads = threads.unwrap();
@@ -1636,14 +1493,12 @@ async fn threads_take_the_memory_lock() {
async fn queued_thread_dump_reads_suspension_under_the_lock() {
let pid = std::process::id();
let state = tokio::sync::Mutex::new(JvmMemoryState::default());
let suspended = Arc::new(Suspension::default());
let suspended = Suspension::default();
let fake = Arc::new(dumping_threads(0, Vec::new()));
let probe: Arc<dyn AttachProbe> = fake.clone();
let running = state.lock().await;
let stopped = suspended.clone();
let target = JvmTarget::Launched(pid as i32);
let mut queued = Box::pin(thread_dump(&state, move || stopped.get(), |_| probe, target, Some(json_dir().into())));
let mut queued = Box::pin(thread_dump(&state, || suspended.get(), |_| probe, JvmTarget::Launched(pid as i32)));
assert!(tokio::time::timeout(Duration::from_millis(50), &mut queued).await.is_err());
// The program hits a breakpoint while the dump waits behind a class-table request.
suspended.stopped(None, true);
@@ -1660,27 +1515,12 @@ async fn attached_thread_dump_keeps_the_scanned_jvm() {
fake.jdwp = Some((5005, 4242));
let probe: Arc<dyn AttachProbe> = Arc::new(fake);
let target = JvmTarget::Attached { pid: &jvm_pid, jdwp_port: Some(5005) };
let r = thread_dump(&state, || false, |_| probe, target, None).await.unwrap();
let r = thread_dump(&state, || false, |_| probe, target).await.unwrap();
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
assert_eq!(dump.pid, 4242);
assert_eq!(jvm_pid.load(Ordering::SeqCst), 4242);
}
#[cfg(unix)]
#[tokio::test]
async fn session_thread_dump_writes_the_json_into_the_given_directory() {
let pid = std::process::id();
let state = tokio::sync::Mutex::new(JvmMemoryState::default());
let fake = dumping_threads(pid, vec![Ok(THREADS.into())]);
*fake.json_dumps.lock() = vec![Ok(VIRTUAL_JSON.into())].into();
let fake = Arc::new(fake);
let probe: Arc<dyn AttachProbe> = fake.clone();
let target = JvmTarget::Launched(pid as i32);
let r = thread_dump(&state, || false, |_| probe, target, Some(json_dir().into())).await.unwrap();
assert_eq!(ready_dump(r).virtual_json.as_deref(), Some(VIRTUAL_JSON));
assert_eq!(*fake.json_dirs.lock(), [json_dir()]);
}
#[tokio::test]
async fn capability_matches_memory() {
for adapter in JVM_MEMORY_ADAPTERS.iter().copied().chain(["debugpy"]) {
+17 -96
View File
@@ -8,15 +8,11 @@ use super::{
};
use crate::session::Session;
use ide_core::{IdeError, IdeResult};
use ide_jvm_attach::{AttachError, JavaVersion};
use ide_jvm_attach::AttachError;
use serde::{Deserialize, Serialize};
use specta::Type;
use std::path::{Path, PathBuf};
use std::sync::Arc;
/// The first release whose virtual threads are final and that writes the JSON dump.
const VIRTUAL_THREADS_MAJOR: u32 = 21;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct JvmThreadDump {
@@ -27,20 +23,6 @@ pub struct JvmThreadDump {
pub taken_while_suspended: bool,
/// Wall time of the `Thread.print` request.
pub elapsed_ms: u32,
/// `Thread.dump_to_file -format=json`, which also lists virtual threads; JDK 21+ only.
pub virtual_json: Option<String>,
/// Why `virtual_json` is missing from a JDK 21+ dump; none below 21.
pub virtual_note: Option<VirtualThreadsNote>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum VirtualThreadsNote {
/// A debugger holds the VM, which would hang the JSON request until it resumes.
WhileSuspended,
/// Over the attach reply limit (64 MiB).
TooLarge,
Failed,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
@@ -66,17 +48,13 @@ pub enum JvmThreadsResult {
Unavailable { reason: JvmThreadsUnavailable },
}
/// A thread dump of `pid`, a JVM no debugger holds; `json_dir` is an absolute, owner-only
/// directory the JVM may write the JSON dump into. Blocking for up to the listener start and
/// A thread dump of `pid`, a JVM no debugger holds. Blocking for up to the listener start and
/// dump timeouts, so callers run it in `spawn_blocking`.
pub fn run_jvm_thread_dump(pid: u32, json_dir: Option<&Path>) -> JvmThreadsResult {
dump_threads(&JdkProbe { suspended: false }, pid, false, json_dir, &|| false)
pub fn run_jvm_thread_dump(pid: u32) -> JvmThreadsResult {
dump_threads(&JdkProbe { suspended: false }, pid, false)
}
pub(crate) async fn session_thread_dump(
session: Arc<Session>,
json_dir: Option<PathBuf>,
) -> IdeResult<JvmThreadsResult> {
pub(crate) async fn session_thread_dump(session: Arc<Session>) -> IdeResult<JvmThreadsResult> {
until_located(&session).await;
let launched = histogram_pid(&session);
// Detached, so a caller that gives up cannot release the lock while the JVM is still
@@ -84,9 +62,7 @@ pub(crate) async fn session_thread_dump(
tokio::spawn(async move {
let target = session_target(&session, launched);
let probe = |suspended| -> Arc<dyn AttachProbe> { Arc::new(JdkProbe { suspended }) };
let stopped = session.clone();
let suspended = move || capture_suspended(&stopped);
thread_dump(&session.jvm_memory, suspended, probe, target, json_dir).await
thread_dump(&session.jvm_memory, || capture_suspended(&session), probe, target).await
})
.await
.map_err(|e| IdeError::internal(format!("JVM thread dump failed: {e}")))?
@@ -94,53 +70,43 @@ pub(crate) async fn session_thread_dump(
/// A thread dump of `pid`, a run's JVM that `session` debugs, taken as the session's own dump
/// is: a JVM the debugger holds suspended is never asked to open a listener.
pub(crate) async fn debugged_run_thread_dump(
session: Arc<Session>,
pid: u32,
json_dir: Option<PathBuf>,
) -> IdeResult<JvmThreadsResult> {
pub(crate) async fn debugged_run_thread_dump(session: Arc<Session>, pid: u32) -> IdeResult<JvmThreadsResult> {
// Detached for the same reason as `session_thread_dump`.
tokio::spawn(async move {
let probe = |suspended| -> Arc<dyn AttachProbe> { Arc::new(JdkProbe { suspended }) };
known_pid_dump(&session, probe, pid, json_dir).await
known_pid_dump(&session, probe, pid).await
})
.await
.map_err(|e| IdeError::internal(format!("JVM thread dump failed: {e}")))?
}
/// The session's suspension decides the JSON dump too: it is read again before that request.
pub(super) async fn known_pid_dump(
session: &Arc<Session>,
session: &Session,
probe: impl FnOnce(bool) -> Arc<dyn AttachProbe>,
pid: u32,
json_dir: Option<PathBuf>,
) -> IdeResult<JvmThreadsResult> {
let target =
i32::try_from(pid).map_or(JvmTarget::Unavailable(JvmMemoryUnavailable::NoJvmProcess), JvmTarget::Known);
let stopped = session.clone();
let suspended = move || capture_suspended(&stopped);
thread_dump(&session.jvm_memory, suspended, probe, target, json_dir).await
thread_dump(&session.jvm_memory, || capture_suspended(session), probe, target).await
}
/// Takes the class-table lock, so a dump never runs beside a histogram or heap dump of the same
/// session; `suspended_now` and then `probe` are read once it is held, and `suspended_now` again
/// before the JSON dump.
/// session; `suspended` and then `probe` are read once it is held.
pub(super) async fn thread_dump(
state: &tokio::sync::Mutex<JvmMemoryState>,
suspended_now: impl Fn() -> bool + Send + Sync + 'static,
suspended: impl FnOnce() -> bool,
probe: impl FnOnce(bool) -> Arc<dyn AttachProbe>,
target: JvmTarget<'_>,
json_dir: Option<PathBuf>,
) -> IdeResult<JvmThreadsResult> {
let _turn = state.lock().await;
let suspended = suspended_now();
let suspended = suspended();
let lookup = match lookup(target) {
Ok(lookup) => lookup,
Err(reason) => return Ok(jvm(reason)),
};
let probe = probe(suspended);
let (found, outcome) = tokio::task::spawn_blocking(move || match resolve_jvm(lookup, &*probe, suspended) {
Ok((tree, found)) => (found, dump_tree(&*probe, &tree, suspended, json_dir.as_deref(), &suspended_now)),
Ok((tree, found)) => (found, dump_tree(&*probe, &tree, suspended)),
Err(reason) => (None, jvm(reason)),
})
.await
@@ -152,32 +118,19 @@ pub(super) async fn thread_dump(
/// `tree` starts with the session's reported pid, followed by its descendants: the JVM is the
/// first with a listener, else the first application JVM (the reported pid may be a shell or a
/// Gradle client), else the reported pid.
pub(super) fn dump_tree(
probe: &dyn AttachProbe,
tree: &[i32],
suspended: bool,
json_dir: Option<&Path>,
suspended_now: &dyn Fn() -> bool,
) -> JvmThreadsResult {
pub(super) fn dump_tree(probe: &dyn AttachProbe, tree: &[i32], suspended: bool) -> JvmThreadsResult {
let jvm_pid = pick_jvm_pid(tree, |p| probe.has_listener(p))
.or_else(|| pick_jvm_pid(tree, |p| probe.is_application_jvm(p)))
.or_else(|| tree.first().and_then(|&p| u32::try_from(p).ok()).filter(|&p| p > 0));
match jvm_pid {
Some(pid) => dump_threads(probe, pid, suspended, json_dir, suspended_now),
Some(pid) => dump_threads(probe, pid, suspended),
None => jvm(JvmMemoryUnavailable::NoJvmProcess),
}
}
/// Blocking. A JVM a debugger holds suspended cannot open a listener (its Signal Dispatcher is
/// stopped), and one below 17 hangs even with one, so it is asked only when both are ruled out.
/// The JSON dump follows a text dump that succeeded; its failure only sets the note.
pub(crate) fn dump_threads(
probe: &dyn AttachProbe,
pid: u32,
suspended: bool,
json_dir: Option<&Path>,
suspended_now: &dyn Fn() -> bool,
) -> JvmThreadsResult {
pub(crate) fn dump_threads(probe: &dyn AttachProbe, pid: u32, suspended: bool) -> JvmThreadsResult {
if suspended {
if !probe.has_listener(pid) {
return jvm(gone(probe, pid));
@@ -196,8 +149,6 @@ pub(crate) fn dump_threads(
Err(e) => return failure(probe, pid, e),
};
let elapsed_ms = u32::try_from(started.elapsed().as_millis()).unwrap_or(u32::MAX);
let (virtual_json, virtual_note) =
virtual_threads(probe, pid, version.as_ref(), suspended, json_dir, suspended_now);
JvmThreadsResult::Ready {
dump: JvmThreadDump {
text,
@@ -205,40 +156,10 @@ pub(crate) fn dump_threads(
java_version: version.map(|v| v.text).unwrap_or_default(),
taken_while_suspended: suspended,
elapsed_ms,
virtual_json,
virtual_note,
},
}
}
/// The program may have stopped during the text dump, so the suspension is read again.
fn virtual_threads(
probe: &dyn AttachProbe,
pid: u32,
version: Option<&JavaVersion>,
suspended: bool,
json_dir: Option<&Path>,
suspended_now: &dyn Fn() -> bool,
) -> (Option<String>, Option<VirtualThreadsNote>) {
if version.is_none_or(|v| v.major < VIRTUAL_THREADS_MAJOR) {
return (None, None);
}
if suspended || suspended_now() {
return (None, Some(VirtualThreadsNote::WhileSuspended));
}
let Some(dir) = json_dir else {
return (None, Some(VirtualThreadsNote::Failed));
};
match probe.thread_dump_json(pid, dir) {
Ok(json) => (Some(json), None),
Err(AttachError::TooLarge) => (None, Some(VirtualThreadsNote::TooLarge)),
Err(e) => {
tracing::warn!("JSON thread dump of JVM {pid}: {e}");
(None, Some(VirtualThreadsNote::Failed))
}
}
}
fn failure(probe: &dyn AttachProbe, pid: u32, error: AttachError) -> JvmThreadsResult {
let reason = match error {
AttachError::ListenerDidNotStart => JvmThreadsUnavailable::ListenerDidNotStart,
+8 -15
View File
@@ -1977,27 +1977,20 @@ impl DebugManager {
jvm_memory::session_heap_dump(session, dir, cancel).await
}
/// `Thread.print -l` of the session's JVM, taking the session's class-table turn, and on JDK
/// 21+ the JSON dump written into `json_dir`. A JVM the debugger holds suspended is asked
/// only when it is 17 or later and its listener already runs: otherwise the request would hang
/// until the program resumes.
pub async fn jvm_thread_dump(&self, s: DebugSessionId, json_dir: Option<PathBuf>) -> IdeResult<JvmThreadsResult> {
/// `Thread.print -l` of the session's JVM, taking the session's class-table turn. A JVM the
/// debugger holds suspended is asked only when it is 17 or later and its listener already
/// runs: otherwise the request would hang until the program resumes.
pub async fn jvm_thread_dump(&self, s: DebugSessionId) -> IdeResult<JvmThreadsResult> {
let session = self.session(s)?;
jvm_memory::session_thread_dump(session, json_dir).await
jvm_memory::session_thread_dump(session).await
}
/// `Thread.print -l` of `pid`, the JVM of `run`, when a live session debugs it (a build
/// tool's run started for Debug, Attach to Process): taken as [`Self::jvm_thread_dump`] takes
/// it, under that session's turn and suspension, so a suspended JVM is not asked for the JSON
/// dump either. `None` when no session debugs `pid`.
pub async fn debugged_jvm_thread_dump(
&self,
run: RunId,
pid: u32,
json_dir: Option<PathBuf>,
) -> Option<IdeResult<JvmThreadsResult>> {
/// it, under that session's turn and suspension. `None` when no session debugs `pid`.
pub async fn debugged_jvm_thread_dump(&self, run: RunId, pid: u32) -> Option<IdeResult<JvmThreadsResult>> {
let session = self.jvm_session_of(run, pid)?;
Some(jvm_memory::debugged_run_thread_dump(session, pid, json_dir).await)
Some(jvm_memory::debugged_run_thread_dump(session, pid).await)
}
/// A session attached to `run` first: one whose JVM is not located yet (its attach-time scan
+2 -2
View File
@@ -3096,7 +3096,7 @@ async fn a_run_dump_goes_through_the_session_attached_to_the_run() {
let pid = jvm.id();
assert_eq!(h.manager.jvm_session_of(RunId(7), pid).map(|s| s.id), Some(id));
assert!(h.manager.jvm_session_of(RunId(8), pid).is_none());
let dump = h.manager.debugged_jvm_thread_dump(RunId(7), pid, None).await.unwrap().unwrap();
let dump = h.manager.debugged_jvm_thread_dump(RunId(7), pid).await.unwrap().unwrap();
let alive = jvm.try_wait().unwrap().is_none();
let _ = jvm.kill();
let _ = jvm.wait();
@@ -3120,7 +3120,7 @@ async fn a_run_jvm_is_found_by_the_session_attached_to_it() {
let id = h.start(cfg).await.unwrap();
assert_eq!(h.manager.jvm_session_of(RunId(1), 4242).map(|s| s.id), Some(id));
assert!(h.manager.jvm_session_of(RunId(1), 4243).is_none());
assert!(h.manager.debugged_jvm_thread_dump(RunId(1), 4243, None).await.is_none());
assert!(h.manager.debugged_jvm_thread_dump(RunId(1), 4243).await.is_none());
}
#[cfg(unix)]
-1
View File
@@ -515,7 +515,6 @@ async fn resolve_jvm_application(
test == Some(true),
policy,
&cancel,
None,
)
.await?;
use ide_lsp::jdtls::JavaBuildStatus;
+2 -12
View File
@@ -717,21 +717,11 @@ pub async fn debug_jvm_memory_classes(
host.debugger.jvm_memory_classes(session).await
}
/// A `Thread.print -l` of the debuggee JVM (with the JSON dump on JDK 21+), or why it cannot be
/// taken.
/// A `Thread.print -l` of the debuggee JVM, or why it cannot be taken.
#[command(trust = trusted)]
pub async fn debug_jvm_thread_dump(host: &Host, window: &str, session: DebugSessionId) -> IdeResult<JvmThreadsResult> {
host.require_trust(window)?;
let heap_root = host.heap.root().to_path_buf();
let dir = host.blocking(move || Ok(super::thread_dump::json_dir(&heap_root))).await?;
let result = host.debugger.jvm_thread_dump(session, dir.clone()).await;
let _ = host
.blocking(move || {
super::thread_dump::discard_json_dir(dir);
Ok(())
})
.await;
result
host.debugger.jvm_thread_dump(session).await
}
/// Up to `limit` live instances of the class in the stopped JVM.
+8 -43
View File
@@ -4,11 +4,9 @@ pub(crate) mod cache;
use crate::Host;
use ide_command::command;
use super::Channel;
use super::build::{load, with_profiles, workspace};
use cache::LaunchEvents;
use ide_build::BuildModel;
use ide_build::compile::{self, BuildEvent};
use ide_build::compile;
use ide_core::error::ErrorKind;
use ide_core::settings::Settings;
use ide_core::{CancellationToken, IdeError, IdeResult, RequestId};
@@ -20,8 +18,6 @@ use std::path::{Path, PathBuf};
/// Builds according to `policy`, then resolves the runtime (or test)
/// classpath and the JDK of the module at `module` (absolute, or relative to the project root).
/// A module with Kotlin / Groovy / Scala sources is built by its build system, whose class directories come first.
/// The build streams its console, messages and progress on `on_event` while it runs; a launch
/// whose build another launch's build joins receives that build's events.
#[command(trust = trusted)]
pub async fn java_resolve_launch(
host: &Host,
@@ -30,16 +26,12 @@ pub async fn java_resolve_launch(
test: bool,
policy: BuildPolicy,
request: RequestId,
on_event: Channel<BuildEvent>,
) -> IdeResult<JavaLaunchInfo> {
// Resources a Gradle build filters or renames are processed by Gradle, replacing the language
// server's plain copies.
host.require_trust(window)?;
let cancel = host.begin_project_request(window, request);
let events: LaunchEvents = std::sync::Arc::new(move |event| {
let _ = on_event.send(event);
});
let result = resolve_launch(host, window, module, test, policy, &cancel, Some(events)).await;
let result = resolve_launch(host, window, module, test, policy, &cancel).await;
host.end_request(request);
result
}
@@ -51,15 +43,8 @@ pub(crate) async fn resolve_launch(
test: bool,
policy: BuildPolicy,
cancel: &CancellationToken,
events: Option<LaunchEvents>,
) -> IdeResult<JavaLaunchInfo> {
let started = std::time::Instant::now();
let progress = |message: &str| {
if let Some(events) = &events {
events(BuildEvent::Progress { message: message.to_owned(), fraction: None });
}
};
progress("Resolving the module");
let project = host.project(window)?;
let module = ide_core::project_roots::resolve(&project.root, &module);
let scope = {
@@ -69,11 +54,11 @@ pub(crate) async fn resolve_launch(
.map_err(|e| IdeError::internal(e.to_string()))??
};
if !project.lsp.java_served_by_jdtls(&module) {
return resolve_launch_without_jdtls(host, &project, module, scope, test, policy, cancel, events).await;
return resolve_launch_without_jdtls(host, &project, module, scope, test, policy, cancel).await;
}
let scope = std::sync::Arc::new(scope);
let launches = project.java_launches.for_cache(&scope.cache);
let waiting = launches.waiting.add(module.clone(), test, policy, events.clone());
let waiting = launches.waiting.add(module.clone(), test, policy);
let prefer_maven = scope.settings.languages.java.maven.delegate_build;
// A launch builds incrementally unless the configuration asks for Rebuild or NoBuild.
let build = policy != BuildPolicy::NoBuild;
@@ -105,9 +90,6 @@ pub(crate) async fn resolve_launch(
};
let mut external_build =
if delegated { Some(project.lsp.java_external_build(&module, cancel).await?) } else { None };
if build && !delegated {
progress("Compiling with the Java language server");
}
let mut info = project.lsp.java_launch(&module, test, build && !delegated, full, delegated, cancel).await?;
if info.errors.iter().any(|e| processor_recreated_a_file(&e.message)) {
if build && !delegated && is_maven {
@@ -136,11 +118,6 @@ pub(crate) async fn resolve_launch(
tokio::task::spawn_blocking(move || {
let _external_build = external_build;
let (root, cache, settings) = (&scope.root, &scope.cache, &scope.settings);
let on_event = |event: BuildEvent| {
if let Some(events) = &events {
events(event);
}
};
let local_repo = ide_sdk::apply::maven_local_repository(root, settings);
// Module outputs the launch runs from a snapshot of: the originals must not come back.
let mut snapshotted = Vec::new();
@@ -153,7 +130,7 @@ pub(crate) async fn resolve_launch(
root,
&model,
&module,
cache::BuildOptions { test, policy, rebuild_on_jdt_errors, members, events: events.clone() },
cache::BuildOptions { test, policy, rebuild_on_jdt_errors, members },
local_repo.clone(),
&cancel,
)?;
@@ -163,7 +140,7 @@ pub(crate) async fn resolve_launch(
snapshotted = outputs.originals;
copies
} else if external {
let built = compile::build_for_launch(root, &model, &module, test, build_kind, &cancel, &on_event)?;
let built = compile::build_for_launch(root, &model, &module, test, build_kind, &cancel)?;
if let Some(failure) = built.failure {
if policy != BuildPolicy::MakeAndContinueOnErrors {
return Err(IdeError::internal(failure));
@@ -177,7 +154,6 @@ pub(crate) async fn resolve_launch(
};
let mut class_paths: Vec<String> = built.iter().map(|p| p.to_string_lossy().into_owned()).collect();
if delegated {
on_event(BuildEvent::Progress { message: "Resolving the classpath".into(), fraction: None });
// m2e runs inside jdtls on the server JDK and can resolve a different
// Maven profile/classifier than the module build. Ask the same Maven
// process that built the module for its runtime/test dependencies.
@@ -227,7 +203,6 @@ fn is_maven_module(root: &Path, model: &BuildModel, module: &Path) -> bool {
/// A launch of a module jdtls doesn't serve (another Java language server, or none): the
/// build tool compiles it, and the classpath comes from that server, else from Maven.
#[allow(clippy::too_many_arguments)]
async fn resolve_launch_without_jdtls(
host: &Host,
project: &std::sync::Arc<crate::Project>,
@@ -236,24 +211,18 @@ async fn resolve_launch_without_jdtls(
test: bool,
policy: BuildPolicy,
cancel: &CancellationToken,
events: Option<LaunchEvents>,
) -> IdeResult<JavaLaunchInfo> {
let started = std::time::Instant::now();
let scope = std::sync::Arc::new(scope);
let kind = if policy == BuildPolicy::Rebuild { compile::BuildKind::Rebuild } else { compile::BuildKind::Build };
let (model, built) = {
let (scope, module, cancel, events) = (scope.clone(), module.clone(), cancel.clone(), events.clone());
let (scope, module, cancel) = (scope.clone(), module.clone(), cancel.clone());
tokio::task::spawn_blocking(move || {
let model = load_launch_model(&scope);
let on_event = |event: BuildEvent| {
if let Some(events) = &events {
events(event);
}
};
let built = if policy == BuildPolicy::NoBuild {
None
} else {
Some(compile::build_for_launch(&scope.root, &model, &module, test, kind, &cancel, &on_event))
Some(compile::build_for_launch(&scope.root, &model, &module, test, kind, &cancel))
};
(model, built)
})
@@ -285,9 +254,6 @@ async fn resolve_launch_without_jdtls(
}
}
let build_ms = started.elapsed().as_millis();
if let Some(events) = &events {
events(BuildEvent::Progress { message: "Resolving the classpath".into(), fraction: None });
}
let from_server = project.lsp.java_server_classpath(&module, test, cancel).await?;
let data_dir = host.local_data_dir.clone();
let cancel = cancel.clone();
@@ -508,7 +474,6 @@ async fn build_members(
members.push(cache::Member {
module: launch.module.clone(),
rebuild_on_jdt_errors: rebuild_on_jdt_errors(launch.policy, prefer_maven, errors),
events: launch.events.clone(),
});
}
Ok(members)
+19 -61
View File
@@ -1,5 +1,5 @@
//! Immutable Maven outputs retained in the project cache, including across close/reopen.
use ide_build::compile::{self, BuildEvent, LaunchFingerprint};
use ide_build::compile::{self, LaunchFingerprint};
use ide_core::{CancellationToken, IdeError, IdeResult};
use ide_run::BuildPolicy;
use parking_lot::Mutex;
@@ -131,10 +131,6 @@ pub(super) fn has_record(root: &Path, cache: &Path, module: &Path) -> bool {
[false, true].into_iter().any(|test| record_path(root, cache, module, test).is_some_and(|record| record.is_file()))
}
/// Where the build of a launch streams its console, messages and progress: the run
/// console, the status bar and the Build tool window of the launch's request.
pub(in crate::ops) type LaunchEvents = Arc<dyn Fn(BuildEvent) + Send + Sync>;
#[derive(Default)]
pub(super) struct BuildOptions {
pub test: bool,
@@ -146,15 +142,13 @@ pub(super) struct BuildOptions {
/// together, #3971): their modules join this Maven run, and their launches then reuse
/// the snapshots recorded here instead of running Maven again.
pub members: Vec<Member>,
/// The launch's own events; members that join the build get them too.
pub events: Option<LaunchEvents>,
}
/// A launch module joining another launch's build; see [`BuildOptions::members`].
#[derive(Debug)]
pub(super) struct Member {
pub module: PathBuf,
pub rebuild_on_jdt_errors: bool,
pub events: Option<LaunchEvents>,
}
/// Launches share a build only within the same workspace project's cache.
@@ -186,12 +180,11 @@ impl Sessions {
#[derive(Default)]
pub(crate) struct Waiting(Arc<Mutex<Vec<Arc<WaitingLaunch>>>>);
#[derive(Debug)]
pub(super) struct WaitingLaunch {
pub module: PathBuf,
pub test: bool,
pub policy: BuildPolicy,
/// The launch's build events, for a build it joins.
pub events: Option<LaunchEvents>,
}
/// Leaves [`Waiting`] when dropped.
@@ -201,14 +194,8 @@ pub(super) struct WaitingGuard {
}
impl Waiting {
pub(super) fn add(
&self,
module: PathBuf,
test: bool,
policy: BuildPolicy,
events: Option<LaunchEvents>,
) -> WaitingGuard {
let launch = Arc::new(WaitingLaunch { module, test, policy, events });
pub(super) fn add(&self, module: PathBuf, test: bool, policy: BuildPolicy) -> WaitingGuard {
let launch = Arc::new(WaitingLaunch { module, test, policy });
self.0.lock().push(launch.clone());
WaitingGuard { all: self.0.clone(), launch }
}
@@ -279,7 +266,7 @@ impl Session {
cancel: &CancellationToken,
) -> IdeResult<Outputs> {
self.initialize();
let BuildOptions { test, policy, rebuild_on_jdt_errors, members, events } = options;
let BuildOptions { test, policy, rebuild_on_jdt_errors, members } = options;
let mut lead = match self.prepare(root, model, module, test, policy, &local_repo, cancel)? {
Ok(outputs) => return Ok(outputs),
Err(pending) => pending,
@@ -297,13 +284,11 @@ impl Session {
let policy = if rebuild_on_jdt_errors { BuildPolicy::Rebuild } else { policy };
let mut joined = Vec::new();
let mut rebuild = policy == BuildPolicy::Rebuild;
let mut sinks: Vec<LaunchEvents> = events.into_iter().collect();
for member in members {
if let Err(pending) =
self.prepare(root, model, &member.module, test, BuildPolicy::Make, &local_repo, cancel)?
{
rebuild |= member.rebuild_on_jdt_errors;
sinks.extend(member.events);
joined.push(pending);
}
}
@@ -313,13 +298,7 @@ impl Session {
tracing::info!(?modules, "Building the launch modules in one Maven run");
}
let kind = if rebuild { compile::BuildKind::Rebuild } else { compile::BuildKind::Build };
// Every launch waiting for this build follows it.
let on_event = |event: BuildEvent| {
for sink in &sinks {
sink(event.clone());
}
};
let mut built = compile::build_for_launches(root, model, &modules, test, kind, cancel, &on_event)?.into_iter();
let mut built = compile::build_for_launches(root, model, &modules, test, kind, cancel)?.into_iter();
let lead_built = built.next().unwrap();
for (pending, built) in joined.into_iter().zip(built) {
match built.failure {
@@ -669,31 +648,10 @@ mod tests {
let mut session = Session::new(root.join("cache"));
let (a, b) = (root.join("a"), root.join("b"));
let with = |rebuild_on_jdt_errors: bool| BuildOptions {
members: vec![Member { module: b.clone(), rebuild_on_jdt_errors, events: None }],
members: vec![Member { module: b.clone(), rebuild_on_jdt_errors }],
..Default::default()
};
// The lead's and the member's launches both follow the shared build.
let seen = Arc::new(Mutex::new(Vec::new()));
let sink = |name: &'static str| -> LaunchEvents {
let seen = seen.clone();
Arc::new(move |event| {
if let BuildEvent::Step { command, .. } = event {
seen.lock().push(format!("{name}: {command}"));
}
})
};
let options = BuildOptions {
members: vec![Member { module: b.clone(), rebuild_on_jdt_errors: false, events: Some(sink("b")) }],
events: Some(sink("a")),
..Default::default()
};
let lead = session.build(root, &model, &a, options, None, &cancel).unwrap();
let seen = seen.lock().clone();
assert_eq!(seen.len(), 2, "{seen:?}");
assert!(
seen[0].starts_with("a: ") && seen[1].starts_with("b: ") && seen[0].contains("-pl a,b -am"),
"{seen:?}"
);
let lead = session.build(root, &model, &a, with(false), None, &cancel).unwrap();
assert_eq!(fs::read_to_string(lead.snapshot.join("0/Main.class")).unwrap(), "a");
assert_eq!(fs::read_to_string(lead.snapshot.join("1/Main.class")).unwrap(), "lib");
// b's own launch runs from the snapshot the shared build recorded for it.
@@ -732,17 +690,17 @@ mod tests {
let root = dir.path();
let model = reactor_fixture(root);
let waiting = Waiting::default();
let lead = waiting.add(root.join("a"), false, BuildPolicy::Automatic, None);
let lead = waiting.add(root.join("a"), false, BuildPolicy::Automatic);
let _guards = [
waiting.add(root.join("b"), false, BuildPolicy::Make, None),
waiting.add(root.join("lib"), false, BuildPolicy::Automatic, None),
waiting.add(root.join("b"), false, BuildPolicy::Automatic, None),
waiting.add(root.join("a"), false, BuildPolicy::Automatic, None),
waiting.add(root.join("lib"), true, BuildPolicy::Automatic, None),
waiting.add(root.join("lib"), false, BuildPolicy::Rebuild, None),
waiting.add(root.join("lib"), false, BuildPolicy::MakeAndContinueOnErrors, None),
waiting.add(root.join("lib"), false, BuildPolicy::NoBuild, None),
waiting.add(root.join("other"), false, BuildPolicy::Automatic, None),
waiting.add(root.join("b"), false, BuildPolicy::Make),
waiting.add(root.join("lib"), false, BuildPolicy::Automatic),
waiting.add(root.join("b"), false, BuildPolicy::Automatic),
waiting.add(root.join("a"), false, BuildPolicy::Automatic),
waiting.add(root.join("lib"), true, BuildPolicy::Automatic),
waiting.add(root.join("lib"), false, BuildPolicy::Rebuild),
waiting.add(root.join("lib"), false, BuildPolicy::MakeAndContinueOnErrors),
waiting.add(root.join("lib"), false, BuildPolicy::NoBuild),
waiting.add(root.join("other"), false, BuildPolicy::Automatic),
];
let join = |prefer_maven| {
super::super::joining_launches(
+4 -59
View File
@@ -3,7 +3,6 @@ use ide_command::command;
use ide_core::{IdeResult, RunId};
use ide_dap::{JvmMemoryUnavailable, JvmThreadsResult, JvmThreadsUnavailable};
use ide_jvm_attach::{ProcEntry, is_hotspot, process_table, select_run_jvm};
use std::path::{Path, PathBuf};
use std::sync::Arc;
/// A `Thread.print -l` of the JVM a run started: the deepest HotSpot JVM of the run's process
@@ -23,43 +22,13 @@ pub async fn run_jvm_thread_dump(
Ok(pid) => pid,
Err(refused) => return Ok(refused),
};
let heap_root = host.heap.root().to_path_buf();
let dir = host.blocking(move || Ok(json_dir(&heap_root))).await?;
// A debugger attached to this run or JVM (Debug of a build tool's run, Attach to Process)
// may hold it suspended, which only its session knows.
let result = match host.debugger.debugged_jvm_thread_dump(id, pid, dir.clone()).await {
Some(dump) => dump,
None => {
let json = dir.clone();
// The attach handshake blocks for seconds.
host.blocking(move || Ok(ide_dap::run_jvm_thread_dump(pid, json.as_deref()))).await
}
};
let _ = host
.blocking(move || {
discard_json_dir(dir);
Ok(())
})
.await;
result
}
/// A fresh owner-only directory for the JVM's JSON dump under the heap snapshot root, whose
/// stale-directory sweep also removes a file a JVM writes after its request timed out. `None`
/// when it cannot be created: the dump then goes without virtual threads.
pub(crate) fn json_dir(heap_root: &Path) -> Option<PathBuf> {
ide_heap::create_snapshot_dir(heap_root)
.inspect_err(|e| tracing::warn!("no directory for the JSON thread dump under {}: {e}", heap_root.display()))
.ok()
}
pub(crate) fn discard_json_dir(dir: Option<PathBuf>) {
if let Some(dir) = dir
&& let Err(e) = std::fs::remove_dir_all(&dir)
&& e.kind() != std::io::ErrorKind::NotFound
{
tracing::warn!("could not delete thread dump directory {}: {e}", dir.display());
if let Some(dump) = host.debugger.debugged_jvm_thread_dump(id, pid).await {
return dump;
}
// The attach handshake blocks for seconds.
host.blocking(move || Ok(ide_dap::run_jvm_thread_dump(pid))).await
}
fn unavailable(reason: JvmThreadsUnavailable) -> JvmThreadsResult {
@@ -131,30 +100,6 @@ mod tests {
assert_eq!(run_jvm(false, Some(10), None, table, |pid| pid == 11), Ok(11));
}
#[cfg(unix)]
#[test]
fn json_dir_is_private_and_removed_afterwards() {
use std::os::unix::fs::PermissionsExt;
let root = tempfile::tempdir().unwrap();
let heap_root = root.path().join("heap-snapshots");
let dir = json_dir(&heap_root).expect("a directory");
assert_eq!(dir.parent(), Some(heap_root.as_path()));
assert_eq!(std::fs::metadata(&dir).unwrap().permissions().mode() & 0o777, 0o700);
// A file the JVM wrote after its request timed out goes with the directory.
std::fs::write(dir.join("threads-1-2.json"), "{}").unwrap();
discard_json_dir(Some(dir.clone()));
assert!(!dir.exists());
discard_json_dir(None);
}
#[test]
fn json_dir_is_none_when_it_cannot_be_created() {
let root = tempfile::tempdir().unwrap();
let blocked = root.path().join("file");
std::fs::write(&blocked, "").unwrap();
assert_eq!(json_dir(&blocked), None);
}
#[cfg(not(unix))]
#[test]
fn unsupported_without_reading_the_process_table() {
+3 -20
View File
@@ -85,26 +85,9 @@ done
for (index, root) in roots.into_iter().enumerate() {
let module = if root == &sibling { root.join("app") } else { root.strip_prefix(&primary).unwrap().join("app") };
let test = index != 0;
let events = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
let sink = events.clone();
let channel = ops::Channel::new(move |event: ide_build::compile::BuildEvent| sink.lock().unwrap().push(event));
let info =
ops::java::java_resolve_launch(&host, "main", module, test, BuildPolicy::Make, RequestId::next(), channel)
.await
.unwrap();
// The build streams its command and progress while it runs.
use ide_build::compile::BuildEvent;
let events = events.lock().unwrap();
assert!(
events.iter().any(|e| matches!(e, BuildEvent::Step { command, .. } if command.contains("-pl app -am"))),
"{events:?}"
);
assert!(
events
.iter()
.any(|e| matches!(e, BuildEvent::Progress { message, .. } if message == "Resolving the classpath")),
"{events:?}"
);
let info = ops::java::java_resolve_launch(&host, "main", module, test, BuildPolicy::Make, RequestId::next())
.await
.unwrap();
let out = root.join("app/target").join(if test { "test-classes" } else { "classes" });
let jar = root.join("app").join(if test { "test.jar" } else { "runtime.jar" });
assert!(info.class_paths.iter().any(|p| std::path::Path::new(p) == out));
+3 -8
View File
@@ -18,16 +18,11 @@ const DUMP_BASE_TIMEOUT: Duration = Duration::from_secs(30);
/// Only `-all` and a quoted path: any argument the DCmd rejects while the VM is suspended
/// hangs the attach listener (17/21/25) until resume, and so does an unquoted path with a space.
pub fn heap_dump_command(path: &Path) -> Result<String, AttachError> {
Ok(format!("GC.heap_dump -all {}", quoted_path(path, "heap dump")?))
}
/// `path` in double quotes, as a DCmd argument; `what` names the file in errors.
pub(crate) fn quoted_path(path: &Path, what: &str) -> Result<String, AttachError> {
let text = path.to_str().ok_or_else(|| AttachError::Protocol(format!("{what} path {path:?} is not UTF-8")))?;
let text = path.to_str().ok_or_else(|| AttachError::Protocol(format!("heap dump path {path:?} is not UTF-8")))?;
if text.contains(['"', '\0', '\n', '\r']) {
return Err(AttachError::Protocol(format!("{what} path {text:?} cannot be quoted for the JVM")));
return Err(AttachError::Protocol(format!("heap dump path {text:?} cannot be quoted for the JVM")));
}
Ok(format!("\"{text}\""))
Ok(format!("GC.heap_dump -all \"{text}\""))
}
/// The JVM answers result code 0 for IO failures too, so success is told apart by its text.
+1 -2
View File
@@ -20,6 +20,5 @@ pub use listener::{LISTENER_START_TIMEOUT, ensure_listener, is_hotspot};
pub use properties::{jdwp_port, parse_properties};
pub use socket::{AttachError, MAX_OUTPUT, agent_properties, has_listener, jcmd, temp_dir};
pub use threads::{
ProcEntry, RUN_TOKEN_PROPERTY, THREAD_DUMP_TIMEOUT, is_application_jvm, process_table, select_run_jvm,
thread_dump_json, thread_print,
ProcEntry, RUN_TOKEN_PROPERTY, THREAD_DUMP_TIMEOUT, is_application_jvm, process_table, select_run_jvm, thread_print,
};
+2 -126
View File
@@ -1,12 +1,9 @@
use std::collections::{HashMap, HashSet, VecDeque};
use std::io::Read;
use std::path::Path;
use std::process::Command;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use std::time::Duration;
use crate::heap_dump::quoted_path;
use crate::listener::is_hotspot;
use crate::socket::{AttachError, MAX_OUTPUT, jcmd};
use crate::socket::{AttachError, jcmd};
/// Default budget for `thread_print`; a dump of a healthy JVM takes milliseconds, so this only
/// bounds a JVM stuck at a safepoint.
@@ -33,55 +30,6 @@ pub fn thread_print(pid: u32, timeout: Duration) -> Result<String, AttachError>
jcmd(pid, "Thread.print -l", timeout)
}
/// `Thread.dump_to_file -format=json`, the only dump that lists virtual threads (JDK 21+). The
/// JVM writes it into `dir`, an absolute directory; the file is read up to [`MAX_OUTPUT`] and
/// deleted whatever the outcome. Never send it to a VM a debugger holds suspended: 21 and 25 hang
/// the request, and every later attach request behind it, until the VM resumes.
pub fn thread_dump_json(pid: u32, dir: &Path, timeout: Duration) -> Result<String, AttachError> {
dump_json_with(pid, dir, MAX_OUTPUT, |command| jcmd(pid, command, timeout))
}
fn dump_json_with(
pid: u32,
dir: &Path,
max: usize,
send: impl FnOnce(&str) -> Result<String, AttachError>,
) -> Result<String, AttachError> {
// The JVM resolves a relative path against its own working directory.
if !dir.is_absolute() {
return Err(AttachError::Protocol(format!("thread dump directory {dir:?} is not absolute")));
}
// JDK 21 has no `-overwrite` and writes nothing when the file exists.
let nanos = SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |since| since.as_nanos());
let path = dir.join(format!("threads-{pid}-{nanos}.json"));
let command = format!("Thread.dump_to_file -format=json {}", quoted_path(&path, "thread dump")?);
let _delete = DeleteOnDrop(&path);
let reply = send(&command)?;
read_capped(&path, max).map_err(|e| match e {
AttachError::Io(e) if e.kind() == std::io::ErrorKind::NotFound => {
AttachError::Protocol(format!("the JVM wrote no thread dump: {}", reply.trim()))
}
e => e,
})
}
fn read_capped(path: &Path, max: usize) -> Result<String, AttachError> {
let mut bytes = Vec::new();
std::fs::File::open(path)?.take(max as u64 + 1).read_to_end(&mut bytes)?;
if bytes.len() > max {
return Err(AttachError::TooLarge);
}
String::from_utf8(bytes).map_err(|_| AttachError::Protocol("the thread dump is not UTF-8".into()))
}
struct DeleteOnDrop<'a>(&'a Path);
impl Drop for DeleteOnDrop<'_> {
fn drop(&mut self) {
let _ = std::fs::remove_file(self.0);
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct ProcEntry {
pub pid: u32,
@@ -171,7 +119,6 @@ fn deepest_jvm_in_tree(table: &[ProcEntry], root: u32, is_hotspot: &dyn Fn(u32)
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
fn entry(pid: u32, ppid: u32, command: &str) -> ProcEntry {
ProcEntry { pid, ppid, command: command.to_string() }
@@ -292,77 +239,6 @@ mod tests {
assert_eq!(select_run_jvm(&table, 10, None, not_the_shell), Some(11));
}
/// The path the fake JVM is asked to write, from `Thread.dump_to_file … "<path>"`.
fn requested_path(command: &str) -> PathBuf {
PathBuf::from(command.split('"').nth(1).expect("quoted path"))
}
fn is_empty(dir: &Path) -> bool {
std::fs::read_dir(dir).unwrap().next().is_none()
}
/// `<tmp>/a b`: the space is what an unquoted path would break on.
fn dir_with_space() -> (tempfile::TempDir, PathBuf) {
let root = tempfile::tempdir().unwrap();
let dir = root.path().join("a b");
std::fs::create_dir(&dir).unwrap();
(root, dir)
}
#[test]
fn json_dump_reads_the_file_and_deletes_it() {
let (_root, dir) = dir_with_space();
let mut sent = String::new();
let json = dump_json_with(42, &dir, 1024, |command| {
sent = command.to_owned();
std::fs::write(requested_path(command), "{\"threadDump\":{}}").unwrap();
Ok(format!("Created {}\n", requested_path(command).display()))
})
.unwrap();
assert_eq!(json, "{\"threadDump\":{}}");
let prefix = format!("Thread.dump_to_file -format=json \"{}/threads-42-", dir.display());
assert!(sent.starts_with(&prefix) && sent.ends_with(".json\""), "{sent}");
assert!(is_empty(&dir));
}
#[test]
fn json_dump_file_is_deleted_when_it_is_too_large() {
let (_root, dir) = dir_with_space();
let result = dump_json_with(42, &dir, 1024, |command| {
std::fs::write(requested_path(command), vec![b' '; 1025]).unwrap();
Ok(String::new())
});
assert!(matches!(result, Err(AttachError::TooLarge)), "{result:?}");
assert!(is_empty(&dir));
}
#[test]
fn json_dump_file_is_deleted_when_the_request_fails() {
let (_root, dir) = dir_with_space();
let result = dump_json_with(42, &dir, 1024, |command| {
// The JVM wrote the file but the reply came too late.
std::fs::write(requested_path(command), "{}").unwrap();
Err(AttachError::Timeout)
});
assert!(matches!(result, Err(AttachError::Timeout)), "{result:?}");
assert!(is_empty(&dir));
}
#[test]
fn json_dump_without_a_file_reports_the_reply() {
let (_root, dir) = dir_with_space();
// JDK 21 answers result code 0 when it writes nothing.
let result = dump_json_with(42, &dir, 1024, |_| Ok("/x.json exists, use -overwrite to overwrite\n".into()));
let Err(AttachError::Protocol(message)) = result else { panic!("{result:?}") };
assert!(message.contains("exists"), "{message}");
}
#[test]
fn json_dump_refuses_a_relative_directory() {
let result = dump_json_with(42, Path::new("dumps"), 1024, |_| panic!("sent a relative path"));
assert!(matches!(result, Err(AttachError::Protocol(_))), "{result:?}");
}
#[test]
fn select_skips_gradle_workers_and_the_kotlin_daemon() {
// `--no-daemon`: the build's helper JVMs sit beside the application in the run's tree.
+1 -50
View File
@@ -11,7 +11,7 @@ use ide_jvm_attach::{
AttachError, HeapDumpReply, LISTENER_START_TIMEOUT, THREAD_DUMP_TIMEOUT, agent_properties, ensure_listener,
find_jvm_by_jdwp_port, has_listener, heap_dump, heap_dump_command, histogram_safe_while_suspended, is_hotspot,
java_version_of, jcmd, jdwp_port, parse_class_histogram, parse_heap_dump_reply, parse_release, process_table,
select_run_jvm, temp_dir, thread_dump_json, thread_print, vm_flags,
select_run_jvm, temp_dir, thread_print, vm_flags,
};
/// Two threads that each hold one monitor and wait for the other's after 200 ms.
@@ -33,25 +33,6 @@ public class Deadlock {
}
"#;
/// Two virtual threads in a monitor deadlock, which `Thread.print` does not list.
const VIRTUAL_DEADLOCK_JAVA: &str = r#"
public class VirtualDeadlock {
static final Object A = new Object(), B = new Object();
static void sleep(long ms) {
try { Thread.sleep(ms); } catch (InterruptedException e) { throw new RuntimeException(e); }
}
public static void main(String[] args) {
Thread.ofVirtual().name("v-sync-1").start(() -> { synchronized (A) { sleep(200); synchronized (B) { } } });
Thread.ofVirtual().name("v-sync-2").start(() -> { synchronized (B) { sleep(200); synchronized (A) { } } });
System.out.println("READY");
System.out.flush();
sleep(60_000);
}
}
"#;
const MAIN_JAVA: &str = r#"
import java.util.ArrayList;
import java.util.List;
@@ -405,33 +386,3 @@ fn thread_print_reports_a_deadlock() {
assert!(table.iter().any(|entry| entry.pid == pid && entry.command.contains("Deadlock")));
assert_eq!(select_run_jvm(&table, pid, None, is_hotspot), Some(pid));
}
#[test]
#[ignore = "needs a real JDK >= 21: set OPENIDEA_TEST_JAVA to its bin/java"]
fn thread_dump_json_lists_virtual_threads() {
let Some(java) = std::env::var_os("OPENIDEA_TEST_JAVA").map(PathBuf::from) else {
eprintln!("OPENIDEA_TEST_JAVA is not set; skipping");
return;
};
let major = reported_major(&java);
if major < 21 {
eprintln!("JDK {major} has no virtual threads; skipping");
return;
}
let dir = tempfile::tempdir().unwrap();
let mut guard =
launch_class(&java, dir.path(), "VirtualDeadlock", VIRTUAL_DEADLOCK_JAVA, &["-XX:+StartAttachListener"]);
let pid = guard.0.id();
wait_for_ready(&output_lines(&mut guard.0));
wait_for_listener(pid);
std::thread::sleep(Duration::from_secs(1));
let dumps = dir.path().join("a b");
std::fs::create_dir(&dumps).unwrap();
let started = Instant::now();
let json = thread_dump_json(pid, &dumps, THREAD_DUMP_TIMEOUT).unwrap();
eprintln!("JDK {major} JSON thread dump: {} bytes in {:?}", json.len(), started.elapsed());
assert!(json.contains("\"threadContainers\""), "{json}");
assert!(json.contains("\"v-sync-1\"") && json.contains("\"v-sync-2\""), "{json}");
assert!(std::fs::read_dir(&dumps).unwrap().next().is_none(), "dump file left in {dumps:?}");
}
-1
View File
@@ -358,7 +358,6 @@ pub enum FoldKind {
Region,
Comment,
Imports,
Compact,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
+1 -70
View File
@@ -144,11 +144,7 @@ pub(super) fn folding(
if !node.is_named() {
return true;
}
if spec.name == "go"
&& let Some(end) = go_compact_end(&node, text)
{
push(&mut out, start, end, FoldKind::Compact);
} else if let Some(close_row) = kinds.bracket_close_row(&node) {
if let Some(close_row) = kinds.bracket_close_row(&node) {
push(&mut out, start, close_row, FoldKind::Region);
} else if kinds.has(&node, FOLD_NODE) {
push(&mut out, start, last_content_row(&node, text), FoldKind::Region);
@@ -161,71 +157,6 @@ pub(super) fn folding(
out
}
// Only join a single statement on the next line. Comments, blank lines and
// nested multi-line statements must keep their own lines.
fn go_compact_end(node: &Node, text: &str) -> Option<usize> {
let start = node.start_position().row;
let braced = match node.kind() {
"block" => {
let parent = node.parent()?;
if parent.kind() != "if_statement"
|| parent.child_by_field_name("consequence") != Some(*node)
|| !go_error_guard(parent.child_by_field_name("condition")?, text)
{
return None;
}
true
}
"expression_case" | "type_case" | "communication_case" | "default_case" => false,
_ => return None,
};
let body = node.named_child(node.named_child_count().checked_sub(1)?)?;
if body.kind() != "statement_list" || body.named_child_count() != 1 {
return None;
}
let header_end = body.prev_sibling()?;
if header_end.kind() != if braced { "{" } else { ":" } || header_end.end_position().row != start {
return None;
}
let statement = body.named_child(0)?;
let position = statement.start_position();
if statement.has_error()
|| statement.is_extra()
|| position.row != start + 1
|| statement.end_position().row != position.row
|| !own_line(text, statement.start_byte(), position.column)
|| !text.get(header_end.end_byte()..statement.start_byte())?.trim().is_empty()
{
return None;
}
let tail = text.get(statement.end_byte()..)?.split('\n').next()?.trim();
if !matches!(tail, "" | ";") {
return None;
}
let end = start + if braced { 2 } else { 1 };
(!braced || node.end_position().row == end).then_some(end)
}
// Folding runs without Go type information. Recognize conventional error
// guards and leave other nil checks alone.
fn go_error_guard(condition: Node, text: &str) -> bool {
if condition.kind() != "binary_expression"
|| !condition.child_by_field_name("operator").is_some_and(|op| op.kind() == "!=")
{
return false;
}
let (Some(left), Some(right)) = (condition.child_by_field_name("left"), condition.child_by_field_name("right"))
else {
return false;
};
let name = match (left.kind(), right.kind()) {
("identifier", "nil") => left,
("nil", "identifier") => right,
_ => return false,
};
name.utf8_text(text.as_bytes()).is_ok_and(|name| name == "err" || name.ends_with("Err"))
}
fn push(out: &mut Vec<FoldRange>, start: usize, end: usize, kind: FoldKind) {
if end > start {
out.push(FoldRange { start_line: start as u32, end_line: end as u32, kind });
-50
View File
@@ -1206,56 +1206,6 @@ fn folding_go_imports_and_ruby_ends() {
);
}
#[test]
fn go_compact_folds_keep_only_single_line_statements_inline() {
let src = r#"package main
func f() {
if err != nil {
return err
}
if err != nil {
return err // keep the comment on its own line
}
switch mode {
case "compact":
run()
case "multi":
run()
stop()
default:
return err
}
if err != nil {
return fmt.Errorf(
"keep both lines")
}
}
"#;
let found = folds("go", src);
let compact: Vec<_> = found.iter().copied().filter(|r| r.2 == FoldKind::Compact).collect();
assert_eq!(compact, [(3, 5, FoldKind::Compact), (10, 11, FoldKind::Compact), (15, 16, FoldKind::Compact)]);
assert!(found.contains(&(6, 8, FoldKind::Region)));
assert!(found.contains(&(18, 21, FoldKind::Region)));
}
#[test]
fn go_compact_if_folds_are_limited_to_conventional_error_guards() {
for (guard, kind) in [
("err != nil", FoldKind::Compact),
("nil != err", FoldKind::Compact),
("parseErr := parse(); parseErr != nil", FoldKind::Compact),
("cfg != nil", FoldKind::Region),
("err == nil", FoldKind::Region),
("invalid", FoldKind::Region),
] {
let source = format!(
"package main\nfunc f() error {{\n if {guard} {{\n return err\n }}\n return nil\n}}\n"
);
assert!(folds("go", &source).contains(&(2, 4, kind)), "unexpected fold for {guard}");
}
}
#[test]
fn folding_swift_control_flow_and_haskell_binds() {
assert_eq!(
+1 -15
View File
@@ -46,10 +46,7 @@ fn from_str(line_no: u32, s: &str, ranges: &[(usize, usize)], out: &mut Vec<Line
utf16_len(&s.as_bytes()[..bounds.0])
};
(prev_start, prev_offset) = (bounds.0, text_offset);
// Only the ranges starting in the window: `in_window` reserves room for all it is given,
// and the rest of a long line can hold every match on it.
let starting = rest.partition_point(|&(a, _)| a <= bounds.1);
let (m, used) = in_window(line_no, s, &rest[..starting], bounds, text_offset);
let (m, used) = in_window(line_no, s, rest, bounds, text_offset);
out.push(m);
rest = &rest[used.max(1)..];
if rest.is_empty() {
@@ -268,17 +265,6 @@ mod tests {
assert!(started.elapsed() < std::time::Duration::from_secs(2), "{:?}", started.elapsed());
}
#[test]
fn each_window_holds_room_for_its_own_matches_only() {
// 7,000 windows of one match each on a 4 MB line.
let s = format!("{}function", "x".repeat(592)).repeat(7_000);
let ranges: Vec<_> = s.match_indices("function").map(|(a, m)| (a, a + m.len())).collect();
let mut out = Vec::new();
line_matches(0, s.as_bytes(), &ranges, &mut out);
let reserved: usize = out.iter().map(|m| m.ranges.capacity()).sum();
assert!(reserved <= 4 * out.len(), "{reserved} ranges reserved for {} windows", out.len());
}
/// `main`'s windowing, which counts each window's offset from the line start.
fn reference(line_no: u32, line: &[u8], ranges: &[(usize, usize)]) -> Vec<LineMatch> {
fn from_str(line_no: u32, s: &str, ranges: &[(usize, usize)], out: &mut Vec<LineMatch>) {
-3
View File
@@ -107,12 +107,9 @@ Double-click a table to edit its data, a data source to open its console, and a
| Duplicate (data source) | `⌘D` | `Ctrl+D` |
| Generate DDL to Clipboard | `⌘⌥⇧G` | `Ctrl+Alt+Shift+G` |
| Generate DDL to Query Console | `⌘⌥⇧B` | `Ctrl+Alt+Shift+B` |
| Diagrams › Show Diagram | `⌘⌥⇧U` | `Ctrl+Alt+Shift+U` |
These keys work while the Database tree has focus. The context menu also has **Truncate…**, **Run SQL Script…** (runs every statement of a `.sql` file), **Import Data from File…**, **Go to Referenced Table** (on foreign keys), SQL templates (select, insert, update, delete) and **Remove Data Source…**.
**Diagrams › Show Diagram** opens a read-only ER diagram of the selected tables, or of every table of a selected schema (up to 50), in an editor tab: columns with `PK` / `FK` markers and the foreign keys between the shown tables. Select several tables with `⌘`/`Ctrl`-click or `Shift`-click. Zoom with `⌘`/`Ctrl`+wheel; the diagram's buttons show it full screen or save it as an image.
**Modify Table…** and **New › Table** open a dialog to add, drop or change columns (name, data type, not null, primary key, default) with a live SQL preview. SQLite can only rename or drop existing columns. ClickHouse tables can't be modified this way.
## Query console
+1 -2
View File
@@ -19,7 +19,7 @@ Showing an empty Terminal window opens a tab in the start directory (the project
- **+** (**New Tab**) opens a tab with the default shell.
- The **▾** button (**More Terminal Options**) has **New Terminal Tab**, **New Predefined Session** (one entry per installed shell, plus **SSH Session…**), **Split Right**, **Split Down** and **Settings**.
- Right-click a tab for **Rename Session…**, **Move to Editor**, **Close Tab**, **Close Other Tabs**, **Split Right**, **Split and Move Right**, **Split Down**, **Split and Move Down** and **Unsplit**. Double-clicking a tab also renames it.
- Drag tabs to reorder them, drop a tab on the edge of another group to split, or drag a tab into an editor group (or its edge) to keep the session running as an editor tab. A terminal moved to the editor can return via **Move to Terminal** or by dragging its editor tab onto a Terminal tab strip, pane edge, or the **Terminal** stripe button.
- Drag tabs to reorder them, drop a tab on the edge of another group to split, or drag a tab into an editor group (or its edge) to keep the session running as an editor tab.
A tab is named after your custom name, otherwise after the program running in it (when the shell reports it), otherwise `Local`, `Local (2)` and so on. A spinner shows while a command runs; **Exited** or **Failed** shows once the session ends.
@@ -56,7 +56,6 @@ The pane's context menu has **Copy**, **Paste**, **Select All**, **Clear Buffer*
- `http`, `https` and `file` URLs open in your browser. OSC 8 hyperlinks from programs work too.
- File locations such as `src/main.rs:42:7` or `Main.java(42,7)` open in the editor at that line. Paths resolve against the shell's current directory, then by file name across the project.
- Hold `⌘` (`Ctrl` on Windows/Linux) and hover over an existing file or folder name (`README.md`, `src/features`, `/tmp`) to turn it into a link: clicking opens files in an editor tab of the current window, opens project folders in the **Project** tool window, and reveals folders outside the project in Finder / Explorer / Files.
- Pasting copied files pastes their paths, quoted for the shell in use (bash/zsh/fish, PowerShell or cmd). Pasting an image from the clipboard saves it to a file and pastes that file's path.
- Dropping files from your file manager onto the terminal types their quoted paths at the prompt. They are not run.
-3
View File
@@ -107,12 +107,9 @@ description: "连接 SQL 数据库、浏览架构、在查询控制台中执行
| 复制(数据源) | `⌘D` | `Ctrl+D` |
| 生成 DDL 到剪贴板 | `⌘⌥⇧G` | `Ctrl+Alt+Shift+G` |
| 生成 DDL 到查询控制台 | `⌘⌥⇧B` | `Ctrl+Alt+Shift+B` |
| 图表 › 显示图表 | `⌘⌥⇧U` | `Ctrl+Alt+Shift+U` |
这些快捷键在数据库树获得焦点时生效。右键菜单中还有 **截断…**、**运行 SQL 脚本…**(执行某个 `.sql` 文件中的所有语句)、**从文件导入数据…**、**转到引用的表**(外键上)、SQL 模板(select、insert、update、delete)以及 **移除数据源…**。
**图表 › 显示图表** 会在编辑器标签页中打开所选表(或所选模式中的全部表,最多 50 个)的只读 ER 图:列带有 `PK` / `FK` 标记,并显示所示表之间的外键关系。用 `⌘`/`Ctrl` 单击或 `Shift` 单击可选择多个表。用 `⌘`/`Ctrl`+滚轮缩放;图上的按钮可全屏显示或保存为图片。
**修改表…** 和 **新建 › 表** 会打开一个对话框,可以添加、删除或修改列(名称、数据类型、非空、主键、默认值),并实时预览 SQL。SQLite 只能重命名或删除已有列。ClickHouse 表不能用这种方式修改。
## 查询控制台
+1 -2
View File
@@ -19,7 +19,7 @@ description: "使用内置终端:标签页、拆分、Shell、链接、查找
- **+**(**新建标签页**)用默认 Shell 打开一个标签页。
- **▾** 按钮(**更多终端选项**)包含 **新建终端标签页**、**新建预定义会话**(每个已安装的 Shell 一项,另有 **SSH 会话…**)、**向右拆分**、**向下拆分** 和 **设置**。
- 右键标签页可以 **重命名会话…**、**移至编辑器**、**关闭标签页**、**关闭其他标签页**、**向右拆分**、**向右拆分并移动**、**向下拆分**、**向下拆分并移动**、**取消拆分**。双击标签页也能重命名。
- 拖动标签页可以调整顺序,拖到另一组的边缘会拆分;拖入编辑器分组(或其边缘)则会带着正在运行的会话作为编辑器标签页打开。移到编辑器的终端可通过 **移至终端**,或将编辑器标签拖回终端标签栏、面板边缘或 **终端** 边栏按钮来归位。
- 拖动标签页可以调整顺序,拖到另一组的边缘会拆分;拖入编辑器分组(或其边缘)则会带着正在运行的会话作为编辑器标签页打开。
标签页名称优先用你设置的名字,其次是 Shell 报告的正在运行的程序名,否则就是 `本地`、`本地 (2)` 等默认名称。命令运行时标签上会显示转圈图标,会话结束后显示 **已退出** 或 **失败**。
@@ -56,7 +56,6 @@ OpenIDEA 会按项目记住终端标签页:各自的目录、自定义名称
- `http`、`https` 和 `file` 链接在浏览器中打开,程序输出的 OSC 8 超链接同样可用。
- `src/main.rs:42:7`、`Main.java(42,7)` 这类文件位置会在编辑器中打开并定位到该行。路径先按 Shell 的当前目录解析,找不到时再在整个项目中按文件名查找。
- 按住 `⌘`(Windows/Linux 上为 `Ctrl`)将鼠标悬停在已存在的文件名或文件夹名(如 `README.md`、`src/features`、`/tmp`)上会变为超链接:点击文件会在当前窗口的编辑器标签页中打开,项目内的文件夹会在左侧 **项目** 视图中展开并选中,项目外的文件夹则会在访达 / 资源管理器 / 文件管理器中显示。
- 粘贴复制的文件时,会粘贴按当前 Shell(bash/zsh/fish、PowerShell 或 cmd)规则加好引号的路径。粘贴剪贴板中的图片时,会先保存为文件,再粘贴该文件的路径。
- 从文件管理器把文件拖到终端,会在提示符处输入加了引号的路径,但不会执行。
-11
View File
@@ -61,15 +61,6 @@ const entries: AgentEntry[] = [
diffs: [],
},
{ type: "agent", text: "The preview is ready: front, side and back." },
{
type: "user",
text: "Looks good.",
attachments: [],
sentMs: 3000,
doneMs: 4000,
steered: false,
},
{ type: "agent", text: "Glad it helped." },
];
async function showImages(page: Page, foldTurns = true) {
@@ -112,8 +103,6 @@ for (const foldTurns of [true, false]) {
expect(box.x + box.width).toBeLessThanOrEqual(page.viewportSize()!.width);
const fold = page.locator("details").first();
await expect(fold).not.toHaveAttribute("open");
if (foldTurns) await expect(fold.locator("summary").first()).toContainText("1s");
else await expect(fold.locator("summary").first()).not.toContainText("1s");
await preview.click();
const dialog = page.getByRole("dialog", { name: "Image", exact: true });
await expect(dialog.getByRole("img")).toHaveJSProperty("naturalWidth", 900);
-252
View File
@@ -468,255 +468,3 @@ test("dragging terminal tabs into editor strips and split edges preserves live s
});
expect(await page.evaluate(() => (window as unknown as { __killedPtys: number[] }).__killedPtys)).toEqual([]);
});
test("editor terminal tabs move and drag back to the Terminal stripe, tab strip, and split edges", async ({
workbench: page,
}) => {
await stubDesktop(page);
await page.evaluate(async () => {
const handlers = window.__ipc.handlers;
let id = 0;
const killed: number[] = [];
(window as unknown as { __killedPtys: number[] }).__killedPtys = killed;
handlers.term_default_shell = () => "/bin/zsh";
handlers.term_available_shells = () => ["/bin/zsh"];
handlers.term_spawn = () => ({ id: ++id, title: "zsh", pid: id });
handlers.term_resize = () => null;
handlers.term_write = () => null;
handlers.term_is_busy = () => true;
handlers.term_kill = (args: unknown) => {
killed.push((args as { id: number }).id);
return null;
};
const contributions = "/src/workbench/contributions.ts";
const editor = (await import(contributions)).editorService();
await editor.openFile("/dev/acme-api/App.tsx", { focus: false });
await editor.openFile("/dev/acme-api/README.md", { focus: false });
const store = "/src/workbench/toolwindows/store.ts";
const layout = await import(store);
layout.setToolWindowSize("bottom", 240);
layout.showToolWindow("terminal", true);
});
const terminal = page.getByRole("region", { name: "Terminal", exact: true });
await expect(terminal.locator(".xterm-helper-textarea")).toBeFocused();
await terminal.getByRole("button", { name: "New Tab", exact: true }).click();
const termStrip = terminal.getByRole("tablist", { name: "Terminal sessions" });
await expect(termStrip.getByRole("tab")).toHaveCount(2);
await page.evaluate(async () => {
const store = "/src/features/terminal/store.ts";
const rt = await import(store);
const [first, second] = rt.useTerminals.getState().tabs;
await new Promise<void>((done) => rt.getSession(first!.session)!.term.write("ALPHA-SESSION-OUTPUT\r\n", done));
await new Promise<void>((done) => rt.getSession(second!.session)!.term.write("BETA-TEST-RUNNER\r\n", done));
const actions = "/src/platform/actions.ts";
const { executeAction } = await import(actions);
await executeAction("terminal.moveToEditor", first!.id);
await executeAction("terminal.moveToEditor", second!.id);
});
await expect(terminal).toBeHidden();
const editorTabs = page.getByRole("tablist", { name: "Editor tabs" });
await expect(editorTabs.getByRole("tab")).toHaveText(["App.tsx", "README.md", "Local", "Local (2)"]);
// 1) Drag "Local" from the editor onto the Terminal stripe button while Terminal is hidden.
const editorLocal = editorTabs.getByRole("tab", { name: "Local", exact: true });
const stripeBtn = page.locator('[data-stripe-button="terminal"]');
const from1 = (await editorLocal.boundingBox())!;
const to1 = (await stripeBtn.boundingBox())!;
await page.mouse.move(from1.x + from1.width / 2, from1.y + from1.height / 2);
await page.mouse.down();
await page.mouse.move(to1.x + to1.width / 2, to1.y + to1.height / 2, { steps: 8 });
await page.mouse.up();
await expect(terminal).toBeVisible();
await expect(termStrip.getByRole("tab", { name: "Local", exact: true })).toBeVisible();
await expect(terminal.locator(".xterm-rows")).toContainText("ALPHA-SESSION-OUTPUT");
await expect(terminal.locator(".xterm-helper-textarea")).toBeFocused();
// 2) Drag "Local (2)" from the editor onto the right edge of the Terminal pane to create a split.
const editorLocal2 = editorTabs.getByRole("tab", { name: "Local (2)", exact: true });
const termPanelBox = (await terminal.getByRole("tabpanel").boundingBox())!;
const from2 = (await editorLocal2.boundingBox())!;
await page.mouse.move(from2.x + from2.width / 2, from2.y + from2.height / 2);
await page.mouse.down();
await page.mouse.move(termPanelBox.x + termPanelBox.width - 20, termPanelBox.y + termPanelBox.height / 2, {
steps: 8,
});
await page.mouse.up();
const termStrips = terminal.getByRole("tablist", { name: "Terminal sessions" });
await expect(termStrips).toHaveCount(2);
await expect(editorTabs.getByRole("tab")).toHaveText(["App.tsx", "README.md"]);
await expect(terminal.locator(".xterm-rows").nth(1)).toContainText("BETA-TEST-RUNNER");
// 3) Context menu round-trip: Move to Editor -> editor tab context menu Move to Terminal.
await termStrips.nth(1).getByRole("tab", { name: "Local (2)", exact: true }).click({ button: "right" });
await page.getByRole("menuitem", { name: "Move to Editor" }).click();
const reopenedEditorTab = editorTabs.getByRole("tab", { name: "Local (2)", exact: true });
await expect(reopenedEditorTab).toBeVisible();
await reopenedEditorTab.click({ button: "right" });
const moveBackItem = page.getByRole("menuitem", { name: "Move to Terminal" });
await expect(moveBackItem).toBeVisible();
await moveBackItem.click();
await expect(editorTabs.getByRole("tab")).toHaveText(["App.tsx", "README.md"]);
await expect(termStrip.getByRole("tab")).toHaveText(["Local", "Local (2)"]);
expect(await page.evaluate(() => (window as unknown as { __killedPtys: number[] }).__killedPtys)).toEqual([]);
});
test("⌘+hover turns existing terminal files and folders into hyperlinks and routes clicks by target kind and project scope", async ({
workbench: page,
}) => {
await stubDesktop(page);
await page.evaluate(async () => {
const handlers = window.__ipc.handlers;
let id = 0;
const revealed: string[][] = [];
(window as unknown as { __revealedInFinder: string[][] }).__revealedInFinder = revealed;
const entries: Record<string, "file" | "dir"> = {
"/dev/acme-api/App.tsx": "file",
"/dev/acme-api/src": "dir",
"/tmp/outside.log": "file",
"/tmp/outside-dir": "dir",
};
handlers.term_default_shell = () => "/bin/zsh";
handlers.term_available_shells = () => ["/bin/zsh"];
handlers.term_spawn = () => ({ id: ++id, title: "zsh", pid: id });
handlers.term_resize = () => null;
handlers.term_write = () => null;
handlers.term_is_busy = () => false;
handlers.term_kill = () => null;
handlers.fs_entry_kind = (args) => {
const p = String(args.path ?? "");
if (p in entries) return entries[p];
throw { kind: "notFound", message: `No such entry: ${p}` };
};
handlers.fs_read_dir = (args) => {
if (args.path === "/dev/acme-api/src") {
return [{ name: "main.ts", path: "/dev/acme-api/src/main.ts", kind: "file", ignored: false }];
}
return [];
};
handlers.find_files = () => [];
handlers["plugin:opener|reveal_item_in_dir"] = (args) => {
revealed.push(args.paths as string[]);
return null;
};
const store = "/src/workbench/toolwindows/store.ts";
const layout = await import(store);
layout.hideToolWindow("project");
layout.setToolWindowSize("bottom", 240);
layout.showToolWindow("terminal", true);
});
const terminal = page.getByRole("region", { name: "Terminal", exact: true });
await expect(terminal.locator(".xterm-helper-textarea")).toBeFocused();
// Row 0 has all 6 cases: in-project file, non-existent file, in-project dir, non-existent dir,
// out-of-project file, out-of-project dir, and non-existent out-of-project dir.
const line = "App.tsx missing.ts src no_dir/ /tmp/outside.log /tmp/outside-dir /tmp/nope";
await page.evaluate(async (text) => {
const store = "/src/features/terminal/store.ts";
const rt = await import(store);
const s = rt.getSession(rt.useTerminals.getState().tabs[0]!.session)!;
s.term.reset();
await new Promise<void>((done) => s.term.write(`${text}\r\n`, done));
}, line);
const screen = terminal.locator(".xterm-screen");
const pointFor = async (token: string) => {
const startCol = line.indexOf(token);
const box = (await screen.boundingBox())!;
const dims = await page.evaluate(async () => {
const store = "/src/features/terminal/store.ts";
const rt = await import(store);
const { term } = rt.getSession(rt.useTerminals.getState().tabs[0]!.session)!;
return { cols: term.cols, rows: term.rows };
});
return {
x: box.x + ((startCol + Math.min(2, token.length / 2)) / dims.cols) * box.width,
y: box.y + (0.5 / dims.rows) * box.height,
};
};
const pathLink = terminal.locator(".openidea-terminal-path-link");
const editorTabs = page.getByRole("tablist", { name: "Editor tabs" });
// 1) Hover & click `App.tsx` WITHOUT ⌘: no link decoration and no editor tab opens.
const appPt = await pointFor("App.tsx");
await page.mouse.move(appPt.x, appPt.y);
await expect(pathLink).toHaveCount(0);
await page.mouse.click(appPt.x, appPt.y);
await expect(editorTabs).toHaveCount(0);
// 2) Press ⌘ while already hovering `App.tsx`: becomes a hyperlink; ⌘+click opens `App.tsx` in editor!
await page.keyboard.down("Meta");
await expect(pathLink).toHaveCount(1);
if (process.env.OPENIDEA_TERMINAL_SHOTS)
await page.screenshot({
path: `${process.env.OPENIDEA_TERMINAL_SHOTS}/pr3-hover-file.png`,
animations: "disabled",
});
await page.mouse.click(appPt.x, appPt.y);
await page.keyboard.up("Meta");
await expect(editorTabs.getByRole("tab", { name: "App.tsx", selected: true })).toBeVisible();
// 3) Non-existent targets (`missing.ts`, `no_dir/`, `/tmp/nope`) do NOT turn into links on ⌘+hover or ⌘+click.
for (const absent of ["missing.ts", "no_dir/", "/tmp/nope"]) {
const pt = await pointFor(absent);
await page.keyboard.down("Meta");
await page.mouse.move(pt.x, pt.y);
await expect(pathLink).toHaveCount(0);
await page.mouse.click(pt.x, pt.y);
await page.keyboard.up("Meta");
}
await expect(editorTabs.getByRole("tab")).toHaveText(["App.tsx"]);
// 4) Out-of-project existing file (`/tmp/outside.log`) opens in an editor tab of the current window.
const outFilePt = await pointFor("/tmp/outside.log");
await page.keyboard.down("Meta");
await page.mouse.move(outFilePt.x, outFilePt.y);
await expect(pathLink).toHaveCount(1);
await page.mouse.click(outFilePt.x, outFilePt.y);
await page.keyboard.up("Meta");
await expect(editorTabs.getByRole("tab", { name: "outside.log", selected: true })).toBeVisible();
// 5) In-project folder (`src`) opens the Project tool window on the left, expands `src`, and selects it.
const projectRegion = page.getByRole("region", { name: "Project", exact: true });
await expect(projectRegion).toBeHidden();
const srcPt = await pointFor("src");
await page.keyboard.down("Meta");
await page.mouse.move(srcPt.x, srcPt.y);
await expect(pathLink).toHaveCount(1);
if (process.env.OPENIDEA_TERMINAL_SHOTS)
await page.screenshot({
path: `${process.env.OPENIDEA_TERMINAL_SHOTS}/pr3-hover-folder.png`,
animations: "disabled",
});
await page.mouse.click(srcPt.x, srcPt.y);
await page.keyboard.up("Meta");
await expect(projectRegion).toBeVisible();
const srcItem = projectRegion.getByRole("treeitem", { name: "src", exact: true });
await expect(srcItem).toHaveAttribute("aria-expanded", "true");
await expect(srcItem).toHaveAttribute("aria-selected", "true");
await expect(projectRegion.getByRole("treeitem", { name: "main.ts", exact: true })).toBeVisible();
if (process.env.OPENIDEA_TERMINAL_SHOTS)
await page.screenshot({
path: `${process.env.OPENIDEA_TERMINAL_SHOTS}/pr3-opened-folder.png`,
animations: "disabled",
});
// 6) Out-of-project folder (`/tmp/outside-dir`) reveals in Finder instead of changing Project selection.
const outDirPt = await pointFor("/tmp/outside-dir");
await page.keyboard.down("Meta");
await page.mouse.move(outDirPt.x, outDirPt.y);
await expect(pathLink).toHaveCount(1);
await page.mouse.click(outDirPt.x, outDirPt.y);
await page.keyboard.up("Meta");
await expect
.poll(() => page.evaluate(() => (window as unknown as { __revealedInFinder: string[][] }).__revealedInFinder))
.toEqual([["/tmp/outside-dir"]]);
});
+1 -67
View File
@@ -180,11 +180,6 @@ pub const DYNAMIC_LAYOUTS: &str = "toolWindowLayouts";
pub const DYNAMIC_STATUS_BAR_WIDGETS: &str = "statusBarWidgets";
/// Tools › entries of plugins (`[[contributes.menus]] menu = "tools"`).
pub const DYNAMIC_PLUGIN_TOOLS: &str = "pluginTools";
/// Build › Flutter: the Flutter build actions, filled only in Flutter projects. Shown as a submenu
/// first in Build (the Flutter plugin's anchor) when it has items, nothing otherwise.
pub const DYNAMIC_FLUTTER_BUILD: &str = "flutterBuild";
/// Id (and `menu.` label key) of the Build › Flutter submenu.
const FLUTTER_BUILD_MENU: &str = "build.flutter";
/// The menu bar for `os`. Labels are English defaults; the frontend replaces
/// them with `menu.<id>` strings from the active locale catalog.
@@ -620,7 +615,6 @@ pub fn spec(os: Os) -> Vec<Entry> {
"build",
"Build",
vec![
Entry::Dynamic(DYNAMIC_FLUTTER_BUILD),
act("build.buildProject", "Build Project"),
act("build.buildModule", "Build Module"),
act("build.compileFile", "Recompile"),
@@ -1296,18 +1290,6 @@ fn render_items(entries: &[Entry], config: &MenuConfig, recent: &[RecentItem]) -
}
}));
}
Entry::Dynamic(DYNAMIC_FLUTTER_BUILD) => {
let items = config.dynamic_items(DYNAMIC_FLUTTER_BUILD);
if !items.is_empty() {
out.push(RenderedItem::Submenu {
id: FLUTTER_BUILD_MENU.into(),
title: config.label(FLUTTER_BUILD_MENU, "Flutter"),
current: false,
items: items.iter().map(|item| item.render(config)).collect(),
});
out.push(RenderedItem::Separator);
}
}
Entry::Dynamic(slot) => out.extend(config.dynamic_items(slot).iter().map(|item| item.render(config))),
Entry::Native(kind) => {
out.push(RenderedItem::Native { kind: *kind, text: config.label(kind.key(), kind.default_label()) })
@@ -1650,18 +1632,6 @@ pub fn model(spec: &[Entry], recent: &[RecentItem], config: &MenuConfig) -> Vec<
}
}));
}
Entry::Dynamic(DYNAMIC_FLUTTER_BUILD) => {
let items = config.dynamic_items(DYNAMIC_FLUTTER_BUILD);
if !items.is_empty() {
out.push(MenuNode::Submenu {
id: FLUTTER_BUILD_MENU.into(),
label: "Flutter".into(),
current: None,
children: items.iter().map(DynamicItem::model).collect(),
});
out.push(MenuNode::Separator);
}
}
Entry::Dynamic(slot) => out.extend(config.dynamic_items(slot).iter().map(DynamicItem::model)),
Entry::Action { id, label, hint, .. } => out.push(MenuNode::Action {
id: (*id).into(),
@@ -2415,13 +2385,7 @@ mod tests {
slots(&spec, &mut found);
assert_eq!(
found,
[
DYNAMIC_TOOL_WINDOWS,
DYNAMIC_STATUS_BAR_WIDGETS,
DYNAMIC_FLUTTER_BUILD,
DYNAMIC_PLUGIN_TOOLS,
DYNAMIC_LAYOUTS
],
[DYNAMIC_TOOL_WINDOWS, DYNAMIC_STATUS_BAR_WIDGETS, DYNAMIC_PLUGIN_TOOLS, DYNAMIC_LAYOUTS],
"{os:?}"
);
assert!(!action_ids(&spec).iter().any(|id| {
@@ -2578,36 +2542,6 @@ mod tests {
}
}
#[test]
fn flutter_build_submenu_leads_build_only_when_filled() {
let build_items = |config: &MenuConfig| {
render_bar(&spec(Os::Mac), config, &[]).into_iter().find(|m| m.id == "build").expect("Build menu").items
};
let mut config = MenuConfig::default();
assert!(matches!(&build_items(&config)[0], RenderedItem::Action { id, .. } if id == "build.buildProject"));
config.labels.insert("menu.build.flutter".into(), "Flutter".into());
config.dynamic.insert(
DYNAMIC_FLUTTER_BUILD.into(),
vec![
dynamic_item("flutter.build.apk", None, "Build APK"),
dynamic_item("flutter.build.web", None, "Build Web"),
],
);
let items = build_items(&config);
let RenderedItem::Submenu { id, title, items: flutter, .. } = &items[0] else { panic!("no Flutter submenu") };
assert_eq!((id.as_str(), title.as_str(), flutter.len()), ("build.flutter", "Flutter", 2));
assert!(matches!(items[1], RenderedItem::Separator));
let model = model(&spec(Os::Mac), &[], &config);
let build = model.iter().find_map(|n| match n {
MenuNode::Submenu { id, children, .. } if id == "build" => Some(children),
_ => None,
});
assert!(
matches!(&build.unwrap()[0], MenuNode::Submenu { id, children, .. } if id == "build.flutter" && children.len() == 2)
);
}
#[test]
fn build_menu_lists_recompile_and_patches_its_label() {
for os in ALL_OS {
+3 -19
View File
@@ -464,10 +464,7 @@ export const commands = {
debugJvmMemoryInstances: (session: DebugSessionId, className: string, limit: number) => typedError<JvmInstancesResult, IdeError>(__TAURI_INVOKE("debug_jvm_memory_instances", { session, className, limit })),
/** The objects that hold a reference to `object`; `limit` 0 selects the default. */
debugJvmMemoryReferrers: (session: DebugSessionId, object: JvmObjectRef, limit: number) => typedError<JvmReferrersResult, IdeError>(__TAURI_INVOKE("debug_jvm_memory_referrers", { session, object, limit })),
/**
* A `Thread.print -l` of the debuggee JVM (with the JSON dump on JDK 21+), or why it cannot be
* taken.
*/
/** A `Thread.print -l` of the debuggee JVM, or why it cannot be taken. */
debugJvmThreadDump: (session: DebugSessionId) => typedError<JvmThreadsResult, IdeError>(__TAURI_INVOKE("debug_jvm_thread_dump", { session })),
/**
* Remote JVM Debug in listen mode: waits (cancellable through `request`) for the remote
@@ -850,10 +847,8 @@ export const commands = {
* Builds according to `policy`, then resolves the runtime (or test)
* classpath and the JDK of the module at `module` (absolute, or relative to the project root).
* A module with Kotlin / Groovy / Scala sources is built by its build system, whose class directories come first.
* The build streams its console, messages and progress on `on_event` while it runs; a launch
* whose build another launch's build joins receives that build's events.
*/
javaResolveLaunch: (module: string, test: boolean, policy: BuildPolicy, request: RequestId, onEvent: Channel<BuildEvent>) => typedError<JavaLaunchInfo, IdeError>(__TAURI_INVOKE("java_resolve_launch", { module, test, policy, request, onEvent })),
javaResolveLaunch: (module: string, test: boolean, policy: BuildPolicy, request: RequestId) => typedError<JavaLaunchInfo, IdeError>(__TAURI_INVOKE("java_resolve_launch", { module, test, policy, request })),
/**
* Downloads the latest `vendor` JDK of Java `version` into `location` (default:
* [`jdk_download_location`]), streaming progress through `on_event`; cancellable
@@ -7254,7 +7249,7 @@ export type FocusedEditor = {
selectedText: string,
};
export type FoldKind = "region" | "comment" | "imports" | "compact";
export type FoldKind = "region" | "comment" | "imports";
export type FoldRange = {
start_line: number,
@@ -7271,7 +7266,6 @@ export type FoldingSettings = {
fileHeader?: boolean,
imports?: boolean,
docComments?: boolean,
goShortBlocks?: boolean,
};
/**
@@ -8882,10 +8876,6 @@ export type JvmThreadDump = {
takenWhileSuspended: boolean,
/** Wall time of the `Thread.print` request. */
elapsedMs: number,
/** `Thread.dump_to_file -format=json`, which also lists virtual threads; JDK 21+ only. */
virtualJson: string | null,
/** Why `virtual_json` is missing from a JDK 21+ dump; none below 21. */
virtualNote: VirtualThreadsNote | null,
};
export type JvmThreadsResult = { status: "ready"; dump: JvmThreadDump } | { status: "unavailable"; reason: JvmThreadsUnavailable };
@@ -14280,12 +14270,6 @@ export type VirtualDocument = {
canReloadEncoding: boolean,
};
export type VirtualThreadsNote =
/** A debugger holds the VM, which would hang the JSON request until it resumes. */
"whileSuspended" |
/** Over the attach reply limit (64 MiB). */
"tooLarge" | "failed";
/** Declared (or conventional) visibility of an outline symbol. */
export type Visibility = "public" | "protected" |
/** Package / module / assembly scope (Java default, `internal`, `pub(crate)`, Go unexported). */
+1 -1
View File
@@ -1446,7 +1446,7 @@ export function registerEditorActions(): () => void {
keyWhen: "editorFocus || !toolWindowFocus",
run: () => {
const p = ctrl.activePath();
if (p) copyEditorPath(pathToCopy("absolute", p) ?? p);
if (p) copyEditorPath(p);
},
},
{
+1 -13
View File
@@ -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 { searchPanelOpen, setSearchQuery } from "@codemirror/search";
import { setSearchQuery } from "@codemirror/search";
import { StreamLanguage } from "@codemirror/language";
import { literalKindAt } from "./literals";
import { selectionMarks } from "./selectionMarks";
@@ -116,18 +116,6 @@ 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.
+3 -10
View File
@@ -359,15 +359,8 @@ 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 {
if (view.state.field(findScope, false)) return step(view, true);
return usableQuery(view) && cmFindNext(view);
return view.state.field(findScope, false) ? step(view, true) : cmFindNext(view);
}
/** The last match in `from`–`to` other than `skip`. */
@@ -473,7 +466,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 usableQuery(view) && cmReplaceNext(view);
if (!state.field(findScope, false) && !preserve) return cmReplaceNext(view);
if (state.readOnly) return false;
const query = getSearchQuery(state);
const ms = matchesIn(state);
@@ -494,7 +487,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 usableQuery(view) && cmReplaceAll(view);
if (!state.field(findScope, false) && !preserve) return cmReplaceAll(view);
if (state.readOnly) return false;
const query = getSearchQuery(state);
const changes = matchesIn(state).map((m) => ({
+1 -82
View File
@@ -1,12 +1,11 @@
import { describe, expect, it } from "vitest";
import { EditorState } from "@codemirror/state";
import { codeFolding, foldEffect, foldService, foldable, foldedRanges, syntaxTree } from "@codemirror/language";
import { codeFolding, foldEffect, foldService, foldable, foldedRanges } from "@codemirror/language";
import { EditorView } from "@codemirror/view";
import { javascript } from "@codemirror/lang-javascript";
import {
backendFoldingChanged,
backendFolds,
compactFoldFits,
enclosingFoldRange,
expandToLevelEffects,
foldChipWidth,
@@ -17,7 +16,6 @@ import {
foldToExpand,
setBackendFolds,
} from "./folding";
import { findLanguageDescription, loadSupport } from "./languages";
/** Folds `{ … }` blocks whose header line ends with `{`. */
const braces = foldService.of((state, from, to) => {
@@ -101,85 +99,6 @@ describe("foldsFromRanges", () => {
view.destroy();
});
it("shows Go statements with their source highlighting and expands them on click or edit", async () => {
const support = await loadSupport(findLanguageDescription("Go", "/p/main.go")!);
const doc = [
"package main",
"func print(mode string) error {",
" switch mode {",
' case "go":',
' fmt.Println("ready")',
" }",
' if mode == "" {',
' return fmt.Errorf("missing")',
" }",
" return nil",
"}",
].join("\n");
const view = new EditorView({ doc, extensions: [support!, foldingExtension(true)], parent: document.body });
try {
view.dispatch({
effects: setBackendFolds.of([
{ start_line: 3, end_line: 4, kind: "compact" },
{ start_line: 6, end_line: 8, kind: "compact" },
]),
});
const [singleCase, guard] = view.state.field(backendFolds);
expect(compactFoldFits(view.state, singleCase!, 40)).toBe(true);
expect(compactFoldFits(view.state, guard!, 40)).toBe(false);
view.dispatch({ effects: [foldEffect.of(singleCase!), foldEffect.of(guard!)] });
const chips = view.dom.querySelectorAll<HTMLElement>(".cm-foldCompact");
expect([...chips].map((chip) => chip.parentElement?.textContent)).toEqual([
' case "go": fmt.Println("ready")',
' if mode == "" { return fmt.Errorf("missing") }',
]);
expect([...chips[1]!.querySelectorAll("span")].map((span) => span.textContent)).toContain("return");
expect([...chips[0]!.querySelectorAll("span")].map((span) => span.textContent)).toContain("Println");
expect(view.state.doc.toString()).toBe(doc);
chips[0]!.click();
const body = view.state.doc.line(8);
view.dispatch({ changes: { from: body.from, to: body.to, insert: " return nil" } });
expect(view.dom.querySelectorAll(".cm-foldCompact")).toHaveLength(0);
expect(view.dom.textContent).toContain("return nil");
} finally {
view.destroy();
}
});
it("highlights a compact Go statement beyond the initial syntax tree", async () => {
expect.assertions(3);
const support = await loadSupport(findLanguageDescription("Go", "/p/main.go")!);
const prefix = ["package main", ...Array.from({ length: 200 }, (_, i) => `var example${i} = "filler"`)];
let state = EditorState.create({
doc: [
...prefix,
"func example() error {",
" if err != nil {",
" return err",
" }",
" return nil",
"}",
].join("\n"),
extensions: [support!, foldingExtension(true)],
});
state = state.update({
effects: setBackendFolds.of([{ start_line: prefix.length + 1, end_line: prefix.length + 3, kind: "compact" }]),
}).state;
const [fold] = state.field(backendFolds);
expect(syntaxTree(state).length).toBeLessThan(fold!.from);
state = state.update({ effects: foldEffect.of(fold!) }).state;
const view = new EditorView({ state });
try {
foldedRanges(state).between(fold!.from, fold!.to, (_from, _to, decoration) => {
const chip = decoration.spec.widget.toDOM(view);
expect(chip.textContent).toBe(" return err ");
expect(chip.querySelector("span")?.textContent).toBe("return");
});
} finally {
view.destroy();
}
});
it("starts an Allman block's fold on its declaration line", () => {
const s = EditorState.create({ doc: "namespace Demo\n{\n class A\n {\n }\n}\n" });
const folds = foldsFromRanges(s, [fold(1, 5), fold(3, 4)]);
+4 -74
View File
@@ -4,13 +4,11 @@
* chevrons in the gutter (open chevrons can be shown only on hover).
*/
import {
countColumn,
EditorSelection,
EditorState,
Prec,
StateEffect,
StateField,
Text,
type EditorState,
type Extension,
type Line,
} from "@codemirror/state";
@@ -22,8 +20,6 @@ import {
foldService,
foldable,
foldedRanges,
language,
syntaxTree,
unfoldEffect,
} from "@codemirror/language";
import type { FoldRange } from "@/platform/ipc";
@@ -32,7 +28,6 @@ import { tx } from "@/platform/i18n";
import { enclosingCodeBlock } from "./caretCommands";
import { foldPreviewExtension } from "./foldPreview";
import { regionMarkerAt, regionNameAt } from "./regions";
import { renderSyntaxRange } from "./renderLineContent";
export interface BackendFold {
/** Offset where the fold starts (end of the header line). */
@@ -136,35 +131,12 @@ export function foldsFromRanges(state: EditorState, ranges: readonly FoldRange[]
// `}` / `)` / `]` on the last line stays visible after the placeholder, like IDEA. An import
// run ending in `} from '…'` hides that whole statement; a bare `)` / `};` still shows.
const delimiter = r.kind === "imports" ? /^[}\])]+[;,]?$/.test(trimmed.trimEnd()) : /^[}\])]/.test(trimmed);
if (r.kind === "compact" && r.end_line === r.start_line + 1) {
out.push({ from, to: end.to, kind: r.kind });
continue;
}
const to = delimiter ? end.from + (end.text.length - trimmed.length) : end.to;
if (to > from) out.push({ from, to, kind: r.kind });
}
return out.sort((a, b) => a.from - b.from || b.to - a.to);
}
function compactBody(state: EditorState, range: { from: number; to: number }) {
const header = state.doc.lineAt(range.from);
const end = state.doc.lineAt(range.to);
const braced = end.number === header.number + 2;
if (range.from !== header.to || (end.number !== header.number + 1 && !braced)) return null;
const body = state.doc.line(header.number + 1);
const source = body.text.trim();
if (!source) return null;
const from = body.from + body.text.length - body.text.trimStart().length;
return { from, to: from + source.length, source, header, end, braced };
}
export function compactFoldFits(state: EditorState, range: BackendFold, margin: number): boolean {
const body = compactBody(state, range);
if (!body) return false;
const tail = body.braced ? ` ${body.end.text.trimStart()}` : "";
return countColumn(`${body.header.text} ${body.source}${tail}`, state.tabSize) <= margin;
}
export const backendFolds = StateField.define<BackendFold[]>({
create: () => [],
update(folds, tr) {
@@ -542,48 +514,11 @@ export function foldingExtension(showOutline = true, visibility: FoldingOutlineV
backendFolds,
backendFoldService,
foldPreviewExtension,
// Recreate the preview by expanding a folded statement if its source is changed.
// Edits above it simply move CodeMirror's fold and keep the preview intact.
EditorState.transactionFilter.of((tr) => {
if (!tr.docChanged) return tr;
const state = tr.startState;
const effects: StateEffect<unknown>[] = [];
tr.changes.iterChangedRanges((fromA, toA) => {
foldedRanges(state).between(fromA, toA, (from, to) => {
const header = state.doc.lineAt(from);
const fold = foldAtLine(state.field(backendFolds), header.from, header.to);
if (fold?.kind !== "compact" || fold.from !== from || fold.to !== to) return;
effects.push(unfoldEffect.of({ from: tr.changes.mapPos(from, 1), to: tr.changes.mapPos(to, -1) }));
});
});
return effects.length ? [tr, { effects, sequential: true }] : tr;
}),
codeFolding({
// A folded custom region shows its name, as in IDEA.
preparePlaceholder: (state, range) => {
const name = regionNameAt(state, range.from);
if (name) return name;
const header = state.doc.lineAt(range.from);
const fold = foldAtLine(state.field(backendFolds), header.from, header.to);
if (fold?.kind === "compact" && fold.from === range.from && fold.to === range.to) {
const body = compactBody(state, range);
if (body) {
const content = document.createDocumentFragment();
content.append(" ");
const tree = syntaxTree(state);
const parser = state.facet(language)?.parser;
if (parser && tree.length < body.to) {
// The initial parse may stop before this fold. Only parse the statement.
const snippet = Text.of(["package main", "func _() {", body.source, "}"]);
const line = snippet.line(3);
renderSyntaxRange(snippet, parser.parse(snippet.toString()), line.from, line.to, content);
} else {
renderSyntaxRange(state.doc, tree, body.from, body.to, content);
}
if (body.braced) content.append(" ");
return content;
}
}
const doc = commentPlaceholderFold(state, state.doc.lineAt(range.from), state.doc.lineAt(range.to));
if (!doc || range.from < doc.from || range.to > doc.to) return null;
const before = state.doc.sliceString(doc.from, range.from);
@@ -592,16 +527,11 @@ export function foldingExtension(showOutline = true, visibility: FoldingOutlineV
? doc.text.slice(before.length, doc.text.length - after.length)
: null;
},
placeholderDOM: (view, onclick, placeholder: string | DocumentFragment | null) => {
placeholderDOM: (view, onclick, name: string | null) => {
const el = document.createElement("span");
el.className = "cm-foldPlaceholder";
if (placeholder instanceof DocumentFragment) {
el.classList.add("cm-foldCompact");
el.append(placeholder.cloneNode(true));
} else {
el.textContent = placeholder ?? "…";
el.setAttribute("aria-label", tx("Folded code"));
}
el.textContent = name ?? "…";
el.setAttribute("aria-label", tx("Folded code"));
// The chip is a button, not a text anchor. Letting the mousedown through
// starts a mouse selection that moves the caret to the chip's line; a caret
// change re-runs the inline blame refresh, which replaces this line's DOM
-44
View File
@@ -566,50 +566,6 @@ describe("language modes", () => {
expect(keywords(support!.language, "switch x {\ncase 1:\ndefault:\n}")).toEqual(["switch", "case", "default"]);
});
it("distinguishes Go packages, methods, fields and builtins without gopls", async () => {
const support = await loadSupport(findLanguageDescription("Go", "/p/main.go")!);
const source = [
"package main",
'import clock "time"',
"const Size = 1",
"func (c Config) Demo(d clock.Duration) {",
" clock.Sleep(d)",
" c.Show(c.Name)",
" _ = make([]int, Size)",
" _ = new([]int)",
"}",
].join("\n");
const highlighter = tagHighlighter([
{ tag: t.namespace, class: "namespace" },
{ tag: t.typeName, class: "type" },
{ tag: t.function(t.propertyName), class: "call" },
{ tag: t.function(t.definition(t.variableName)), class: "declaration" },
{ tag: t.propertyName, class: "field" },
{ tag: t.constant(t.variableName), class: "constant" },
{ tag: t.standard(t.function(t.variableName)), class: "builtin" },
]);
const found: Array<[string, string]> = [];
highlightTree(support!.language.parser.parse(source), highlighter, (from, to, classes) => {
found.push([source.slice(from, to), classes]);
});
expect(found).toEqual([
["main", "namespace"],
["clock", "namespace"],
["Size", "constant"],
["Config", "type"],
["Demo", "declaration"],
["clock", "namespace"],
["Duration", "type"],
["Sleep", "call"],
["Show", "call"],
["Name", "field"],
["make", "builtin"],
["int", "type"],
["new", "builtin"],
["int", "type"],
]);
});
it("colours TOML keys as keywords in files, lock files and ```toml code blocks", async () => {
await Promise.all(
["/p/Cargo.toml", "/p/uv.lock"].map(async (path) => {
+2 -8
View File
@@ -510,14 +510,8 @@ export const JAVA_TAGS: Parameters<typeof styleTags>[0] = {
Label: t.variableName,
};
const GO_TAGS: Parameters<typeof styleTags>[0] = {
default: t.controlKeyword,
"PackageClause/DefName ImportSpec/DefName QualifiedType/VariableName": t.namespace,
"MethodDecl/FieldName MethodElem/FieldName": t.function(t.definition(t.variableName)),
"CallExpr/SelectorExpr/FieldName": t.function(t.propertyName),
"ConstSpec/DefName": t.constant(t.variableName),
"make new": t.standard(t.function(t.variableName)),
};
// @lezer/go leaves `default` uncoloured, unlike `case` and `switch`.
const GO_TAGS: Parameters<typeof styleTags>[0] = { default: t.controlKeyword };
/** Highlighting the stock grammars lack or colour unlike IntelliJ. */
const EXTRA_TAGS: Record<string, Parameters<typeof styleTags>[0]> = {
+7 -25
View File
@@ -1,6 +1,5 @@
import type { EditorState, Text } from "@codemirror/state";
import { type EditorState } from "@codemirror/state";
import { syntaxTree } from "@codemirror/language";
import type { Tree } from "@lezer/common";
import { highlightTree } from "@lezer/highlight";
import { openideaHighlightStyle } from "./highlight";
import { bracketClass, DEFAULT_BRACKET_COLORS, type BracketMark } from "./rainbowBrackets";
@@ -21,30 +20,13 @@ export function renderLineContent(
colors = DEFAULT_BRACKET_COLORS,
) {
const line = state.doc.line(lineNo);
renderSyntaxRange(
state.doc,
syntaxTree(state),
line.from,
Math.min(line.to, line.from + MAX_PREVIEW_LINE_LENGTH),
target,
brackets,
colors,
);
}
export function renderSyntaxRange(
doc: Text,
tree: Tree,
start: number,
end: number,
target: ParentNode,
brackets: readonly BracketMark[] = [],
colors = DEFAULT_BRACKET_COLORS,
) {
let pos = start;
const text = line.text.slice(0, MAX_PREVIEW_LINE_LENGTH);
const end = line.from + text.length;
const tree = syntaxTree(state);
let pos = line.from;
let next = 0;
const node = (to: number, cls: string): Node => {
const s = doc.sliceString(pos, to);
const s = state.doc.sliceString(pos, to);
pos = to;
if (!cls) return document.createTextNode(s);
const span = document.createElement("span");
@@ -75,7 +57,7 @@ export function renderSyntaxRange(
push(Math.max(from, pos), "");
push(Math.min(to, end), cls);
},
start,
line.from,
end,
);
}
-1
View File
@@ -320,7 +320,6 @@ export const openideaTheme = EditorView.theme({
margin: "0 2px",
cursor: "pointer",
},
".cm-foldPlaceholder.cm-foldCompact": { color: "var(--fg-editor)", padding: "0", margin: "0" },
".cm-foldPlaceholder:hover": { backgroundColor: "color-mix(in srgb, var(--fg-muted) 24%, transparent)" },
// Indent guides (cm/indentGuides.ts): one 1px strip per guide, positioned per guide.
+1 -50
View File
@@ -1,7 +1,7 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { ChangeSet, EditorState, StateEffect } from "@codemirror/state";
import { showTooltip, type Tooltip } from "@codemirror/view";
import { foldedRanges, indentUnit, language as languageFacet } from "@codemirror/language";
import { indentUnit, language as languageFacet } from "@codemirror/language";
import { HEAVY_LIMIT, onEditorEvent, registerSaveParticipant, remoteChange, shownAgain } from "@/editor/api";
import { createMemoryBackend, type MemoryBackend } from "../backend";
import { _resetLanguages } from "../cm/languages";
@@ -85,55 +85,6 @@ describe("DocumentManager + slots", () => {
}
});
it.each([
["opening the file", {}, 0, false, [3, 9]],
["opening a file that was already loaded", {}, 0, true, [3, 9]],
["jumping into a short block", {}, 4, false, [9]],
["disabling short Go block folding", { goShortBlocks: false }, 0, false, []],
])("applies compact Go folding when %s", async (_reason, folding, caret, loadedFirst, expected) => {
const path = "/p/main.go";
const { backend, manager, frame } = setup(
{
[path]: [
"package main",
"func main() {",
" if ok {",
" return",
" }",
` if ${"longCondition".repeat(12)} {`,
" return",
" }",
" if done {",
" return",
" }",
"}",
].join("\n"),
},
{ editor: { folding } },
);
vi.spyOn(backend, "folding").mockResolvedValue([
{ start_line: 2, end_line: 4, kind: "compact" },
{ start_line: 5, end_line: 7, kind: "compact" },
{ start_line: 8, end_line: 10, kind: "compact" },
]);
try {
const model = await manager.acquire(path);
if (loadedFirst) await frame();
const slot = new EditorSlot(model, "go", host);
if (caret) slot.dispatchLocal({ selection: { anchor: slot.state.doc.line(caret).from } });
await vi.waitFor(() => {
const lines: number[] = [];
foldedRanges(slot.state).between(0, slot.state.doc.length, (from) => {
lines.push(slot.state.doc.lineAt(from).number);
});
expect(lines).toEqual(expected);
});
slot.dispose();
} finally {
manager.stop();
}
});
it("requests Kotlin declaration highlights while retaining its CodeMirror language", async () => {
const { backend, manager, frame } = setup({ "/p/Palette.kt": "class Greeter { fun greet() {} }" });
const highlights = vi.spyOn(backend, "highlights").mockResolvedValue({ kinds: ["function"], data: [20, 25, 0] });
+6 -20
View File
@@ -39,7 +39,7 @@ import {
uiModeForPath,
} from "../cm/languages";
import { foldEffect } from "@codemirror/language";
import { backendFolds, compactFoldFits, setBackendFolds } from "../cm/folding";
import { backendFolds, setBackendFolds } from "../cm/folding";
import { setSyntaxHighlights } from "../cm/syntaxHighlight";
import {
caretFor,
@@ -49,7 +49,6 @@ import {
effectiveIndent,
foldingFor,
fontExtension,
hardWrapAt,
heavyExtension,
indentExtension,
lineNumbersExtension,
@@ -390,8 +389,6 @@ export class DocModel {
addSlot(slot: EditorSlot) {
this.slots.add(slot);
// An attachment can load and refresh the document before its first editor opens.
if (this.meta.language === "go" && this.slots.size === 1 && !this.initialFolds) this.scheduleRefresh(0);
if (this.highlights?.counter === this.changeCounter)
slot.reconfigure([setSyntaxHighlights.of(this.highlights.value)]);
}
@@ -640,8 +637,6 @@ export class DocModel {
backend.folding(this.doc),
backend.outline(this.doc),
!this.desc || GRAMMAR_SUPPLEMENTED.has(this.meta.language) ? backend.highlights(this.doc) : null,
// Compact folds render the original statement with the Go syntax mode.
this.meta.language === "go" && !this.initialFolds ? this.loadLanguage() : null,
]);
if (this.closed) return;
if (counter !== this.changeCounter) {
@@ -650,7 +645,7 @@ export class DocModel {
}
if (folds.status === "fulfilled") {
for (const s of this.slots) s.reconfigure([setBackendFolds.of(folds.value)]);
if (!this.initialFolds && this.slots.size) {
if (!this.initialFolds) {
this.initialFolds = true;
this.foldByDefault();
}
@@ -666,18 +661,14 @@ export class DocModel {
}
}
/** Code Folding › "Fold by default". */
/** Code Folding › "Fold by default": file header, imports, documentation comments. */
private foldByDefault() {
const settings = this.settings();
const f = prefsOf(settings).folding;
if (!f.fileHeader && !f.imports && !f.docComments && !f.goShortBlocks) return;
const margin = hardWrapAt(settings, this.info);
const f = prefsOf(this.settings()).folding;
if (!f.fileHeader && !f.imports && !f.docComments) return;
for (const s of this.slots) {
const state = s.currentState();
const folds = state.field(backendFolds, false) ?? [];
if (!folds.length) continue;
const info = this.info;
const head = state.selection.main.head;
const firstCodeLine = (() => {
for (let n = 1; n <= state.doc.lines; n++) {
const t = state.doc.line(n).text.trim();
@@ -687,12 +678,6 @@ export class DocModel {
})();
const chosen = folds.filter((r) => {
if (r.kind === "imports") return f.imports;
if (r.kind === "compact")
return (
f.goShortBlocks &&
!state.selection.ranges.some(({ from, to }) => r.from < to && from < r.to) &&
compactFoldFits(state, r, margin)
);
if (r.kind !== "comment") return false;
// A file header must sit at the top AND start with a comment token.
// Keeping the position check keeps ordinary doc comments further down
@@ -705,6 +690,7 @@ export class DocModel {
const effects: StateEffect<unknown>[] = chosen.map((r) => foldEffect.of({ from: r.from, to: r.to }));
// Folding the header / imports shifts everything below: keep a navigation
// target (caret revealed on open) in view.
const head = state.selection.main.head;
if (effects.length && head > 0 && !chosen.some((r) => r.from < head && head <= r.to))
effects.push(EditorView.scrollIntoView(head, { y: "center" }));
if (effects.length) s.reconfigure(effects);
+12 -119
View File
@@ -8,7 +8,6 @@
import { useCallback, useEffect, useId, useMemo, useState, type ReactNode } from "react";
import type {
AgentConfigOption,
AgentModelCatalog,
AgentProvider,
AgentRegistry,
CustomAgentInput,
@@ -23,9 +22,8 @@ import { Button, Dialog, Icon, IconButton, Input, List, ProgressBar, SearchField
import { useSettingsForm } from "@/workbench/contributions";
import { confirm } from "@/workbench/messages";
import { LocalCliUpdate } from "./LocalCliUpdate";
import { approvalDefaults, cursorModelDefaults, isPerModelOption } from "./composerModel";
import { isPerModelOption } from "./composerModel";
import { providerIcon, slugifyId } from "./model";
import { useAgents } from "./store";
import {
DISTRIBUTION_LABEL,
afterInstall,
@@ -868,7 +866,7 @@ function ProviderSettings({
</Section>
)}
<Section title="New Tasks">
<AgentDefaults agent={agent} backend={backend} />
<AgentDefaults agent={agent} />
</Section>
<Section title="Launch">
<div className={styles.form}>
@@ -1016,117 +1014,29 @@ function ExternalLink({ url, label }: { url: string; label: string }) {
);
}
/** 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,
};
});
/** 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);
const modelOption = base.find((o) => o.category === "model");
const model = (modelOption && chosen[modelOption.id]) || modelOption?.current;
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];
const levels = (model && agent.thoughtLevels?.[model]) || [];
return [...base, ...levels.filter((o) => o.values.length > 1)];
}
const MODEL_SETTINGS_POLL_MS = 600;
function AgentDefaults({ agent, backend }: { agent: AgentProvider; backend: CommandsBackend }) {
function AgentDefaults({ agent }: { agent: AgentProvider }) {
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 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]);
const options = defaultOptions(agent, chosen);
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: 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 next = value ? { ...rest, [id]: value } : rest;
const { [agent.id]: __, ...others } = all;
form.set("agents.defaults", Object.keys(next).length ? { ...others, [agent.id]: next } : others);
};
@@ -1134,26 +1044,14 @@ function AgentDefaults({ agent, backend }: { agent: AgentProvider; backend: Comm
<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={currentChoice}
value={chosen[o.id] ?? ""}
options={[
{ value: "", label: defaultLabel },
...unavailableChoice,
{ value: "", label: fallback ? tx`Agent's default (${fallback})` : tx("Agent's default") },
...o.values.map((v) => ({
value: v.value,
label: v.name,
@@ -1167,11 +1065,6 @@ function AgentDefaults({ agent, backend }: { agent: AgentProvider; backend: Comm
</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>
+2
View File
@@ -119,6 +119,7 @@
background: none;
color: var(--fg-subtle);
--icon-color: currentColor;
cursor: pointer;
transition:
background var(--dur-fast) var(--ease),
color var(--dur-fast) var(--ease);
@@ -175,6 +176,7 @@
background: none;
color: inherit;
font: inherit;
cursor: pointer;
}
.statusItem:hover {
background: var(--bg-hover);
+48 -16
View File
@@ -222,42 +222,31 @@
background: transparent;
color: var(--fg);
font: inherit;
cursor: pointer;
}
.refreshModels:hover:not(:disabled) {
color: var(--fg-strong);
}
.refreshModels:disabled {
color: var(--fg-muted);
cursor: default;
}
.quickSettings {
display: flex;
flex-direction: column;
gap: var(--space-3);
padding: 4px 12px 10px;
}
.quickRow {
display: flex;
flex-direction: column;
}
.quickRow + .quickRow {
margin-top: 6px;
padding-top: 6px;
border-top: 1px solid var(--border);
gap: var(--space-1);
}
.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;
}
@@ -276,6 +265,7 @@
border-radius: var(--radius-small);
background: transparent;
color: var(--fg-muted);
cursor: pointer;
}
.modelRowConfigure:hover,
.modelRowConfigure:focus-visible {
@@ -297,6 +287,45 @@
.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;
cursor: pointer;
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;
@@ -436,6 +465,7 @@
background: var(--bg-popup);
box-shadow: 0 0 0 1px var(--border);
color: var(--fg);
cursor: pointer;
opacity: 0;
}
.image:hover .removeImage,
@@ -471,6 +501,7 @@
outline: 1px dashed var(--border-strong);
outline-offset: -1px;
color: var(--fg-muted);
cursor: pointer;
transition:
color var(--dur-fast) var(--ease),
background var(--dur-fast) var(--ease);
@@ -498,6 +529,7 @@
border-radius: var(--radius-small);
background: none;
color: var(--fg-muted);
cursor: pointer;
}
.removeChip:hover {
background: var(--bg-hover);
+11 -43
View File
@@ -344,15 +344,13 @@ 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("listbox", { name: "Effort Level" });
expect(within(effort).getByRole("option", { name: "medium" })).toHaveAttribute("aria-selected", "true");
fireEvent.click(within(effort).getByRole("option", { name: "XHigh" }));
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" }));
expect(onChange).toHaveBeenCalledExactlyOnceWith("reasoning_effort", "xhigh");
// The only setting: choosing it closes the popup.
expect(screen.queryByRole("dialog", { name: "Model settings" })).not.toBeInTheDocument();
});
it("renders effort levels consistently as a vertical list regardless of option count", () => {
it("lists more effort levels than fit the segmented control, one click away", () => {
const onChange = vi.fn();
const config = copilotConfig().map((o) =>
o.category === "thought_level"
@@ -368,18 +366,11 @@ 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")).not.toBeInTheDocument();
expect(within(dialog).queryByRole("radiogroup", { name: "Effort Level" })).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");
// 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/ }));
fireEvent.click(within(levels).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();
@@ -451,11 +442,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 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" }));
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" }));
expect(onChange).toHaveBeenCalledExactlyOnceWith("contextTier", "default");
// Several settings: the popup stays for the next one.
expect(screen.getByRole("dialog", { name: "Model settings" })).toBeInTheDocument();
@@ -474,29 +465,6 @@ 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");
+86 -25
View File
@@ -1,7 +1,7 @@
/**
* Model and settings controls shared by the New Task and session composers.
*/
import { useEffect, useRef, useState } from "react";
import { useEffect, useRef, useState, type KeyboardEvent } from "react";
import clsx from "clsx";
import type { AgentConfigOption } from "@/bindings";
import { useTx } from "@/platform/i18n";
@@ -252,6 +252,9 @@ 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"
@@ -399,10 +402,9 @@ function ModelPicker({
}
/**
* 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.
* 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.
*/
function ModelSettings({
settings,
@@ -419,31 +421,35 @@ function ModelSettings({
<div className={styles.quickSettings}>
{settings.map((o) => {
const label = tx(settingName(o));
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;
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();
}}
/>
);
return (
<div key={o.id} className={styles.quickRow}>
<span className={styles.quickLabel} title={o.description ?? undefined}>
{label}
</span>
<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();
}}
/>
{control}
</div>
);
})}
@@ -507,6 +513,61 @@ 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. */
function ModePicker({
mode,
+18 -75
View File
@@ -102,8 +102,9 @@ async function chooseModel(model: string) {
async function chooseEffort(effort: string) {
fireEvent.click(settingsButton());
const list = screen.getByRole("listbox", { name: "Effort Level" });
fireEvent.click(within(list).getByRole("option", { name: effort }));
const group = screen.getByRole("radiogroup", { name: "Effort Level" });
fireEvent.click(within(group).getByRole("radio", { name: effort }));
fireEvent.keyDown(document, { key: "Escape" });
}
it("switches model-specific levels and restores each draft effort before starting", async () => {
@@ -189,79 +190,21 @@ it("ignores old provider-wide effort choices and refreshes unsupported per-model
});
it.each([
[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 formats context concisely.
expect(settingsButton()).toHaveTextContent("high · 256k · Fast: Off");
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" },
]);
[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 });
}
});
it("applies fitWidth on the New Task page only when fitWindowWidth is enabled", () => {
+2 -2
View File
@@ -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, newTaskApprovals } = useAgentSettings();
const { defaults, fitWindowWidth } = useAgentSettings();
const providerDefaults = (provider && defaults[provider.id]) || {};
const config = draftConfig(provider, draft, providerDefaults, newTaskApprovals);
const config = draftConfig(provider, draft, providerDefaults);
const model = config.find((o) => o.category === "model");
const selectedModel = model?.current ?? null;
const selectedModelRef = useRef(selectedModel);
@@ -251,6 +251,7 @@
color: var(--fg-muted);
font: inherit;
font-size: var(--fs-small);
cursor: pointer;
}
.segmentActive {
@@ -277,6 +278,7 @@
color: var(--fg-secondary);
font: inherit;
font-size: var(--fs-small);
cursor: pointer;
}
.agentChip:hover {
+6 -1
View File
@@ -15,7 +15,7 @@
font-size: var(--agent-fs-small, var(--fs-small));
line-height: calc(20px + max(0px, var(--agent-font-zoom, 0px)) * 1.4);
white-space: nowrap;
cursor: default;
cursor: pointer;
user-select: none;
transition:
background var(--dur-fast) var(--ease),
@@ -58,6 +58,7 @@
border-radius: var(--radius-small);
background: none;
color: var(--fg-muted);
cursor: pointer;
}
.chipRemove:hover {
background: var(--bg-hover);
@@ -226,6 +227,7 @@
border-radius: var(--radius-small);
background: none;
color: var(--fg-muted);
cursor: pointer;
}
.codeRemove:hover,
.codeCopy:hover {
@@ -263,6 +265,9 @@
background: var(--bg-hover);
}
/* In the composer: the card opens as text on a click. */
.codeCard[title] {
cursor: pointer;
}
.codeCard[title]:hover {
box-shadow: inset 0 0 0 1px var(--border-strong);
}
+15 -5
View File
@@ -127,6 +127,7 @@
font-size: var(--fs-small);
font-variant-numeric: tabular-nums;
white-space: nowrap;
cursor: pointer;
}
.statusChip:hover {
background: var(--bg-toolbar-hover);
@@ -252,6 +253,7 @@
border-radius: var(--radius-toolbar-button);
background: var(--bg-app);
color: var(--fg-muted);
cursor: pointer;
}
/* Over the stream's text: keep it opaque against the icon button's translucent hover fill. */
.streamArea .jumpToLatest:not(:disabled):hover {
@@ -566,6 +568,7 @@
border-radius: var(--radius-small);
background: var(--bg-elev);
color: var(--fg-secondary);
cursor: pointer;
opacity: 0;
-webkit-user-select: none;
user-select: none;
@@ -744,6 +747,7 @@
background: var(--bg-elev);
color: var(--fg-secondary);
font: inherit;
cursor: pointer;
}
.loadImage:hover {
background: var(--bg-toolbar-hover);
@@ -767,7 +771,7 @@
}
.thought summary,
.toolDetails > summary {
cursor: default;
cursor: pointer;
list-style: none;
}
.thought summary::-webkit-details-marker,
@@ -859,6 +863,7 @@
background: none;
padding: 0 4px;
border-radius: var(--radius-small);
cursor: pointer;
white-space: nowrap;
}
.toolDiff:hover {
@@ -867,7 +872,7 @@
/* Reasoning and tool calls between messages, folded as one block per turn. */
.processRun > summary {
cursor: default;
cursor: pointer;
list-style: none;
}
.processRun > summary::-webkit-details-marker {
@@ -1228,6 +1233,7 @@
background: var(--bg-popup);
box-shadow: 0 0 0 1px var(--border);
color: var(--fg);
cursor: pointer;
}
/* Opaque on hover too: the icon button's own hover fill is translucent over the image. */
.imageItem .removeImage:not(:disabled):hover {
@@ -1378,6 +1384,7 @@
color: var(--fg);
font: inherit;
text-align: left;
cursor: pointer;
}
.subagentOpen:hover {
background: var(--bg-hover);
@@ -1420,7 +1427,7 @@
padding-left: 22px;
color: var(--fg-muted);
font-size: var(--agent-fs-small, var(--fs-small));
cursor: default;
cursor: pointer;
list-style: none;
}
.subagentSection > summary::-webkit-details-marker {
@@ -1517,6 +1524,7 @@
color: var(--fg-secondary);
font: inherit;
font-size: var(--fs-small);
cursor: pointer;
}
.subagentChip:hover {
background: var(--bg-toolbar-hover);
@@ -1766,7 +1774,7 @@
/* A finished turn's work, folded under its message. */
.turnFold > summary {
cursor: default;
cursor: pointer;
list-style: none;
}
.turnFold > summary::-webkit-details-marker {
@@ -1814,6 +1822,7 @@
color: var(--fg-secondary);
font: inherit;
font-size: var(--fs-small);
cursor: pointer;
}
.trayChip:hover,
.trayChip[aria-expanded="true"] {
@@ -1934,6 +1943,7 @@
}
.meterButton {
composes: meter;
cursor: pointer;
color: inherit;
font: inherit;
border: 0;
@@ -1995,7 +2005,7 @@
flex-basis: 0;
}
.contextDetails summary {
cursor: default;
cursor: pointer;
color: var(--fg);
}
.contextDetails ul {
@@ -24,6 +24,7 @@
font-size: var(--fs-small);
font-variant-numeric: tabular-nums;
white-space: nowrap;
cursor: pointer;
transition:
background var(--dur-fast) var(--ease),
border-color var(--dur-fast) var(--ease),
@@ -98,6 +99,7 @@
font: inherit;
font-size: var(--fs-ui);
text-align: left;
cursor: pointer;
}
.rowMain:focus-visible {
@@ -11,6 +11,7 @@
color: var(--fg-secondary);
font: inherit;
white-space: nowrap;
cursor: pointer;
transition: background var(--dur-fast) var(--ease);
}
@@ -194,6 +195,7 @@
color: var(--fg-secondary);
font: inherit;
font-size: var(--fs-tiny);
cursor: pointer;
}
.inlineLink:hover {
@@ -109,6 +109,7 @@
font: inherit;
font-weight: 600;
text-align: left;
cursor: pointer;
}
.chevron {
@@ -189,6 +190,7 @@
color: inherit;
font: inherit;
text-align: left;
cursor: pointer;
}
.cardMain {
@@ -97,6 +97,7 @@
background: var(--bg-elev);
color: var(--fg);
font-size: var(--fs-small);
cursor: pointer;
}
.candidateBtn:hover {
+2 -125
View File
@@ -813,7 +813,7 @@ describe("the agent list", () => {
closeSettings();
dispose();
});
const open = async (commands: FakeCommands, backend = new FakeBackend(), regionName = "Claude Code") => {
const open = async (commands: FakeCommands, backend = new FakeBackend()) => {
dispose = registerSettingsPage({
id: REGISTRY_PAGE,
title: "Agents",
@@ -825,7 +825,7 @@ describe("the agent list", () => {
<MessagesHost />
</>,
);
await screen.findByRole("region", { name: regionName });
await screen.findByRole("region", { name: "Claude Code" });
return backend;
};
const model = {
@@ -906,129 +906,6 @@ 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")];
+1 -1
View File
@@ -10,7 +10,7 @@ export const AGENT_SETTINGS_DEFAULTS: ResolvedAgentSettings = {
showWorkTime: true,
showUsageLimits: true,
showCost: false,
foldTurns: false,
foldTurns: true,
smoothText: true,
fitWindowWidth: false,
thinking: "auto",
+4 -39
View File
@@ -2,12 +2,9 @@ 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,
@@ -292,45 +289,13 @@ describe("agent composer", () => {
expect(atEdgeLine("a\nb", 1, 1)).toBe(false);
});
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";
it("defaults Cursor fast mode off when available", () => {
const fast = option("model_config", ["false", "true"], "true");
fast.id = "fast";
fast.name = "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",
});
expect(cursorModelDefaults("cursor", [fast])).toEqual({ fast: "false" });
expect(cursorModelDefaults("claude", [fast])).toEqual({});
expect(modelConfigOptions([fast]).map((o) => o.id)).toEqual(["fast"]);
});
it("picks the main settings and cycles the mode", () => {
+8 -45
View File
@@ -452,28 +452,21 @@ 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|context_tier|contextTier)$/.test(id);
export const isFastOption = (id: string) => id === "fast";
export const isContextOption = (id: string) => /^(context_tier|contextTier)$/.test(id);
/** 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" ||
o.category === "model_config" ||
isFastOption(o.id) ||
isContextOption(o.id);
o.category === "thought_level" || o.category === "context_tier" || isContextOption(o.id);
const matchesCategory = (o: AgentConfigOption, category: string) =>
o.category === category ||
(category === "model_config" &&
(o.category === "model_config" || o.category === "context_tier" || isFastOption(o.id) || isContextOption(o.id)));
(o.category === "model_config" || o.category === "context_tier" || o.id === "fast" || isContextOption(o.id)));
/** Cursor / ACP model parameters (`fast`, `context`, `contextTier`…), separate from the model id itself. */
/** Cursor / ACP model parameters (`fast`, `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" || isFastOption(o.id) || isContextOption(o.id),
(o) => o.category === "model_config" || o.category === "context_tier" || o.id === "fast" || isContextOption(o.id),
);
}
@@ -486,13 +479,13 @@ export function mainOptions(config: readonly AgentConfigOption[]): AgentConfigOp
});
}
/** Cursor defaults to Fast; prefer standard speed unless the user chose otherwise. */
/** Cursor defaults to Fast; prefer standard Composer 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) => isFastOption(o.id));
const fast = config.find((o) => o.id === "fast" || o.category === "model_config");
if (fast?.values.some((v) => v.value === "false")) return { [fast.id]: "false" };
return {};
}
@@ -518,14 +511,7 @@ export function modeIcon(mode: string): string {
return "lock";
}
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. */
/** The settings that approve everything without asking (a bypass mode, or approvals), by option id. */
export function bypassDefaults(config: readonly AgentConfigOption[]): Record<string, string> {
const out: Record<string, string> = {};
const mode = modeOption(config);
@@ -539,29 +525,6 @@ 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
View File
@@ -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("option", { name: "max" }));
expect(screen.getByRole("option", { name: "long_context" })).toBeVisible();
fireEvent.click(screen.getByRole("option", { name: "long_context" }));
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("button", { name: "Model" }));
fireEvent.click(screen.getByTitle("big"));
expect(settings).toHaveTextContent("high");
-3
View File
@@ -7,7 +7,6 @@ import type {
AcpImportOutcome,
AgentCliOffer,
AgentCliUpdateResult,
AgentModelCatalog,
AgentProvider,
AgentRegistry,
CustomAgentInput,
@@ -32,7 +31,6 @@ 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>;
@@ -60,7 +58,6 @@ 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 });
+2 -2
View File
@@ -506,8 +506,8 @@ export function Stream({
const rows = useMemo(() => {
if (!entries) return [];
const rows = conversationRows(entries, start, toolCalls === "grouped");
return foldTurns && !finding ? foldTurnRows(rows, foldedTurns(entries, start)) : rows;
}, [entries, start, foldTurns, toolCalls, finding]);
return foldTurns && !finding ? foldTurnRows(rows, foldedTurns(entries, start, busy)) : rows;
}, [entries, start, busy, foldTurns, toolCalls, finding]);
const authorHeaders = useMemo(() => {
const headers = new Set<number>();
const byAgent = (row: ConversationRow) =>
@@ -12,62 +12,24 @@ const user = (text: string): AgentEntry => ({
doneMs: 5000,
});
const agent = (text: string): AgentEntry => ({ type: "agent", text });
const tool = (id: string, kind = "read", added = 0): AgentEntry => ({
const tool = (id: string, added = 0): AgentEntry => ({
type: "tool",
id,
title: id,
kind,
kind: "edit",
status: "completed",
locations: [],
output: null,
diffs: added ? [{ path: `/${id}.ts`, added, removed: 0 }] : [],
});
const rowsOf = (entries: AgentEntry[]) => {
const rowsOf = (entries: AgentEntry[], busy = false) => {
const rows = conversationRows(entries, 0);
return foldTurnRows(rows, foldedTurns(entries, 0));
return foldTurnRows(rows, foldedTurns(entries, 0, busy));
};
describe("conversationRows", () => {
it("groups consecutive read-only exploration entries and keeps edits and commands separate", () => {
const entries: AgentEntry[] = [
user("a"),
{ type: "thought", text: "inspect" },
tool("r1", "read"),
tool("s1", "search"),
tool("e1", "edit", 3),
tool("cmd1", "execute"),
tool("f1", "fetch"),
tool("r2", "read"),
agent("done"),
];
const rows = conversationRows(entries, 0);
expect(rows.map((row) => row.kind)).toEqual(["entry", "process", "entry", "entry", "process", "entry"]);
expect(rows[1]!.kind === "process" ? rows[1]!.entries.length : 0).toBe(3);
expect(rows[4]!.kind === "process" ? rows[4]!.entries.length : 0).toBe(2);
});
it("flattens grouped runs inside a folded turn to avoid nested folds", () => {
const entries: AgentEntry[] = [
user("a"),
tool("r1", "read"),
tool("r2", "search"),
tool("e1", "edit", 2),
agent("done"),
user("b"),
agent("next"),
];
const rows = rowsOf(entries);
const turn = rows[1]!;
expect(turn.kind).toBe("turn");
if (turn.kind === "turn") {
expect(turn.rows.map((r) => r.kind)).toEqual(["entry", "entry", "entry"]);
}
});
});
describe("sameRow", () => {
const entries = [user("a"), tool("t1", "edit"), tool("t2", "edit"), agent("done"), user("b"), agent("streaming")];
const entries = [user("a"), tool("t1"), tool("t2"), agent("done"), user("b"), agent("streaming")];
it("sees the rows of the same conversation as the same, whichever copy it was built from", () => {
const again = rowsOf(entries);
@@ -76,20 +38,20 @@ describe("sameRow", () => {
});
it("leaves the rows a streamed chunk did not touch the same and the grown one different", () => {
const before = rowsOf(entries);
const after = rowsOf([...entries.slice(0, -1), agent("streaming on")]);
const before = rowsOf(entries, true);
const after = rowsOf([...entries.slice(0, -1), agent("streaming on")], true);
expect(after.map((row, i) => sameRow(before[i]!, row))).toEqual([true, true, true, true, false]);
});
it("tells a turn whose work changed from one whose work did not", () => {
const [, turn] = rowsOf(entries);
const [, edited] = rowsOf([entries[0]!, tool("t1", "edit"), tool("t2", "edit", 7), ...entries.slice(3)]);
const [, edited] = rowsOf([entries[0]!, tool("t1"), tool("t2", 7), ...entries.slice(3)]);
expect(sameRow(turn!, edited!)).toBe(false);
});
it("tells a run that gained a call from the run before", () => {
const run = conversationRows([user("a"), tool("t1", "read"), tool("t2", "read")], 0)[1]!;
const longer = conversationRows([user("a"), tool("t1", "read"), tool("t2", "read"), tool("t3", "read")], 0)[1]!;
const run = conversationRows([user("a"), tool("t1"), tool("t2")], 0)[1]!;
const longer = conversationRows([user("a"), tool("t1"), tool("t2"), tool("t3")], 0)[1]!;
expect(run.kind).toBe("process");
expect(sameRow(run, longer)).toBe(false);
});
@@ -20,15 +20,11 @@ export type TurnRow = Extract<ConversationRow, { kind: "turn" }>;
export const liveTool = (entry: AgentEntry) =>
entry.type === "tool" && (entry.status === "running" || entry.status === "pending");
const EXPLORATION_KINDS = new Set(["read", "search", "fetch", "think"]);
/**
* Reasoning and read-only exploration tool calls fold together, running ones included: the run
* keeps its place while a call finishes, and its summary line says what is running. Edits,
* commands and other side-effecting calls stay visible as their own rows.
* Reasoning and tool calls fold together, running ones included: the run keeps its place while
* a call finishes, and its summary line says what is running.
*/
export const isProcessEntry = (entry: AgentEntry) =>
entry.type === "thought" || (entry.type === "tool" && EXPLORATION_KINDS.has(entry.kind) && entry.diffs.length === 0);
export const isProcessEntry = (entry: AgentEntry) => entry.type === "thought" || entry.type === "tool";
/**
* The conversation's rows from `from`: a run of reasoning and finished tool calls becomes
@@ -61,11 +57,7 @@ export function foldTurnRows(rows: ConversationRow[], turns: ReadonlyMap<number,
let open: Extract<ConversationRow, { kind: "turn" }> | null = null;
for (const row of rows) {
if (open && row.index < open.turn.reply) {
if (row.kind === "process") {
for (const item of row.entries) open.rows.push({ kind: "entry", ...item });
} else {
open.rows.push(row);
}
open.rows.push(row);
continue;
}
open = null;
+11 -58
View File
@@ -482,13 +482,10 @@ describe("tool result images", () => {
tool("preview", { images: [image] }),
tool("inspect", { output: "Preview ready" }),
{ type: "agent", text: "Here is the result." },
{ type: "user", text: "Thanks", attachments: [], steered: false, sentMs: 3000, doneMs: 4000 },
{ type: "agent", text: "You're welcome." },
]);
useAgents.setState({ entries: new Map(backend.entries) });
render(<SessionEditor input={input("A")} />);
await screen.findByText("Here is the result.");
expect(!!stream().querySelector(`.${styles.turnFold}`)).toBe(foldTurns);
const preview = screen.getByRole("img", { name: "Image" });
expect(preview).toHaveAttribute("src", "data:image/png;base64,aW1hZ2U=");
expect(preview.closest("details")).toBeNull();
@@ -502,7 +499,7 @@ describe("tool result images", () => {
});
describe("turn folding", () => {
it("keeps a finished turn's interim text and tools visible by default", async () => {
it("folds a finished turn's work under its message and keeps the reply", async () => {
backend.entries.set("A", [
{
type: "user",
@@ -520,43 +517,7 @@ describe("turn folding", () => {
]);
useAgents.setState({ entries: new Map(backend.entries) });
render(<SessionEditor input={input("A")} />);
expect(await screen.findByText("Interim note")).toBeInTheDocument();
expect(screen.getByText("two")).toBeInTheDocument();
expect(screen.getByText("Final reply")).toBeInTheDocument();
expect(stream().querySelector(`.${styles.turnFold}`)).toBeNull();
});
it("folds earlier turns when foldTurns is enabled, keeping the latest turn open and flattening runs inside", async () => {
useProject.setState({ settings: { agents: { foldTurns: true } } as never });
backend.entries.set("A", [
{
type: "user",
text: "Question",
attachments: [],
steered: false,
sentMs: 1000,
doneMs: 13000,
},
{ type: "thought", text: "think" },
tool("one"),
{ type: "agent", text: "Interim note" },
tool("two", { kind: "execute" }),
{ type: "agent", text: "Final reply" },
{
type: "user",
text: "Follow up",
attachments: [],
steered: false,
sentMs: 14000,
doneMs: 15000,
},
tool("latest", { kind: "execute" }),
{ type: "agent", text: "Latest reply" },
]);
useAgents.setState({ entries: new Map(backend.entries) });
render(<SessionEditor input={input("A")} />);
await screen.findByText("Latest reply");
expect(screen.getByText("latest")).toBeInTheDocument();
await screen.findByText("Final reply");
const summary = screen.getByText("Ran 1 command · Read 1 file · 1 message");
const fold = summary.closest("details")!;
expect(fold).toHaveClass(styles.turnFold!);
@@ -565,12 +526,9 @@ describe("turn folding", () => {
fold.open = true;
fireEvent(fold, new Event("toggle"));
expect(await screen.findByText("Interim note")).toBeInTheDocument();
expect(screen.getByText("one")).toBeInTheDocument();
expect(fold.querySelector(`.${styles.processRun}`)).toBeNull();
});
it("leaves the turn the agent works on open", async () => {
useProject.setState({ settings: { agents: { foldTurns: true } } as never });
backend.entries.set("A", [
{
type: "user",
@@ -631,7 +589,7 @@ describe("working status", () => {
});
describe("opened runs", () => {
it("stay open while the run grows and when the turn finishes", async () => {
it("stay open when the finished turn folds them away and is opened again", async () => {
const asked = {
type: "user",
text: "Question",
@@ -673,6 +631,9 @@ describe("opened runs", () => {
...setTask("ready"),
}),
);
const turn = screen.getByText("Read 2 files · 1 message").closest("details")!;
expect(turn).toHaveClass(styles.turnFold!);
toggle(turn);
expect(screen.getByText("Read 2 files").closest("details")!.open).toBe(true);
});
});
@@ -1295,27 +1256,19 @@ describe("tool calls", () => {
expect(screen.queryByText("Reading files…")).toBeNull();
});
it("folds consecutive exploration calls into one collapsed row while keeping edits visible", async () => {
it("folds consecutive finished tool calls into one collapsed row", async () => {
const edit = (id: string) =>
tool(id, {
kind: "edit",
diffs: [{ path: "/project/a.ts", added: 2, removed: 1 }],
});
backend.entries.set("A", [
tool("r1", { kind: "read" }),
tool("s1", { kind: "search" }),
edit("one"),
edit("two"),
{ type: "agent", text: "Answer A" },
]);
backend.entries.set("A", [edit("one"), edit("two"), { type: "agent", text: "Answer A" }]);
useAgents.setState({ entries: new Map(backend.entries) });
render(<SessionEditor input={input("A")} />);
const summary = await screen.findByText("Read 1 file · Searched once");
const summary = await screen.findByText("Edited 1 file");
expect(summary.closest("details")!.open).toBe(false);
expect(screen.getByText("one")).toBeInTheDocument();
expect(screen.getByText("two")).toBeInTheDocument();
expect(screen.getAllByText("+2")).toHaveLength(2);
expect(screen.getAllByText("−1")).toHaveLength(2);
expect(screen.getByText("+4")).toBeInTheDocument();
expect(screen.getByText("−2")).toBeInTheDocument();
});
});
+32 -32
View File
@@ -36,7 +36,7 @@ import { editorService, notifications, notifyTabTitlesChanged, toolWindowService
import { tx } from "@/platform/i18n";
import { confirm, showError } from "@/workbench/messages";
import {
approvalDefaults,
bypassDefaults,
canSend,
shellCommand,
cursorModelDefaults,
@@ -261,7 +261,6 @@ 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 ?? [];
@@ -270,31 +269,27 @@ export function draftConfig(
priorModel && draft.config[priorModel.id] !== undefined && !offered.some((o) => o.category === "model")
? [...offered, { ...priorModel, values: [] }]
: offered;
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 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 model = config.find((o) => o.category === "model")?.current;
if (model) {
config.push(
...(draftModelSettings(
(catalog ?? provider)?.thoughtLevels?.[model],
draft.thoughtLevels?.[model],
defaults,
provider?.id,
) ?? []),
...(draftModelSettings((catalog ?? provider)?.thoughtLevels?.[model], draft.thoughtLevels?.[model], defaults) ??
[]),
);
}
return config;
@@ -304,12 +299,9 @@ export function draftModelSettings(
options: AgentConfigOption[] | undefined,
choices: Record<string, string> | undefined,
defaults: Record<string, string>,
providerId?: string,
) {
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 options?.map((o) => {
const choice = choices?.[o.id] ?? defaults[o.id];
return {
...o,
defaultValue: o.defaultValue ?? o.current,
@@ -1293,9 +1285,17 @@ export async function startTask(
)
)
return;
const config = options.flatMap((o) =>
o.current !== null && o.values.some((v) => v.value === o.current) ? [{ id: o.id, value: o.current }] : [],
);
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 }] : [];
});
try {
const task = await call(
commands.agentCreate({
+12 -17
View File
@@ -48,26 +48,21 @@ describe("summarizeWork", () => {
});
describe("foldedTurns", () => {
it("folds earlier finished turns' work before their reply and keeps the latest turn open", () => {
it("folds a finished turn's work before its reply", () => {
const entries = [user("q"), tool("read"), agent("mid"), tool("edit"), agent("done"), user("next"), agent("ok")];
expect([...foldedTurns(entries, 0).values()]).toEqual([{ user: 0, reply: 4, sentMs: 1000, doneMs: 5000 }]);
expect([...foldedTurns(entries, 0, false).values()]).toEqual([{ user: 0, reply: 4, sentMs: 1000, doneMs: 5000 }]);
});
it("leaves the latest turn, turns without work, and turns ending otherwise open", () => {
const latestOnly = [user("q"), tool("read"), agent("a")];
expect(foldedTurns(latestOnly, 0).size).toBe(0);
expect(foldedTurns([user("q"), agent("a"), user("next")], 0).size).toBe(0);
expect(foldedTurns([user("q"), tool("read"), user("next")], 0).size).toBe(0);
expect(
foldedTurns([user("q"), tool("read"), agent("a"), { type: "error", message: "x" }, user("next")], 0).size,
).toBe(0);
expect(
foldedTurns([user("q"), { type: "error", message: "x" }, tool("read"), agent("a"), user("next")], 0).size,
).toBe(0);
expect(
foldedTurns([user("q"), tool("read"), user("more", { steered: true }), agent("a"), user("next")], 0).size,
).toBe(0);
expect(foldedTurns([user("q"), tool("read"), agent("a"), user("next")], 1).size).toBe(0);
it("leaves the turn in progress, turns without work, and turns ending otherwise open", () => {
const working = [user("q"), tool("read"), agent("a")];
expect(foldedTurns(working, 0, true).size).toBe(0);
expect(foldedTurns(working, 0, false).size).toBe(1);
expect(foldedTurns([user("q"), agent("a")], 0, false).size).toBe(0);
expect(foldedTurns([user("q"), tool("read")], 0, false).size).toBe(0);
expect(foldedTurns([user("q"), tool("read"), agent("a"), { type: "error", message: "x" }], 0, false).size).toBe(0);
expect(foldedTurns([user("q"), { type: "error", message: "x" }, tool("read"), agent("a")], 0, false).size).toBe(0);
expect(foldedTurns([user("q"), tool("read"), user("more", { steered: true }), agent("a")], 0, false).size).toBe(0);
expect(foldedTurns([user("q"), tool("read"), agent("a")], 1, false).size).toBe(0);
});
});
+7 -6
View File
@@ -101,12 +101,13 @@ export interface FoldedTurn {
}
/**
* The earlier finished turns whose work before their last reply folds into one line. A turn
* folds once a later turn has started, when it ended with a reply and did something before
* that reply (and neither the user sent anything into it nor it ran into an error meanwhile);
* the latest turn always stays open. Turns asked before `from` aren't shown and so don't fold.
* The finished turns whose work before their last reply folds into one line. A turn
* folds when it has ended, ended with a reply, and did something before that reply (and
* neither the user sent anything into it nor it ran into an error meanwhile); the
* latest turn stays open while the agent works. Turns asked before `from` aren't shown
* and so don't fold.
*/
export function foldedTurns(entries: readonly AgentEntry[], from: number): Map<number, FoldedTurn> {
export function foldedTurns(entries: readonly AgentEntry[], from: number, busy: boolean): Map<number, FoldedTurn> {
const turns = new Map<number, FoldedTurn>();
const starts: number[] = [];
entries.forEach((e, i) => {
@@ -115,7 +116,7 @@ export function foldedTurns(entries: readonly AgentEntry[], from: number): Map<n
starts.forEach((user, k) => {
const end = starts[k + 1] ?? entries.length;
const last = k === starts.length - 1;
if (last) return;
if (last && busy) return;
const asked = entries[user] as Extract<AgentEntry, { type: "user" }>;
let reply = -1;
for (let i = end - 1; i > user; i--) {
+6 -14
View File
@@ -49,7 +49,6 @@ export async function walkFiles(
while (queue.length && out.length < limit) {
let entries: FileEntry[];
try {
// oxlint-disable-next-line no-await-in-loop -- BFS stops at the file limit; each read supplies the next queue entries
entries = await readDir(queue.shift()!);
} catch {
continue;
@@ -144,13 +143,10 @@ async function runOverFiles(
done: false,
cancel: () => (run.cancelled = true),
});
// oxlint-disable-next-line no-await-in-loop -- cleanup runs one file at a time so cancel, progress and open/close state stay ordered
const result = await cleanupFile(path, options);
if (result?.applied) summary.formatted++;
if (result?.noFormatter) summary.noFormatter.push(path);
// oxlint-disable-next-line no-await-in-loop -- save the file just cleaned before its tab is closed
await saveCleaned(path);
// oxlint-disable-next-line no-await-in-loop -- a refused close cancels the run; editors must settle before the next file
if (!wasOpen.has(path) && (await editors?.closePath?.(path)) === false) {
run.cancelled = true;
break;
@@ -270,17 +266,13 @@ export async function reformatTargets(
const mask = maskMatcher(options.mask);
const accept = (p: string) => sources.isText(p) && mask(nameOf(p));
const found = new Set<string>();
for (const t of targets) if (!t.dir && mask(nameOf(t.path))) found.add(t.path);
const dirs = targets.filter((t) => t.dir);
const walked: string[][] = [];
for (let i = 0; i < dirs.length; i += 8) {
// oxlint-disable-next-line no-await-in-loop -- bound concurrent walks; results are merged in target order
const batch = await Promise.all(
dirs.slice(i, i + 8).map((t) => walkFiles(t.path, sources.readDir, accept, { recursive: options.recursive })),
);
walked.push(...batch);
for (const t of targets) {
if (!t.dir) {
if (mask(nameOf(t.path))) found.add(t.path);
continue;
}
for (const p of await walkFiles(t.path, sources.readDir, accept, { recursive: options.recursive })) found.add(p);
}
for (const paths of walked) for (const p of paths) found.add(p);
if (options.changedTextOnly) {
const changed = new Set(await sources.changedFiles());
for (const p of found) if (!changed.has(p)) found.delete(p);
@@ -452,7 +452,6 @@ it("leaves test code alone", async () => {
expect(await testMethod.run()).toEqual([]);
for (const path of ["/p/tests/test_a.py", "/p/a_test.py", "/p/conftest.py"]) {
const testFile = new Fixture(path).add(path, [{ name: "Helpers", line: 0, bases: [], methods: [helper] }]);
// oxlint-disable-next-line no-await-in-loop -- assertions stay in path order so a failure names the exact test file
expect(await testFile.run()).toEqual([]);
}
});
@@ -140,7 +140,6 @@ class ProjectView {
const decl = this.declarationOf(facts);
if (!decl) continue;
const item = classItem(this.deps.outline, facts);
// oxlint-disable-next-line no-await-in-loop -- classes stay in declaration order while ancestryOf fills the shared memo cache
const { firstUnresolvedDepth } = await this.ancestryOf(decl);
out.push({ decl, facts, members: memberNames(item), firstUnresolvedDepth });
}
@@ -178,7 +177,6 @@ class ProjectView {
const key = declarationKey(sub);
if (seen.has(key)) continue;
seen.add(key);
// oxlint-disable-next-line no-await-in-loop -- BFS with a shared `seen` set; the first subclass declaring the name ends the search
if ((await this.membersOf(sub)).has(name) || (await this.methodsOf(sub)).some((m) => m.name === name))
return true;
queue.push(sub);
@@ -265,18 +263,13 @@ export async function inheritanceDiagnostics(deps: InheritanceInspectionDeps): P
// A class whose header changed since the graph was indexed is skipped: every rule
// below would reason about a parent the source no longer names.
if (!sameNames(cls.facts.bases, cls.decl.bases)) continue;
// oxlint-disable-next-line no-await-in-loop -- ordered analysis pass; diagnostics append in producer order
if (runs(PYTHON_CIRCULAR_BASES_PRODUCER)) out.push(...(await circularInheritance(view, cls)));
// A method may live on any ancestor: only a fully known chain can say it does not.
// oxlint-disable-next-line no-await-in-loop -- ordered analysis pass; diagnostics append in producer order
if (runs(PYTHON_OVERRIDE_PRODUCER) && view.complete(cls)) out.push(...(await unusedOverride(view, cls)));
// oxlint-disable-next-line no-await-in-loop -- ordered analysis pass; diagnostics append in producer order
if (runs(PYTHON_REDUNDANT_OVERRIDE_PRODUCER)) out.push(...(await redundantOverride(view, cls)));
// oxlint-disable-next-line no-await-in-loop -- ordered analysis pass; diagnostics append in producer order
if (runs(PYTHON_ABSTRACT_METHOD_PRODUCER)) out.push(...(await missingAbstractMethods(view, cls)));
// A method may override one a foreign base declares: only a fully known chain can say it does not.
if (runs(PYTHON_METHOD_MAY_BE_STATIC_PRODUCER) && view.complete(cls))
// oxlint-disable-next-line no-await-in-loop -- ordered analysis pass; diagnostics append in producer order
out.push(...(await mayBeStatic(view, cls, deps.path)));
}
return out;
@@ -301,7 +294,6 @@ async function unusedOverride(view: ProjectView, cls: ClassView): Promise<Diagno
const out: Diagnostic[] = [];
for (const method of cls.facts.methods) {
if (!method.overrideDecorated || isDunder(method.name)) continue;
// oxlint-disable-next-line no-await-in-loop -- one method at a time so diagnostics keep declaration order; the memoised view is concurrency-safe
if (await declaredInAncestry(view, cls, method.name)) continue;
out.push(
problem(
@@ -328,7 +320,6 @@ async function mayBeStatic(view: ProjectView, cls: ClassView, path: string): Pro
const out: Diagnostic[] = [];
for (const method of cls.facts.methods) {
if (!method.unusedReceiver || method.name.startsWith("test")) continue;
// oxlint-disable-next-line no-await-in-loop -- ancestry checks share the memoised view; the first hit skips this method
if ((await declaredInAncestry(view, cls, method.name)) || (await view.overriddenBelow(cls, method.name))) continue;
out.push(
problem(
@@ -353,11 +344,9 @@ async function missingAbstractMethods(view: ProjectView, cls: ClassView): Promis
for (const ancestor of await view.ancestors(cls)) {
// A foreign base above the declarer cannot override it: Python's MRO puts it later.
if (!view.knownTo(cls, ancestor.depth - 1)) continue;
// oxlint-disable-next-line no-await-in-loop -- ancestor methods are read in MRO order into the shared `reported` set
for (const method of await view.methodsOf(ancestor.decl)) {
const name = method.name;
if (!method.abstractMethod || reported.has(name) || cls.members.has(name)) continue;
// oxlint-disable-next-line no-await-in-loop -- the nearest concrete implementation wins; later ancestors are still in MRO order
if (await implementedAbove(view, cls, ancestor.depth, name)) continue;
reported.add(name);
out.push(
@@ -383,10 +372,8 @@ async function implementedAbove(
for (const ancestor of await view.ancestors(cls)) {
if (ancestor.depth >= declarerDepth) return false;
if (!view.knownTo(cls, ancestor.depth - 1)) return true;
// oxlint-disable-next-line no-await-in-loop -- nearest ancestor first; a method found here returns before reading further
const method = (await view.methodsOf(ancestor.decl)).find((m) => m.name === name);
if (method) return !method.abstractMethod;
// oxlint-disable-next-line no-await-in-loop -- an attribute on a nearer ancestor resolves the search immediately
if ((await view.membersOf(ancestor.decl)).has(name)) return true;
}
return false;
@@ -396,7 +383,6 @@ async function implementedAbove(
async function redundantOverride(view: ProjectView, cls: ClassView): Promise<Diagnostic[]> {
const out: Diagnostic[] = [];
for (const method of cls.facts.methods) {
// oxlint-disable-next-line no-await-in-loop -- one method at a time so diagnostics keep declaration order; the memoised view is concurrency-safe
const inherited = await inheritedMethod(view, cls, method.name);
// A foreign base below the declarer cannot change which method runs: MRO puts it later.
if (!inherited || !view.knownTo(cls, inherited.depth)) continue;
@@ -436,7 +422,6 @@ async function inheritedMethod(
name: string,
): Promise<{ method: PythonMethodFacts; depth: number } | null> {
for (const ancestor of await view.ancestors(cls)) {
// oxlint-disable-next-line no-await-in-loop -- nearest ancestor wins; stop at the first declaration found
const found = (await view.methodsOf(ancestor.decl)).find((m) => m.name === name);
if (found) return { method: found, depth: ancestor.depth };
}
@@ -446,9 +431,7 @@ async function inheritedMethod(
/** Whether any ancestor declares `name`, as a member or a method. */
async function declaredInAncestry(view: ProjectView, cls: ClassView, name: string): Promise<boolean> {
for (const ancestor of await view.ancestors(cls)) {
// oxlint-disable-next-line no-await-in-loop -- nearest ancestor first; the first declaration ends the search
if ((await view.membersOf(ancestor.decl)).has(name)) return true;
// oxlint-disable-next-line no-await-in-loop -- only reached when the nearer ancestor had no such member
if ((await view.methodsOf(ancestor.decl)).some((m) => m.name === name)) return true;
}
return false;
-61
View File
@@ -34,7 +34,6 @@ import {
} from "./model";
import {
BUILD_TASK_ID,
followLaunchBuild,
rerunBuild,
setBuildBackend,
startBuild,
@@ -687,64 +686,4 @@ describe("build feature", () => {
);
expect(screen.getByRole("document", { name: "Build message" })).toHaveTextContent("cannot find symbol");
});
it("follows a launch's build: status bar progress, its commands in the console, its output in Build", async () => {
vi.useFakeTimers();
try {
const report = vi.fn();
const follower = followLaunchBuild(42 as never, "Build before launch: App", report);
follower.onEvent({ kind: "progress", message: "Resolving the module", fraction: null });
expect(useTasks.getState().tasks.find((t) => t.id === "launch-build:42")).toMatchObject({
title: "Build before launch: App",
message: "Resolving the module",
});
follower.onEvent({ kind: "started", system: "maven", title: "demo: build module 'app'" });
follower.onEvent({ kind: "step", command: "mvn -pl app -am compile", cwd: "/p" });
follower.onEvent({ kind: "output", text: "[INFO] Building app 1 [2/2]\n", stderr: false });
follower.onEvent({ kind: "progress", message: "Building app", fraction: 0.5 });
follower.onEvent({ kind: "message", message: err("/p/app/A.java", 3) });
vi.advanceTimersByTime(20);
expect(report).toHaveBeenCalledWith("mvn -pl app -am compile\n", "system");
expect(useTasks.getState().tasks.find((t) => t.id === "launch-build:42")).toMatchObject({
message: "Building app",
fraction: 0.5,
});
expect(useBuildRun.getState()).toMatchObject({
request: 42,
status: "running",
title: "demo: build module 'app'",
});
expect(useBuildRun.getState().lines.map((l) => l.text)).toEqual([
"mvn -pl app -am compile",
"[INFO] Building app 1 [2/2]",
]);
// A launch build stays out of sight at start, as Build before launch does.
expect(show).not.toHaveBeenCalled();
// Cancel in the status bar cancels the launch's request.
useTasks.getState().tasks.find((t) => t.id === "launch-build:42")!.cancel!();
expect(fake.cancelled).toEqual([42]);
follower.finish("failed");
expect(useBuildRun.getState()).toMatchObject({ request: null, status: "failed" });
expect(getContext()["build.running"]).toBe(false);
expect(show).toHaveBeenCalledWith("build", false);
expect(openFile).toHaveBeenCalledWith("/p/app/A.java", expect.objectContaining({ focus: true }));
} finally {
vi.useRealTimers();
}
});
it("leaves the Build window to a build that is already running", async () => {
void startBuild("build");
await act(async () => {});
const running = useBuildRun.getState().request;
const follower = followLaunchBuild(43 as never, "Build before launch: App");
follower.onEvent({ kind: "started", system: "maven", title: "launch" });
follower.onEvent({ kind: "output", text: "launch output\n", stderr: false });
follower.finish("success");
expect(useBuildRun.getState().request).toBe(running);
expect(useBuildRun.getState().lines.some((l) => l.text === "launch output")).toBe(false);
await act(async () => {
fake.resolve(result([], true));
});
});
});
-71
View File
@@ -317,77 +317,6 @@ async function executeBuild(
return result;
}
/** Follows the build of a Run / Debug launch: see {@link followLaunchBuild}. */
export interface LaunchBuildFollower {
onEvent(e: BuildEvent): void;
/** The launch's build is over (the launch itself may still fail later). */
finish(status: BuildStatus): void;
}
/**
* Follows the before-launch build of a Java launch (`javaResolveLaunch`), as IDEA shows it:
* progress (the phase, the Maven module being built) as a cancellable status bar task, the
* commands it runs in the launch's console (`report`), and, when no other build is running,
* its whole output in the Build tool window, which opens per Settings › Compiler like any
* before-launch build. Cancelling cancels `request`, which stops the build and the launch.
*/
export function followLaunchBuild(
request: RequestId,
title: string,
report?: (text: string, kind?: "system" | "stderr") => void,
): LaunchBuildFollower {
const taskId = `launch-build:${request}`;
const cancel = () => backend.cancel(request);
let owned = false;
let done = false;
const ownsBuild = () => owned && useBuildRun.getState().request === request;
let queue: BuildEvent[] = [];
let timer: ReturnType<typeof setTimeout> | undefined;
const flush = () => {
clearTimeout(timer);
timer = undefined;
const events = queue;
queue = [];
if (!ownsBuild() || !events.length) return;
let s = useBuildRun.getState();
for (const e of events) s = { ...s, ...applyBuildEvent(s, e) };
useBuildRun.setState(s);
};
const take = () => {
if (owned || isBuilding()) return;
owned = true;
const previous = useBuildRun.getState().files;
useBuildRun.setState({ ...INITIAL, request, kind: "build", title, status: "running", files: previous });
setContext(BUILD_LAST_STATUS, null);
setContext(BUILD_RUNNING, true);
showBuildWindow("start", false);
};
return {
onEvent(e) {
if (done) return;
if (e.kind === "progress")
upsertTask({ id: taskId, title, message: e.message, fraction: e.fraction, done: false, cancel });
if (e.kind === "started") take();
if (e.kind === "step") report?.(`${e.command}\n`, "system");
if (!ownsBuild()) return;
queue.push(e);
timer ??= setTimeout(flush, 16);
},
finish(status) {
if (done) return;
done = true;
upsertTask({ id: taskId, title, message: null, fraction: 1, done: true });
if (!ownsBuild()) return;
flush();
const { messages } = useBuildRun.getState();
useBuildRun.setState({ status, request: null, message: null });
setContext(BUILD_LAST_STATUS, status);
setContext(BUILD_RUNNING, false);
if (status === "failed" && messages.length) showFailure();
},
};
}
/** Opens the source of a build message; `focus` moves focus to the editor (otherwise a preview). */
export function navigateToMessage(m: BuildMessage, focus: boolean) {
if (!m.path) return;
+2 -20
View File
@@ -459,19 +459,6 @@ export function DatabaseView() {
};
});
/** The shown nodes with keys in `keys`, in tree order. */
const shownNodes = (keys: ReadonlySet<string>): Node[] => {
const out: Node[] = [];
const walk = (nodes: readonly Node[]) => {
for (const n of nodes) {
if (keys.has(n.key)) out.push(n);
if (st.treeExpanded.has(n.key)) walk(children(n) ?? []);
}
};
walk(roots);
return out;
};
const label = (n: Node): string => {
switch (n.kind) {
case "source":
@@ -669,13 +656,8 @@ export function DatabaseView() {
</span>
);
}}
onSelectionChange={(selected, lead) =>
useDatabase.setState({
selectedSource: lead ? nodeTarget(lead) : null,
selectedNode: lead,
// Not just the lead: a ⌘-click that deselects a row still makes it the lead.
selectedNodes: shownNodes(selected),
})
onSelectionChange={(_, lead) =>
useDatabase.setState({ selectedSource: lead ? nodeTarget(lead) : null, selectedNode: lead })
}
onActivate={(n) => {
if (n.kind === "table") openTableData(n.id, n.schema, n.table.name);
-45
View File
@@ -1,45 +0,0 @@
.diagram {
height: 100%;
overflow: auto;
padding: 16px 28px;
background: var(--bg-editor);
color: var(--fg);
}
/* The source stays until the diagram is drawn, and next to an error. */
.diagram :global([data-mermaid]) {
position: relative;
}
.diagram :global([data-mermaid-state="ok"] > pre) {
display: none;
}
.diagram :global([data-mermaid] > pre) {
margin: 0;
}
.diagram :global(.mermaid-output) {
overflow-x: auto;
overflow-y: hidden;
text-align: center;
}
.diagram :global([data-mermaid-state="ok"] > .mermaid-output) {
user-select: none;
}
.diagram :global(.mermaid-output svg[data-natural-width]) {
display: block;
margin: 0 auto;
width: min(var(--diagram-width), 100%);
height: auto;
}
.diagram :global(.mermaid-output[data-zoomed="true"]) {
overflow: hidden;
cursor: grab;
touch-action: none;
}
.diagram :global(.mermaid-output[data-dragging="true"]) {
cursor: grabbing;
}
.diagram :global([data-mermaid-state="error"] > .mermaid-output) {
color: var(--danger);
font-family: var(--font-mono);
text-align: left;
white-space: pre-wrap;
}
-30
View File
@@ -1,30 +0,0 @@
/** The tab Diagrams › Show Diagram opens: a read-only ER diagram drawn by the Markdown preview's Mermaid renderer. */
import { useLayoutEffect, useRef, useSyncExternalStore } from "react";
import { renderMermaidIn } from "@/features/viewers/markdown/mermaid";
import { subscribeTheme, themeKey } from "@/platform/themeWatch";
import type { EditorInput } from "@/workbench/contributions";
import type { DiagramData } from "./erDiagram";
import styles from "./Diagram.module.css";
export function DiagramEditor({ input }: { input: EditorInput }) {
const { source } = input.data as DiagramData;
const block = useRef<HTMLDivElement>(null);
const previous = useRef<Node[]>([]);
// Drawn in the active theme's colours: a theme change redraws it.
const theme = useSyncExternalStore(subscribeTheme, themeKey, () => "");
useLayoutEffect(() => {
const root = block.current;
if (!root) return;
const pass = renderMermaidIn(root, previous.current);
return () => pass.cancel();
}, [source, theme]);
return (
<div className={styles.diagram} ref={block}>
<div data-mermaid="">
<pre>
<code className="language-mermaid">{source}</code>
</pre>
</div>
</div>
);
}
-136
View File
@@ -1,136 +0,0 @@
import { describe, expect, it } from "vitest";
import type { DbColumnInfo, DbForeignKey } from "@/platform/ipc";
import { erDiagram, type DiagramTable } from "./erDiagram";
const col = (name: string, dataType = "integer", extra: Partial<DbColumnInfo> = {}): DbColumnInfo => ({
name,
dataType,
nullable: false,
default: null,
primaryKey: false,
...extra,
});
const fk = (table: string, columns: string[], refTable: string, refSchema = "public"): DbForeignKey => ({
schema: "public",
table,
columns,
refSchema,
refTable,
refColumns: ["id"],
});
const table = (
name: string,
columns: DbColumnInfo[],
foreignKeys: DbForeignKey[] = [],
schema = "public",
id = "pg",
): DiagramTable => ({ id, schema, name, details: { columns, indexes: [], foreignKeys, triggers: [] } });
const users = table("users", [col("id", "integer", { primaryKey: true }), col("name", "text")]);
const orders = table(
"orders",
[col("id", "integer", { primaryKey: true }), col("user_id"), col("coupon_id", "integer", { nullable: true })],
[fk("orders", ["user_id"], "users"), fk("orders", ["coupon_id"], "coupons")],
);
describe("erDiagram", () => {
it("lists the columns with PK / FK markers and links the selected tables by their foreign keys", () => {
expect(erDiagram([users, orders])).toBe(
[
"erDiagram",
' t0["users"] {',
" `integer` `id` PK",
" `text` `name`",
" }",
' t1["orders"] {',
" `integer` `id` PK",
" `integer` `user#95;id` FK",
" `integer` `coupon#95;id` FK",
" }",
' t0 ||--o{ t1 : "user#95;id"',
].join("\n"),
);
});
it("draws no relationship to a table that is not selected", () => {
expect(erDiagram([orders])).not.toContain("--");
});
it("makes the parent optional when a referencing column is nullable", () => {
const coupons = table("coupons", [col("id", "integer", { primaryKey: true })]);
expect(erDiagram([coupons, orders])).toContain('t0 |o--o{ t1 : "coupon#95;id"');
});
it("draws one relationship per composite foreign key, and one to the table itself", () => {
const lines = table(
"lines",
[col("order_id"), col("n")],
[{ ...fk("lines", ["order_id", "n"], "lines"), refColumns: ["order_id", "n"] }],
);
expect(
erDiagram([lines])
.split("\n")
.filter((l) => l.includes("--")),
).toEqual([' t0 ||--o{ t0 : "order#95;id#44; n"']);
});
it("matches a referenced table spelled in another case (SQLite keeps the DDL's spelling)", () => {
const child = table("child", [col("p")], [fk("child", ["p"], "USERS")]);
expect(erDiagram([users, child])).toContain('t0 ||--o{ t1 : "p"');
});
it("keeps tables of different schemas or data sources apart and qualifies their names", () => {
const archived = table("users", [col("id")], [], "archive");
const other = table("users", [col("id")], [], "public", "mysql");
const diagram = erDiagram([users, archived, other]);
expect(diagram).toContain('t0["public#46;users"]');
expect(diagram).toContain('t1["archive#46;users"]');
expect(diagram).toContain('t2["public#46;users"]');
const child = table("child", [col("u")], [fk("child", ["u"], "users", "archive")]);
expect(erDiagram([users, archived, child])).toContain('t1 ||--o{ t2 : "u"');
});
it.each([
["spaces", "order items", "order items"],
["a double quote", 'say "hi"', "say #34;hi#34;"],
["a backtick", "a`b", "a#96;b"],
["percent and backslash", "50%\\off", "50#37;#92;off"],
["an entity-like name", "a#35;b", "a#35;35#59;b"],
["markdown and HTML", "*x* <b>_y_</b>", "#42;x#42; #60;b#62;#95;y#95;#60;#47;b#62;"],
["braces and a newline", "a{b}\nc", "a#123;b#125;#10;c"],
["non-ASCII letters", "Заказы_2024", "Заказы#95;2024"],
])("escapes %s in table, column and type names", (_, name, escaped) => {
const diagram = erDiagram([table(name, [col(name, name)], [fk(name, [name], name)])]);
expect(diagram.split("\n")).toEqual([
"erDiagram",
` t0["${escaped}"] {`,
` \`${escaped}\` \`${escaped}\` FK`,
" }",
` t0 ||--o{ t0 : "${escaped}"`,
]);
});
it("stays valid Mermaid whatever the names", async () => {
const mermaid = (await import("mermaid")).default;
const names = [
"order items",
'say "hi"',
"a`b",
"50%\\off",
"a#35;b",
"*x* <b>_y_</b>",
"a{b}\nc",
"numeric(10,2)",
"",
];
const tables = names.map((name, i) =>
table(name || `t${i}`, [col(name || "c", name)], [fk(name, [name || "c"], names[0]!)]),
);
await expect(mermaid.parse(erDiagram(tables))).resolves.toBeTruthy();
});
it("gives a column without a declared type (SQLite) a placeholder type, and an unnamed one a placeholder name", () => {
expect(erDiagram([table("t", [col("x", "")])])).toContain(" `#63;` `x`");
expect(erDiagram([table("t", [col("")])])).toContain(" `integer` `#63;`");
});
});
-76
View File
@@ -1,76 +0,0 @@
/** Diagrams › Show Diagram: the selected tables as a Mermaid ER diagram, linked by their foreign keys. */
import type { DbTableDetails } from "@/platform/ipc";
import type { EditorInput } from "@/workbench/contributions";
export const DIAGRAM_KIND = "db-diagram";
export interface DiagramData {
title: string;
/** Mermaid `erDiagram` source. */
source: string;
}
export const diagramTitle = (input: EditorInput) => (input.data as DiagramData).title;
/** The same diagram opens in the same tab. */
export function diagramInput(data: DiagramData): EditorInput {
return { kind: DIAGRAM_KIND, key: `${DIAGRAM_KIND}:${data.source}`, data };
}
export interface DiagramTable {
/** Connection target. */
id: string;
schema: string;
name: string;
details: DbTableDetails;
}
/** Tables of a schema shown at most: Mermaid lays out and sizes larger diagrams poorly. */
export const DIAGRAM_TABLE_LIMIT = 50;
/** Mermaid's default `maxTextSize`: a longer source renders as an error. */
export const MERMAID_MAX_TEXT = 50_000;
/**
* Text Mermaid shows as written: anything but letters, digits and spaces
* becomes an entity code (`#34;`), so quotes, backticks, `%`, `\`, `#` and
* Markdown markers in a name can neither end its token nor format it.
*/
function text(s: string): string {
return s.replace(/[^\p{L}\p{N} ]/gu, (c) => `#${c.codePointAt(0)};`);
}
const tableKey = (id: string, schema: string, name: string) => `${id}\u0000${schema}\u0000${name}`;
/**
* The Mermaid `erDiagram` source of `tables`: their columns with PK / FK
* markers, and a relationship per foreign key whose referenced table is one of
* `tables`. Names are qualified by schema when the tables span several.
*/
export function erDiagram(tables: readonly DiagramTable[]): string {
const qualify = new Set(tables.map((t) => tableKey(t.id, t.schema, ""))).size > 1;
const ids = new Map(tables.map((t, i) => [tableKey(t.id, t.schema, t.name), `t${i}`]));
// SQLite (and MySQL on case-insensitive file systems) keep the referenced name as the DDL spells it.
const folded = new Map(tables.map((t, i) => [tableKey(t.id, t.schema, t.name).toLowerCase(), `t${i}`]));
const lines = ["erDiagram"];
const relations: string[] = [];
tables.forEach((t, i) => {
const label = qualify ? `${t.schema}.${t.name}` : t.name;
const fkColumns = new Set(t.details.foreignKeys.flatMap((k) => k.columns));
lines.push(` t${i}["${text(label)}"] {`);
for (const c of t.details.columns) {
const keys = [c.primaryKey && "PK", fkColumns.has(c.name) && "FK"].filter(Boolean).join(", ");
lines.push(` \`${text(c.dataType || "?")}\` \`${text(c.name || "?")}\`${keys ? ` ${keys}` : ""}`);
}
lines.push(" }");
for (const k of t.details.foreignKeys) {
const ref = tableKey(t.id, k.refSchema, k.refTable);
const parent = ids.get(ref) ?? folded.get(ref.toLowerCase());
if (!parent) continue;
// A nullable referencing column lets a row reference nothing: zero or one parent.
const optional = k.columns.some((name) => t.details.columns.find((c) => c.name === name)?.nullable ?? true);
relations.push(` ${parent} ${optional ? "|o" : "||"}--o{ t${i} : "${text(k.columns.join(", "))}"`);
}
});
return [...lines, ...relations].join("\n");
}
-8
View File
@@ -31,7 +31,6 @@ import { installValueEditorActions } from "./valueEditorActions";
import { registerResultTabActions } from "./resultTabActions";
import { SQL_LANGUAGE } from "./sqlLanguage";
import { TABLE_KIND, tableTitle } from "./tableInput";
import { DIAGRAM_KIND, diagramTitle } from "./erDiagram";
import { databaseRequest, projectRequest } from "./requests";
import { nodeTarget, type DbNode } from "./nodes";
import { registerDatabaseTreeActions } from "./treeActions";
@@ -150,12 +149,6 @@ export function activate(): () => void {
// Switching tabs keeps the rows, filters, page and unsubmitted edits without querying again.
keepAlive: true,
}),
registerEditorKind({
kind: DIAGRAM_KIND,
component: lazyComponent(() => import("./DiagramEditor").then((m) => m.DiagramEditor)),
title: diagramTitle,
icon: () => "db-table",
}),
registerOverlay({
id: "database.dialogs",
component: lazyWhen(useDialogOpen, () => import("./Dialogs").then((m) => m.DatabaseDialogs)),
@@ -196,7 +189,6 @@ export function activate(): () => void {
activeResult: null,
selectedSource: null,
selectedNode: null,
selectedNodes: [],
treeExpanded: new Set(),
treeReveal: null,
manualCommit: new Set(),
-167
View File
@@ -1,167 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { getAction } from "@/platform/actions";
import type { DbColumnInfo, DbTableDetails } from "@/platform/ipc";
import { provideEditorService, type EditorInput } from "@/workbench/contributions";
import type { DbNode } from "./nodes";
import { detailsKey, tablesKey, useDatabase } from "./store";
import { registerDatabaseTreeActions } from "./treeActions";
import { nodeMenu } from "./treeMenu";
import type { DiagramData } from "./erDiagram";
const ui = vi.hoisted(() => ({ notify: vi.fn() }));
vi.mock("@/workbench/contributions", async (importOriginal) => {
const actual = await importOriginal<typeof import("@/workbench/contributions")>();
return { ...actual, notifications: () => ({ notify: ui.notify }) };
});
const id = "pg";
const col = (name: string, primaryKey = false): DbColumnInfo => ({
name,
dataType: "integer",
nullable: false,
default: null,
primaryKey,
});
const details = (columns: DbColumnInfo[], refTable?: string): DbTableDetails => ({
columns,
indexes: [],
foreignKeys: refTable
? [{ schema: "public", table: "", columns: [columns[1]!.name], refSchema: "public", refTable, refColumns: ["id"] }]
: [],
triggers: [],
});
const tableNode = (name: string, kind: "table" | "view" = "table"): DbNode => ({
kind: "table",
key: `${id}/public/tables/${name}`,
id,
schema: "public",
table: { name, kind },
});
const schema: DbNode = { kind: "schema", key: `${id}/public`, id, schema: "public" };
const folder = (f: "tables" | "routines"): DbNode => ({
kind: "folder",
key: `${id}/public/${f}`,
id,
schema: "public",
folder: f,
});
const opened = vi.fn<(input: EditorInput) => void>();
const diagram = () => opened.mock.calls.at(-1)?.[0].data as DiagramData | undefined;
const showDiagram = (arg?: DbNode) => getAction("db.showDiagram")!.run({ arg } as never);
let dispose: () => void;
beforeEach(() => {
dispose = registerDatabaseTreeActions();
provideEditorService({ openInput: async (input: EditorInput) => opened(input) } as never);
const tables = ["users", "orders", "audit"];
useDatabase.setState({
sources: [{ id, driver: "postgres" }],
loaded: true,
tables: {
[tablesKey(id, "public")]: {
status: "ok",
value: [...tables.map((name) => ({ name, kind: "table" as const })), { name: "active_users", kind: "view" }],
},
},
details: {
[detailsKey(id, "public", "users")]: { status: "ok", value: details([col("id", true)]) },
[detailsKey(id, "public", "orders")]: { status: "ok", value: details([col("id", true), col("uid")], "users") },
[detailsKey(id, "public", "audit")]: { status: "ok", value: details([col("id"), col("oid")], "orders") },
[detailsKey(id, "public", "active_users")]: { status: "ok", value: details([col("id")]) },
},
selectedNodes: [],
});
});
afterEach(() => {
dispose();
opened.mockReset();
ui.notify.mockReset();
});
const entities = (source: string) => [...source.matchAll(/^ {2}t\d+\["([^"]*)"\]/gm)].map((m) => m[1]);
describe("Diagrams › Show Diagram", () => {
it("is in the Diagrams submenu of tables, schemas and table folders only", () => {
const has = (n: DbNode) =>
nodeMenu(n).some(
(item) =>
"submenu" in item &&
item.label === "Diagrams" &&
item.submenu?.some((s) => "action" in s && s.action === "db.showDiagram"),
);
expect([tableNode("users"), schema, folder("tables"), folder("routines")].map(has)).toEqual([
true,
true,
true,
false,
]);
});
it("shows the selected tables, linked only among themselves", async () => {
const selection = [tableNode("orders"), tableNode("audit")];
useDatabase.setState({ selectedNodes: selection });
await showDiagram(selection[1]);
expect(entities(diagram()!.source)).toEqual(["orders", "audit"]);
expect(diagram()!.source).toContain('t0 ||--o{ t1 : "oid"');
expect(diagram()!.source).not.toContain("users");
});
it("shows only the clicked table when it is outside the selection", async () => {
useDatabase.setState({ selectedNodes: [tableNode("orders"), tableNode("audit")] });
await showDiagram(tableNode("users"));
expect(diagram()).toEqual({ title: "users", source: expect.stringContaining('t0["users"]') });
expect(entities(diagram()!.source)).toEqual(["users"]);
});
it("shows every table of a schema, without its views", async () => {
await showDiagram(schema);
expect(diagram()!.title).toBe("public");
expect(entities(diagram()!.source)).toEqual(["users", "orders", "audit"]);
expect(diagram()!.source.match(/--o\{/g)).toHaveLength(2);
expect(ui.notify).not.toHaveBeenCalled();
});
it("caps a large schema and says so", async () => {
const names = Array.from({ length: 60 }, (_, i) => `t${i}`);
useDatabase.setState({
tables: { [tablesKey(id, "public")]: { status: "ok", value: names.map((name) => ({ name, kind: "table" })) } },
details: Object.fromEntries(
names.map((name) => [detailsKey(id, "public", name), { status: "ok", value: details([col("id")]) }]),
),
});
await showDiagram(schema);
expect(entities(diagram()!.source)).toHaveLength(50);
expect(ui.notify).toHaveBeenCalledWith(
expect.objectContaining({ title: "Showing the first 50 of 60 tables in the diagram" }),
);
});
it("leaves out tables that would take the source past Mermaid's size limit, and says so", async () => {
const names = Array.from({ length: 20 }, (_, i) => `wide_${i}`);
const wide = Array.from({ length: 60 }, (_, i) => ({
...col(`column_with_a_long_name_${i}`),
dataType: "varchar(255)",
}));
useDatabase.setState({
tables: { [tablesKey(id, "public")]: { status: "ok", value: names.map((name) => ({ name, kind: "table" })) } },
details: Object.fromEntries(
names.map((name) => [detailsKey(id, "public", name), { status: "ok", value: details(wide) }]),
),
});
await showDiagram(schema);
const { source } = diagram()!;
const shown = entities(source).length;
expect(source.length).toBeLessThanOrEqual(50_000);
expect(shown).toBeGreaterThan(1);
expect(shown).toBeLessThan(20);
expect(ui.notify).toHaveBeenCalledWith(
expect.objectContaining({ title: `Showing the first ${shown} of 20 tables in the diagram` }),
);
});
it("opens nothing without tables", async () => {
await showDiagram(folder("routines"));
expect(opened).not.toHaveBeenCalled();
});
});
-3
View File
@@ -236,8 +236,6 @@ interface DatabaseState {
selectedSource: string | null;
/** The tree's lead node: what the tree actions act on. */
selectedNode: DbNode | null;
/** Every selected node of the tree, the lead's included (Show Diagram). */
selectedNodes: DbNode[];
/** The toolbar's New popup is open. */
newMenuOpen: boolean;
/** Expanded nodes of the Database tree. */
@@ -304,7 +302,6 @@ export const useDatabase = create<DatabaseState>(() => ({
dialog: null,
selectedSource: null,
selectedNode: null,
selectedNodes: [],
newMenuOpen: false,
treeExpanded: new Set(),
treeReveal: null,
-65
View File
@@ -48,7 +48,6 @@ import {
removeSource,
} from "./store";
import { tableInput } from "./tableInput";
import { DIAGRAM_TABLE_LIMIT, MERMAID_MAX_TEXT, diagramInput, erDiagram, type DiagramTable } from "./erDiagram";
import { dumpScope, mysqlDumpScope } from "./dumpTools";
import { tx } from "@/platform/i18n";
import { chooseItem } from "@/workbench/inputDialogs";
@@ -106,62 +105,6 @@ async function tablesIn(id: string, schema: string): Promise<DbTableInfo[]> {
return l?.status === "ok" ? l.value : [];
}
/** The nodes an action on `arg` runs on: the tree's selection when `arg` is part of it. */
function nodesFrom(arg: unknown): DbNode[] {
const { selectedNodes } = useDatabase.getState();
if (!isNode(arg)) return selectedNodes;
return selectedNodes.some((n) => n.key === arg.key) ? selectedNodes : [arg];
}
/**
* Diagrams › Show Diagram: the selected tables and views, and the tables of
* selected schemas and table folders, in an ER diagram tab.
*/
async function showDiagram(nodes: DbNode[]): Promise<void> {
const refs = new Map<string, { id: string; schema: string; name: string }>();
const add = (id: string, schema: string, name: string) =>
refs.set(detailsKey(id, schema, name), { id, schema, name });
for (const n of nodes) {
if (n.kind === "table") add(n.id, n.schema, n.table.name);
else if (
n.kind === "schema" ||
(n.kind === "folder" && ["tables", "views", "materializedViews"].includes(n.folder))
)
// oxlint-disable-next-line no-await-in-loop -- one schema at a time: its tables load over the same connection
for (const t of await tablesIn(n.id, n.schema))
if (n.kind === "schema" ? t.kind === "table" : tableFolder(t.kind) === n.folder) add(n.id, n.schema, t.name);
}
const all = [...refs.values()];
if (!all.length) return;
const shown = all.slice(0, DIAGRAM_TABLE_LIMIT);
const missing = shown.filter(
(t) => useDatabase.getState().details[detailsKey(t.id, t.schema, t.name)]?.status !== "ok",
);
await Promise.all(missing.map((t) => loadDetails(t.id, t.schema, t.name)));
const { details } = useDatabase.getState();
const tables = shown.flatMap((t): DiagramTable[] => {
const d = details[detailsKey(t.id, t.schema, t.name)];
return d?.status === "ok" ? [{ ...t, details: d.value }] : [];
});
if (!tables.length) return;
// Mermaid draws only an error for a source over its size limit: wide tables leave fewer in the diagram.
let source = erDiagram(tables);
while (source.length > MERMAID_MAX_TEXT && tables.length > 1) {
tables.pop();
source = erDiagram(tables);
}
const [limit, total] = [tables.length, all.length];
if (total > limit)
notifications().notify({
level: "info",
title: tx`Showing the first ${limit} of ${total} tables in the diagram`,
key: "db-diagram-limit",
});
const one = nodes.length === 1 ? nodes[0]! : null;
const title = one?.kind === "table" ? one.table.name : one && "schema" in one ? one.schema : tx("Diagram");
void editorService().openInput(diagramInput({ title, source }), { focus: true });
}
/**
* Connects to `target` before a dump / restore dialog opens (a password prompt would replace
* the dialog) and reads the server's version; `undefined` when the user cancelled.
@@ -665,14 +608,6 @@ export function registerDatabaseTreeActions(): () => void {
if (n?.kind === "foreignKey") void revealInTree(n.id, n.fk.refSchema, n.fk.refTable, "table");
},
}),
tree({
id: "db.showDiagram",
title: "Show Diagram",
description: "Show the selected tables, or the tables of a schema, as an ER diagram linked by foreign keys",
icon: "db-table",
keywords: ["er diagram", "uml", "visualization", "foreign keys", "relationships"],
run: ({ arg }) => showDiagram(nodesFrom(arg)),
}),
tree({
id: "db.new",
title: "New…",
-5
View File
@@ -108,9 +108,6 @@ function importExport(items: MenuItem[]): MenuItem[] {
return items.length ? [{ label: "Import/Export", submenu: items }] : [];
}
/** Diagrams ▸ Show Diagram, of the tree's selection when it holds `n`. */
const diagrams = (n: DbNode): MenuItem => ({ label: "Diagrams", submenu: [act("db.showDiagram", n)] });
/** Context menu of a tree node (`null`: the empty area). */
export function nodeMenu(n: DbNode | null): MenuItem[] {
if (!n) return [{ label: "New", icon: "plus", submenu: newMenu() }];
@@ -201,7 +198,6 @@ export function nodeMenu(n: DbNode | null): MenuItem[] {
sqlScripts(n, false),
...(n.kind === "schema" ? [act("db.compareSchemas", n)] : []),
...importExport(dumpItems(n, true)),
...(n.kind === "schema" || ["tables", "views", "materializedViews"].includes(n.folder) ? [diagrams(n)] : []),
...(n.kind === "schema" ? [sep, drop] : []),
];
case "table":
@@ -233,7 +229,6 @@ export function nodeMenu(n: DbNode | null): MenuItem[] {
navigation([act("db.goToDdl", n)]),
sep,
sqlScripts(n, true),
...(n.kind === "table" ? [diagrams(n)] : []),
...(n.kind === "table" && !view
? [
{
@@ -463,7 +463,6 @@ describe("debugger actions (IDEA parity)", () => {
for (const action of ["debug.toggleBreakpoint", "debug.toggleTemporaryBreakpoint"]) {
for (const line of [1, 2]) {
caret("/p/a.py", "python", "x = 1\n\n \ny = 2", line);
// oxlint-disable-next-line no-await-in-loop -- caret setup and the breakpoint assertion share editor/breakpoint state, so each action must run before the next caret change
await executeAction(action);
}
expect(breakpointsOf("/p/a.py"), action).toHaveLength(0);
+2 -14
View File
@@ -7,12 +7,6 @@ let kotlinFiles = false;
let debugAdapter = "java-debug";
const files: Record<string, string> = {};
let missingTools: string[] = [];
vi.mock("@tauri-apps/api/core", async (original) => ({
...(await original<typeof import("@tauri-apps/api/core")>()),
Channel: class {
onmessage = null;
},
}));
vi.mock("@/platform/ipc", async (orig) => {
const real = await orig<typeof import("@/platform/ipc")>();
const ok = (data: unknown) => Promise.resolve({ status: "ok", data });
@@ -99,7 +93,7 @@ describe("Java debugging (java-debug through jdtls)", () => {
expect(isJavaDebuggable({ ...app, kind: "maven" })).toBe(false);
const l = await javaLaunchConfig(app, "/p");
expect(invoked).toEqual([
["javaResolveLaunch", ["api", false, "automatic", expect.any(Number), expect.anything()]],
["javaResolveLaunch", ["api", false, "automatic", expect.any(Number)]],
["javaDebugAdapter", ["api"]],
["javaDebugServer", ["api"]],
]);
@@ -160,7 +154,6 @@ describe("Java debugging (java-debug through jdtls)", () => {
it("lets java-debug shorten a classpath too long for the OS, as Run does", async () => {
for (const how of ["jarmanifest", "argfile"]) {
shortenCommandLine = how;
// oxlint-disable-next-line no-await-in-loop -- shortenCommandLine is shared module state set per iteration; the assertion must follow the launch that used it
const l = await javaLaunchConfig(app, "/p");
expect(JSON.parse(l.extraJson!).shortenCommandLine).toBe(how);
}
@@ -236,12 +229,8 @@ it.each(["sibling", "/outside/modules"])("debugs from %s with the main class mod
kotlinFiles = false;
for (const module of ["api", undefined]) {
invoked.length = 0;
// oxlint-disable-next-line no-await-in-loop -- invoked is a shared call log reset each iteration; the assertions must follow the matching launch
const launch = await javaLaunchConfig({ ...app, module, cwd }, "/p");
expect(invoked).toContainEqual([
"javaResolveLaunch",
["api", false, "automatic", expect.any(Number), expect.anything()],
]);
expect(invoked).toContainEqual(["javaResolveLaunch", ["api", false, "automatic", expect.any(Number)]]);
expect(invoked).toContainEqual(["javaDebugServer", ["api"]]);
expect(launch.cwd).toBe(cwd.startsWith("/") ? cwd : `/p/${cwd}`);
}
@@ -292,7 +281,6 @@ describe("the debugger for a build tool's JVMs", () => {
try {
for (const missing of [[], ["kotlin-debug-adapter"], ["kotlin-lsp"]]) {
missingTools = missing;
// oxlint-disable-next-line no-await-in-loop -- missingTools is shared state changed per iteration; each assertion must check the matching configuration
expect(await jvmAttachDebuggerReady("app", "/p", retry)).toBe(true);
}
missingTools = ["kotlin-debug-adapter", "kotlin-lsp"];
@@ -15,12 +15,6 @@ const ipc = vi.hoisted(() => ({
debugStop: vi.fn(async () => ({ status: "ok", data: null })),
fsReadDir: vi.fn(async () => ({ status: "ok", data: [] })),
}));
vi.mock("@tauri-apps/api/core", async (original) => ({
...(await original<typeof import("@tauri-apps/api/core")>()),
Channel: class {
onmessage = null;
},
}));
vi.mock("@/platform/ipc", async (original) => {
const real = await original<typeof import("@/platform/ipc")>();
return { ...real, isTauri: () => true, commands: { ...real.commands, ...ipc } };
@@ -8,12 +8,6 @@ const ipc = vi.hoisted(() => ({
javaDebugServer: vi.fn(async () => ({ status: "ok", data: 5005 })),
fsReadDir: vi.fn(async () => ({ status: "ok", data: [] })),
}));
vi.mock("@tauri-apps/api/core", async (original) => ({
...(await original<typeof import("@tauri-apps/api/core")>()),
Channel: class {
onmessage = null;
},
}));
vi.mock("@/platform/ipc", async (importOriginal) => ({
...(await importOriginal<typeof import("@/platform/ipc")>()),
commands: ipc,
@@ -112,7 +112,6 @@ describe("watches while the program runs", () => {
];
for (const [s, visible] of quiet) {
const { result, unmount } = renderHook(() => useLiveWatches(s, ["a"], visible));
// oxlint-disable-next-line no-await-in-loop -- fake timers and the hook under test are per iteration; the assertion and unmount must follow this advance
await act(async () => void (await vi.advanceTimersByTimeAsync(2500)));
expect(result.current).toEqual([]);
unmount();
@@ -73,14 +73,10 @@ it.each([undefined, true, false])(
const show = vi.fn();
provideToolWindowService({ show } as unknown as ToolWindowService);
if (prepared) {
// oxlint-disable-next-line no-await-in-loop -- prepared and direct starts share tool-window/session state; the show assertion must follow this start
await startPreparedSession({ id: "java", name: "Java" } as never, async () => config("launch"), {
show: foreground,
});
} else {
// oxlint-disable-next-line no-await-in-loop -- prepared and direct starts share tool-window/session state; the show assertion must follow this start
await startSession(config("launch"), { show: foreground });
}
} else await startSession(config("launch"), { show: foreground });
if (showOnStart && foreground !== false) expect(show).toHaveBeenCalledWith("debug");
else expect(show).not.toHaveBeenCalled();
}
-2
View File
@@ -13,7 +13,6 @@ import {
type RunId,
} from "@/platform/ipc";
import { downloadJdkActions } from "@/platform/jdk";
import { followLaunchBuild } from "@/features/build/store";
import { useProject } from "@/platform/project";
import { isRemoteWindow } from "@/platform/remote";
import { openExternalUrl } from "@/platform/openUrl";
@@ -384,7 +383,6 @@ async function startJavaConfig(config: RunConfig, root: string, origin: RunConfi
request,
signal,
report,
build: followLaunchBuild(request, tx`Build before launch: ${config.name}`, report),
saveAll: async () => {
await maybeEditorService()?.saveAll();
},
@@ -125,7 +125,6 @@ async function drainBreakpoints() {
while (paths.size) {
for (const timer of timers.values()) clearTimeout(timer);
timers.clear();
// oxlint-disable-next-line no-await-in-loop -- the debounce drain must repeat: syncing can schedule new timers, so the next batch is recomputed only after this one settles
await Promise.all([...paths].map((path) => syncFile(path)));
paths = new Set([...timers.keys(), ...inFlight.keys()]);
}
-2
View File
@@ -183,14 +183,12 @@ export async function evaluateWithImports(
const known = importsOf(sessionId);
for (let round = 0; ; round++) {
try {
// oxlint-disable-next-line no-await-in-loop -- retry loop: the next attempt runs only after this one fails and imports discovered so far are applied
return await run(qualify(expression, known));
} catch (e) {
const names = unresolvedNames(messageOf(e)).filter((name) => !known.has(name));
if (round >= MAX_ROUNDS || !names.length) throw e;
let added = false;
for (const name of names) {
// oxlint-disable-next-line no-await-in-loop -- lookups are processed in name order to keep the first ambiguity and the shared imports map deterministic
const candidates = await find(name).catch(() => []);
if (candidates.length > 1) throw new AmbiguousClassError(name, candidates, messageOf(e));
if (candidates.length === 1) {
Loaded 100 of 206 files, more files were not shown because too many files have changed in this diff. Show more