Compare commits

..
146 changed files with 1147 additions and 5372 deletions

No files matched your search

+1 -1
View File
@@ -51,7 +51,7 @@ async fn run_once(
move || launch.resolve_for_launch_with_copilot_env(&root, strip_ambient)
})
.await
.map_err(|e| e.to_string())??;
.map_err(|e| e.to_string())?;
let cwd = dunce::canonicalize(&root).unwrap_or(root);
let updates = Arc::new(DiscoveryUpdates { provider: spec.id.clone(), ..Default::default() });
let client = Dialect::wrap(updates.clone());
+11 -28
View File
@@ -132,7 +132,6 @@ pub type McpExecutableFn = dyn Fn() -> Option<PathBuf> + Send + Sync;
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
struct CopilotBinaryKey {
command: String,
github_account: Option<String>,
modified: Option<std::time::SystemTime>,
len: Option<u64>,
}
@@ -194,7 +193,6 @@ impl Shared {
let metadata = std::fs::metadata(&executable).ok();
CopilotBinaryKey {
command: executable.to_string_lossy().into_owned(),
github_account: provider::copilot_github_account(&spec.env),
modified: metadata.as_ref().and_then(|m| m.modified().ok()),
len: metadata.as_ref().map(std::fs::Metadata::len),
}
@@ -1128,16 +1126,6 @@ impl AgentManager {
/// Changes a session setting (model, mode…): right away when the agent runs, else when it next starts.
pub async fn set_config(&self, id: &str, option: &str, value: String) -> IdeResult<()> {
let task = self.task(id)?;
let provider = task.state.lock().task.provider.clone();
let discovered = self
.shared
.paths
.catalogs
.cached(&self.shared, &provider)
.config
.iter()
.find(|o| o.id == option && o.category.as_deref() == Some("model"))
.cloned();
let (target, change) = {
let mut s = task.state.lock();
let busy = s.busy;
@@ -1158,19 +1146,17 @@ impl AgentManager {
task.emit_task();
return Ok(());
}
let session_target = s.task.config.iter().find(|o| o.id == option).cloned();
let recovered_model = session_target.is_none();
let target = match session_target {
Some(target) => target,
None if discovered.is_some() => discovered.unwrap(),
None => return Err(IdeError::not_found("no such setting")),
};
let target = s
.task
.config
.iter()
.find(|o| o.id == option)
.ok_or_else(|| IdeError::not_found("no such setting"))?
.clone();
if s.pending_model.is_some() && config::is_per_model_option(&target) {
return Err(IdeError::invalid("This setting is not available on the selected model"));
}
if recovered_model {
(target, None)
} else if !target.values.iter().any(|v| v.value == value) {
if !target.values.iter().any(|v| v.value == value) {
if target.category.as_deref() != Some("model") {
return Err(IdeError::invalid(format!("{} has no value {value}", target.name)));
}
@@ -2813,12 +2799,9 @@ impl Task {
pending_model: Option<&PendingModel>,
) -> Result<Live, SessionOpenError> {
let launch_cwd = cwd.to_path_buf();
let mut spec = tokio::task::spawn_blocking(move || {
spec.resolve_for_launch_with_copilot_env(&launch_cwd, provider::prefer_stored_copilot_auth())
})
.await
.map_err(|e| SessionOpenError { message: e.to_string(), allow_acp_fallback: false })?
.map_err(|e| SessionOpenError { message: e, allow_acp_fallback: false })?;
let mut spec = tokio::task::spawn_blocking(move || spec.resolve_for_launch(&launch_cwd))
.await
.map_err(|e| SessionOpenError { message: e.to_string(), allow_acp_fallback: false })?;
if spec.driver == provider::Driver::Acp && provider::is_copilot_provider(provider_id) {
let mcp_overrides = self.state.lock().task.mcp_overrides.clone();
for name in self.shared.mcp_servers_off_for_session(provider_id, &mcp_overrides) {
+1 -2
View File
@@ -144,8 +144,7 @@ async fn discover_once(spec: ProviderSpec, cwd: PathBuf, strip_ambient: bool) ->
move || spec.resolve_for_launch_with_copilot_env(&cwd, strip_ambient)
})
.await
.map_err(|e| DiscoverError { message: e.to_string(), allow_acp_fallback: false })?
.map_err(|e| DiscoverError { message: e, allow_acp_fallback: false })?;
.map_err(|e| DiscoverError { message: e.to_string(), allow_acp_fallback: false })?;
let cwd = dunce::canonicalize(&cwd).unwrap_or(cwd);
let args = headless_args(&launch.args);
let peer = Peer::spawn_framed(
+2 -14
View File
@@ -312,7 +312,7 @@ impl Settings {
}
/// Parses `models.list` + optional `models.listTokenPriceUnits` into catalog entries,
/// prepending `"auto"` when direct models are present or Copilot advertises an enabled Auto tier.
/// prepending `"auto"` when not already in the list.
pub(super) fn parse_catalog(list: &Value, price_units: Option<&Value>) -> Vec<ModelEntry> {
let units = parse_price_units(price_units);
let raw = list
@@ -322,7 +322,7 @@ pub(super) fn parse_catalog(list: &Value, price_units: Option<&Value>) -> Vec<Mo
.map(Vec::as_slice)
.unwrap_or_default();
let mut out = Vec::new();
if !raw.iter().any(|m| str_of(m, "id") == Some("auto")) && (!raw.is_empty() || auto_model_available(list)) {
if !raw.iter().any(|m| str_of(m, "id") == Some("auto")) && !raw.is_empty() {
out.push(ModelEntry {
id: "auto".into(),
name: "Auto".into(),
@@ -344,18 +344,6 @@ pub(super) fn parse_catalog(list: &Value, price_units: Option<&Value>) -> Vec<Mo
out
}
fn auto_model_available(list: &Value) -> bool {
let Some(auto) = list.get("auto") else { return false };
if auto.get("enabled").or_else(|| auto.pointer("/status/enabled")).and_then(Value::as_bool) == Some(false) {
return false;
}
let Some(tiers) = auto.get("tiers").and_then(Value::as_array) else { return auto.is_object() };
tiers.is_empty()
|| tiers.iter().any(|tier| {
tier.get("enabled").or_else(|| tier.pointer("/status/enabled")).and_then(Value::as_bool) != Some(false)
})
}
fn parse_model(m: &Value, units: &HashMap<String, PriceUnit>) -> Option<ModelEntry> {
let id = str_of(m, "id")?.to_owned();
if m.get("model_picker_enabled").and_then(Value::as_bool) == Some(false)
@@ -110,72 +110,6 @@ fn sample_price_units() -> Value {
})
}
#[test]
fn parses_an_enabled_auto_only_catalog() {
let list = json!({
"models": [],
"auto": {
"defaultTier": "balance",
"tiers": [
{
"id": "balance",
"displayName": "Standard",
"type": "auto",
"fusionTier": "standard",
"status": { "enabled": true, "pickerVisible": true }
},
{
"id": "hydrafusion",
"displayName": "High",
"type": "fusion",
"fusionTier": "high",
"status": {
"enabled": false,
"pickerVisible": true,
"reason": "user_not_eligible"
}
},
{
"id": "fast",
"displayName": "Fast",
"type": "auto",
"status": { "enabled": true, "pickerVisible": false }
}
],
"providerId": "copilot"
},
"imageModels": []
});
let catalog = models::parse_catalog(&list, None);
assert_eq!(catalog.iter().map(|m| m.id.as_str()).collect::<Vec<_>>(), ["auto"]);
assert_eq!(Settings::new(&catalog, &UserDefaults::default()).model, "auto");
let options =
config::parse_options(&models::config_options(&catalog, &Settings::new(&catalog, &UserDefaults::default())));
let model = options.iter().find(|option| option.id == MODEL).unwrap();
assert_eq!(model.current.as_deref(), Some("auto"));
assert_eq!(model.values.iter().map(|value| value.value.as_str()).collect::<Vec<_>>(), ["auto"]);
}
#[test]
fn rejects_an_auto_only_catalog_when_every_tier_is_disabled() {
let list = json!({
"models": [],
"auto": {
"defaultTier": "balance",
"tiers": [
{
"id": "balance",
"status": { "enabled": false, "pickerVisible": true }
}
]
}
});
assert!(models::parse_catalog(&list, None).is_empty());
}
#[test]
fn parses_tiered_context_windows_pricing_and_uses_copilots_own_defaults() {
let catalog = models::parse_catalog(&sample_models_list(), Some(&sample_price_units()));
+2 -129
View File
@@ -9,8 +9,6 @@ use serde_json::Value;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
pub(crate) const COPILOT_GITHUB_ACCOUNT_ENV: &str = "OPENIDEA_COPILOT_GITHUB_ACCOUNT";
/// The protocol an agent speaks. Native ones run behind an in-process ACP endpoint
/// (`native`), so tasks see every agent as ACP and read features from its capabilities.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
@@ -140,31 +138,15 @@ impl ProviderSpec {
/// Resolve once before connecting, so authentication guidance names that same install.
pub(crate) fn resolve_for_launch(self, cwd: &Path) -> Self {
let strip = prefer_stored_copilot_auth();
self.resolve_for_launch_base(cwd, strip)
self.resolve_for_launch_with_copilot_env(cwd, strip)
}
pub(crate) fn resolve_for_launch_with_copilot_env(
self,
cwd: &Path,
strip_ambient_tokens: bool,
) -> Result<Self, String> {
let account = is_copilot_provider(&self.id).then(|| copilot_github_account(&self.env)).flatten();
let mut resolved = self.resolve_for_launch_base(cwd, strip_ambient_tokens || account.is_some());
if let Some(account) = account {
let token = github_token_for_account(&account)?;
resolved.env.retain(|(name, _)| !AMBIENT_COPILOT_AUTH_VARS.contains(&name.as_str()));
resolved.env.push(("COPILOT_GITHUB_TOKEN".into(), token));
}
Ok(resolved)
}
fn resolve_for_launch_base(mut self, cwd: &Path, strip_ambient_tokens: bool) -> Self {
pub(crate) fn resolve_for_launch_with_copilot_env(mut self, cwd: &Path, strip_ambient_tokens: bool) -> Self {
if self.driver != Driver::Acp {
self.command = crate::native::newest_install(&self.command);
}
if is_copilot_provider(&self.id) {
self.env = sanitized_copilot_env(&self.env, strip_ambient_tokens);
self.env.retain(|(name, _)| name != COPILOT_GITHUB_ACCOUNT_ENV);
}
let program = ide_jsonrpc::resolve_spawn_program(&self.command, &self.env);
self.command =
@@ -182,50 +164,6 @@ pub(crate) fn is_copilot_provider(id: &str) -> bool {
id == "copilot" || id.starts_with("copilot-")
}
pub(crate) fn copilot_github_account(env: &[(String, String)]) -> Option<String> {
env.iter()
.rev()
.find(|(name, _)| name == COPILOT_GITHUB_ACCOUNT_ENV)
.map(|(_, value)| value.trim())
.filter(|value| !value.is_empty())
.map(str::to_owned)
}
fn github_token_for_account(account: &str) -> Result<String, String> {
let path = ide_core::process::shell_env()
.find(|(name, _)| name == "PATH")
.map(|(_, value)| value)
.or_else(|| ide_core::process::host_var_os("PATH"));
let program = path
.as_deref()
.and_then(|path| ide_core::process::find_executable("gh", path))
.ok_or_else(|| "GitHub CLI (`gh`) is required to select a Copilot GitHub account".to_owned())?;
let mut command = std::process::Command::new(program);
command.args(["auth", "token", "--hostname", "github.com", "--user", account]).envs(ide_core::process::shell_env());
for name in AMBIENT_COPILOT_AUTH_VARS {
command.env_remove(name);
}
let output = command
.output()
.map_err(|error| format!("Couldn't read GitHub authentication for account {account}: {error}"))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
let detail = stderr.trim();
return Err(if detail.is_empty() {
format!("GitHub CLI has no authenticated account named {account}")
} else {
format!("Couldn't use GitHub account {account}: {detail}")
});
}
let token = String::from_utf8(output.stdout)
.map_err(|_| format!("GitHub CLI returned a non-text token for account {account}"))?;
let token = token.trim();
if token.is_empty() {
return Err(format!("GitHub CLI returned no token for account {account}"));
}
Ok(token.to_owned())
}
pub(crate) fn prefer_stored_copilot_auth() -> bool {
PREFER_STORED_COPILOT_AUTH.load(std::sync::atomic::Ordering::Acquire)
}
@@ -401,31 +339,6 @@ pub(crate) fn set_builtin_env(
id: &str,
env: BTreeMap<String, String>,
) -> IdeResult<()> {
if id == "copilot" {
let file = custom_dir.join("copilot.toml");
if file.try_exists()?
&& let mut agent = CustomAgent::read_with(&file, id, secrets).map_err(IdeError::invalid)?
&& agent.registry.is_some()
{
let existing = agent.env.clone();
let mut existing_launch_env = existing.clone();
let mut next_launch_env = env.clone();
existing_launch_env.remove(COPILOT_GITHUB_ACCOUNT_ENV);
next_launch_env.remove(COPILOT_GITHUB_ACCOUNT_ENV);
if existing_launch_env != next_launch_env {
return Err(IdeError::invalid(format!("{id} is installed from the ACP Registry")));
}
match env.get(COPILOT_GITHUB_ACCOUNT_ENV).filter(|value| !value.trim().is_empty()) {
Some(account) => {
agent.env.insert(COPILOT_GITHUB_ACCOUNT_ENV.into(), account.trim().into());
}
None => {
agent.env.remove(COPILOT_GITHUB_ACCOUNT_ENV);
}
}
return agent.write(&file).map_err(Into::into);
}
}
update_builtin(custom_dir, secrets, id, |agent, _| agent.env = env)
}
@@ -1042,46 +955,6 @@ mod tests {
set_builtin_env(dir.path(), None, "not-a-builtin", env).unwrap_err();
}
#[test]
fn registry_copilot_allows_only_the_github_account_override() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("copilot.toml");
CustomAgent {
name: Some("GitHub Copilot".into()),
driver: Driver::Acp,
command: "/tools/copilot".into(),
args: vec!["--acp".into()],
env: BTreeMap::from([("REGISTRY_SETTING".into(), "kept".into())]),
registry: Some(RegistryRef { id: "copilot".into(), version: "1.0.0".into() }),
}
.write(&file)
.unwrap();
set_builtin_env(
dir.path(),
None,
"copilot",
BTreeMap::from([
("REGISTRY_SETTING".into(), "kept".into()),
(COPILOT_GITHUB_ACCOUNT_ENV.into(), "dengliu_microsoft".into()),
]),
)
.unwrap();
let spec = load(Some(dir.path()), None).into_iter().find(|spec| spec.id == "copilot").unwrap();
assert_eq!(copilot_github_account(&spec.env).as_deref(), Some("dengliu_microsoft"));
set_builtin_env(dir.path(), None, "copilot", BTreeMap::from([("REGISTRY_SETTING".into(), "changed".into())]))
.unwrap_err();
}
#[test]
fn launch_metadata_never_passes_the_github_account_control_to_copilot() {
let mut spec = builtin_spec("copilot").unwrap();
spec.env.push((COPILOT_GITHUB_ACCOUNT_ENV.into(), "dengliu_microsoft".into()));
let resolved = spec.resolve_for_launch(Path::new("."));
assert!(resolved.env.iter().all(|(name, _)| name != COPILOT_GITHUB_ACCOUNT_ENV));
}
#[test]
fn acp_adapters_of_native_agents_are_unlisted_until_customized() {
let dir = tempfile::tempdir().unwrap();
-8
View File
@@ -537,14 +537,6 @@ fn install_entry_with(
return Err(e);
}
};
let github_account = (entry.id == "copilot")
.then(|| CustomAgent::read(&file).ok())
.flatten()
.and_then(|agent| agent.env.get(provider::COPILOT_GITHUB_ACCOUNT_ENV).cloned());
let mut env = env;
if let Some(account) = github_account {
env.insert(provider::COPILOT_GITHUB_ACCOUNT_ENV.into(), account);
}
let agent = CustomAgent {
name: Some(entry.name.clone()),
driver: Driver::Acp,
-50
View File
@@ -2333,56 +2333,6 @@ async fn idle_model_switches_discover_controls_and_no_control_models_without_ano
restored.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn session_without_a_model_option_can_select_from_a_recovered_catalog() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
*agent.model_options.lock() = HashMap::from([
("big".into(), effort_options(&["low", "high"], "high")),
("small".into(), effort_options(&["minimal", "medium"], "minimal")),
]);
let mgr = manager(tmp.path(), agent);
let task = mgr
.create(NewAgentTask {
prompt: text("again"),
provider: "claude-acp".into(),
isolation: Isolation::Local,
..Default::default()
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let spec = mgr.shared.spec("claude-acp").unwrap();
let (_, flight) = mgr.shared.paths.catalogs.request(&mgr.shared, spec, true, None);
if let Some(mut ready) = flight {
tokio::time::timeout(Duration::from_secs(5), async {
while !*ready.borrow_and_update() {
ready.changed().await.unwrap();
}
})
.await
.unwrap();
}
{
let task = mgr.task(&task.id).unwrap();
let mut state = task.state.lock();
state.task.config.retain(|option| option.category.as_deref() != Some("model"));
state.task.model = Some("stale-model".into());
}
mgr.set_config(&task.id, "model", "small".into()).await.unwrap();
let task = mgr.task(&task.id).unwrap();
{
let state = task.state.lock();
assert_eq!(state.task.model.as_deref(), Some("small"));
let model = state.task.config.iter().find(|option| option.category.as_deref() == Some("model")).unwrap();
assert_eq!(model.current.as_deref(), Some("small"));
assert!(model.values.iter().any(|value| value.value == "small"));
}
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn idle_model_discovery_failure_restores_the_previous_choice_without_claiming_no_controls() {
let tmp = tempfile::tempdir().unwrap();
+11 -88
View File
@@ -2020,25 +2020,11 @@ fn property_target(text: &str, path: &Path, name: &str, local_repo: Option<PathB
label: name.clone(),
});
}
// Built-in coordinates (`project.artifactId`, and the bare `@artifactId@`
// shorthand resource filtering resolves the same way): the POM's own element,
// else the first ancestor declaring one. Any other name under `project.` is a
// custom property (`project.port`, `project.servlet.path`), which the
// `<properties>` lookup below resolves.
let built_in = match name.strip_prefix("project.") {
Some(key) if matches!(key, "groupId" | "artifactId" | "version" | "packaging" | "name") => Some(key),
// `project.basedir`, `project.build.directory`… have no element of their own.
Some(_) => None,
None if matches!(name.as_str(), "groupId" | "artifactId" | "version" | "packaging" | "name") => {
// The bare shorthand of a built-in; a custom property of that name wins.
if let Some(found) = properties_target(&chain, &name, &resolver) {
return Some(found);
}
Some(name.as_str())
// Built-in coordinates: the POM's own element, else the first ancestor declaring one.
if let Some(key) = name.strip_prefix("project.") {
if !matches!(key, "groupId" | "artifactId" | "version" | "packaging" | "name") {
return None; // `project.basedir`, `project.build.directory`… have no element.
}
None => None,
};
if let Some(key) = built_in {
for (p, text) in &chain {
let Some(root) = xml::parse(text).filter(|e| e.name == "project") else { continue };
let Some(e) = root.child(key).filter(|e| !e.text.trim().is_empty()) else { continue };
@@ -2051,34 +2037,30 @@ fn property_target(text: &str, path: &Path, name: &str, local_repo: Option<PathB
}
return None;
}
properties_target(&chain, &name, &resolver)
}
/// A property of `<properties>`: the first POM of the chain (child-first) that
/// declares it, at project level or in an active profile.
fn properties_target(chain: &[(PathBuf, String)], name: &str, resolver: &Resolver) -> Option<PomGoto> {
for (p, text) in chain {
// A property of `<properties>`: the first POM of the chain (child-first) that
// declares it, at project level or in an active profile.
for (p, text) in &chain {
let Some(root) = xml::parse(text).filter(|e| e.name == "project") else { continue };
let active: Vec<String> = parse_pom(text)
.map(|pom| resolver.active(&pom.profiles).map(|pr| pr.id.clone()).collect())
.unwrap_or_default();
// Project level first, then the first active profile declaring the property.
let e = root.child("properties").and_then(|props| props.child(name)).or_else(|| {
let e = root.child("properties").and_then(|props| props.child(&name)).or_else(|| {
root.list("profiles", "profile")
.into_iter()
.find(|profile| {
active.contains(&profile.child("id").map(|id| id.text.trim().to_owned()).unwrap_or_default())
&& profile.child("properties").and_then(|props| props.child(name)).is_some()
&& profile.child("properties").and_then(|props| props.child(&name)).is_some()
})?
.child("properties")?
.child(name)
.child(&name)
});
if let Some(e) = e {
return Some(PomGoto {
path: p.clone(),
range: range_of(text, e),
kind: PomGotoKind::Property,
label: name.to_owned(),
label: name.clone(),
});
}
}
@@ -3104,65 +3086,6 @@ mod tests {
assert_eq!(goto.range, Range::new(pos_at(&text, from), pos_at(&text, to)));
}
#[test]
fn a_custom_project_property_is_found_like_a_plain_one() {
let text = format!(
r#"{CHILD_HEADER}<properties>
<project.port>8001</project.port>
</properties>
<dependencies>
<dependency>
<groupId>com.example</groupId>
<artifactId>lib</artifactId>
<version>${{project.port}}</version>
</dependency>
</dependencies>
</project>"#
);
let path = Path::new("/tmp/pom.xml");
let goto = goto_declaration(&text, path, at(&text, "${project.port}"), None).unwrap();
assert_eq!(goto.kind, PomGotoKind::Property);
assert_eq!(goto.label, "project.port");
assert_eq!(goto.path, path);
let from = text.find("<project.port>").unwrap();
let to = text.find("</project.port>").unwrap() + "</project.port>".len();
assert_eq!(goto.range, Range::new(pos_at(&text, from), pos_at(&text, to)));
// `${project.basedir}` has no element and no custom property: still nothing.
let basedir = text.replace("${project.port}", "${project.basedir}");
assert_eq!(goto_declaration(&basedir, path, at(&basedir, "${project.basedir}"), None), None);
}
#[test]
fn the_bare_builtin_shorthand_resolves_to_the_coordinate_and_a_custom_property_wins() {
let text = format!(
r#"{CHILD_HEADER}<artifactId>app</artifactId>
<dependencies>
<dependency>
<groupId>com.example</groupId>
<artifactId>lib</artifactId>
</dependency>
</dependencies>
<properties>
<groupId>custom</groupId>
</properties>
<description>${{artifactId}}-${{groupId}} docs</description>
</project>"#
);
let path = Path::new("/tmp/pom.xml");
// `@artifactId@` in a filtered resource resolves to the own coordinate.
let goto = goto_declaration(&text, path, at(&text, "${artifactId}"), None).unwrap();
assert_eq!(goto.label, "artifactId");
let from = text.find("<artifactId>app").unwrap();
assert_eq!(goto.range.start, pos_at(&text, from));
// A custom property of the bare name wins over the shorthand. The click
// sits inside the reference: the second one's `$` is behind the first's
// closing `}`, which `property_ref_at` does not take for the `$` itself.
let goto = goto_declaration(&text, path, at(&text, "groupId} docs"), None).unwrap();
assert_eq!(goto.label, "groupId");
let from = text.find("<groupId>custom").unwrap();
assert_eq!(goto.range.start, pos_at(&text, from));
}
#[test]
fn an_inherited_property_reference_finds_its_definition_in_the_parent_pom() {
let tmp = tempfile::tempdir().unwrap();
-3
View File
@@ -176,8 +176,6 @@ pub struct CommitSettings {
pub agent_model: String,
/// That model's thinking level for commit messages; empty keeps the agent's.
pub agent_effort: String,
/// Show the Generate Commit Message with Agent button above the commit message.
pub agent_button: bool,
}
impl Default for CommitSettings {
@@ -203,7 +201,6 @@ impl Default for CommitSettings {
agent: String::new(),
agent_model: String::new(),
agent_effort: String::new(),
agent_button: true,
}
}
}
-8
View File
@@ -749,14 +749,6 @@ impl Pool {
}
/// The keep-alive ping (Oracle needs a FROM clause).
/// Keep-alive: one cheap round trip on the session.
pub async fn ping(&self) -> IdeResult<()> {
match self {
Pool::Jdbc(p) => p.ping().await,
_ => self.rows(self.ping_sql(), 1).await.map(|_| ()),
}
}
pub fn ping_sql(&self) -> &'static str {
match self {
Pool::Oracle(_) => "SELECT 1 FROM DUAL",
+1 -91
View File
@@ -5,7 +5,6 @@ use crate::{DataSource, DbManager, QueryResult, ResultColumn};
use ide_core::{CancellationToken, IdeError, IdeResult};
use serde::{Deserialize, Serialize};
use specta::Type;
use std::collections::HashMap;
use std::io::{Cursor, Read};
use std::path::{Path, PathBuf};
use std::process::Stdio;
@@ -459,44 +458,6 @@ impl JdbcPool {
}
async fn request(&self, fields: &[&str], sql: &str, cancel: &CancellationToken) -> IdeResult<QueryResult> {
let result = self.exchange_once(fields, sql, cancel).await;
if let Err(e) = &result
&& fields.first() != Some(&"open")
&& e.kind != ide_core::error::ErrorKind::Cancelled
&& !self.is_closed()
&& !self.session_valid().await
{
// The session is gone (a proxy or tunnel dropped the idle TCP connection): close the
// pool so the next statement or Connect starts a new one instead of failing forever.
self.close().await;
}
result
}
/// Keep-alive: checks the session (any SQL would be dialect-specific) and closes a dead one.
pub(crate) async fn ping(&self) -> IdeResult<()> {
if self.session_valid().await {
return Ok(());
}
self.close().await;
Err(IdeError::new(ide_core::error::ErrorKind::Io, "JDBC connection was lost"))
}
/// Whether the JDBC session still works, asked after a failed statement.
async fn session_valid(&self) -> bool {
if self.bridge.lock().await.is_none() {
return false;
}
let cancel = CancellationToken::new();
match tokio::time::timeout(Duration::from_secs(10), self.exchange_once(&["valid"], "", &cancel)).await {
Ok(Ok(result)) => {
result.rows.first().and_then(|row| row.first()).cloned().flatten().as_deref() != Some("false")
}
Ok(Err(_)) | Err(_) => false,
}
}
async fn exchange_once(&self, fields: &[&str], sql: &str, cancel: &CancellationToken) -> IdeResult<QueryResult> {
let mut slot = tokio::select! {
biased;
() = cancel.cancelled() => return Err(IdeError::cancelled()),
@@ -601,26 +562,14 @@ fn decode(data: &[u8], sql: &str, elapsed_ms: f64) -> IdeResult<QueryResult> {
impl DbManager {
pub(crate) async fn jdbc_completion(&self, id: &str, pool: &JdbcPool) -> IdeResult<crate::CompletionModel> {
let mut tables = vec![];
let mut column_count = 0;
let schemas = self.schemas(id).await?;
for schema in &schemas {
// Columns of the whole namespace in one call; a driver that refuses it still completes tables.
let mut columns = if column_count < crate::MAX_META_ROWS {
pool.metadata(&["schemaColumns", schema]).await.map(schema_columns).unwrap_or_else(|e| {
tracing::warn!("JDBC columns of {schema}: {}", e.message);
HashMap::new()
})
} else {
HashMap::new()
};
for table in self.tables(id, schema).await? {
let columns = columns.remove(&table.name).unwrap_or_default();
column_count += columns.len();
tables.push(crate::CompletionTable {
schema: schema.clone(),
name: table.name,
kind: table.kind,
columns,
columns: vec![],
});
if tables.len() >= crate::MAX_META_ROWS {
break;
@@ -645,49 +594,10 @@ impl DbManager {
}
}
/// The bridge's `schemaColumns` rows (table, name, type, nullable, default) by table.
fn schema_columns(rows: Vec<Vec<Option<String>>>) -> HashMap<String, Vec<crate::CompletionColumn>> {
let mut by_table: HashMap<String, Vec<crate::CompletionColumn>> = HashMap::new();
for row in rows {
let mut it = row.into_iter();
let (Some(Some(table)), Some(Some(name))) = (it.next(), it.next()) else { continue };
let data_type = it.next().flatten().unwrap_or_default();
let nullable = it.next().flatten().as_deref() != Some("0");
let has_default = it.next().flatten().is_some();
by_table.entry(table).or_default().push(crate::CompletionColumn {
name,
data_type,
nullable,
primary_key: false,
has_default,
});
}
by_table
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn schema_columns_group_by_table() {
let row = |t: &str, n: &str, null: &str, def: Option<&str>| {
vec![Some(t.into()), Some(n.into()), Some("INT".into()), Some(null.into()), def.map(Into::into)]
};
let by_table = schema_columns(vec![
row("orders", "id", "0", None),
row("orders", "note", "1", Some("'none'")),
row("items", "sku", "1", None),
vec![None, Some("orphan".into())],
]);
let orders = &by_table["orders"];
assert_eq!(orders.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["id", "note"]);
assert_eq!((orders[0].nullable, orders[0].has_default), (false, false));
assert_eq!((orders[1].nullable, orders[1].has_default), (true, true));
assert_eq!(by_table["items"].len(), 1);
assert_eq!(by_table.len(), 2);
}
#[tokio::test]
async fn frame_codec_checks_both_16_mib_boundaries() {
assert_eq!(encode(7, &["a"]).unwrap(), [0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 1, 0, 0, 0, 1, b'a']);
+7 -12
View File
@@ -379,8 +379,8 @@ pub(crate) fn keep_alive(pool: &Arc<Pool>, every: Duration) {
loop {
tick.tick().await;
let Some(p) = pool.upgrade().filter(|p| !p.is_closed()) else { break };
if let Err(e) = p.ping().await {
tracing::info!("keep-alive: {}", e.message);
if let Err(e) = p.rows(p.ping_sql(), 1).await {
tracing::debug!("keep-alive: {}", e.message);
}
}
});
@@ -847,12 +847,12 @@ impl DbManager {
}
pub fn is_connected(&self, id: &str) -> bool {
self.pools.lock().get(id).is_some_and(|p| !p.is_closed())
self.pools.lock().contains_key(id)
}
/// Connected targets (data source ids, `<id>:<database>`).
pub fn connected(&self) -> Vec<String> {
self.pools.lock().iter().filter(|(_, p)| !p.is_closed()).map(|(id, _)| id.clone()).collect()
self.pools.lock().keys().cloned().collect()
}
/// The pool of target `id`, connecting first if needed.
@@ -862,13 +862,8 @@ impl DbManager {
if self.tunnels.lock().get(source_id).is_some_and(|t| t.is_closed()) {
self.disconnect_source(source_id).await;
}
let cached = self.pools.lock().get(id).cloned();
if let Some(p) = cached {
if !p.is_closed() {
return Ok(p);
}
// The connection broke (a custom JDBC session whose TCP connection was dropped): reconnect.
self.disconnect(id).await;
if let Some(p) = self.pools.lock().get(id) {
return Ok(p.clone());
}
let source = self.source(id)?;
let password = self.password(&source).await;
@@ -922,7 +917,7 @@ impl DbManager {
/// Disconnects every database of data source `id`.
pub async fn disconnect_source(&self, id: &str) {
let targets: Vec<String> = self.pools.lock().keys().filter(|t| split_target(t).0 == id).cloned().collect();
let targets: Vec<String> = self.connected().into_iter().filter(|t| split_target(t).0 == id).collect();
for t in targets {
self.disconnect(&t).await;
}
+1 -37
View File
@@ -90,10 +90,7 @@ async fn duckdb_custom_driver_through_database_manager() -> IdeResult<()> {
assert!(result.has_more);
assert_eq!(result.rows, vec![vec![Some("1".into()), None]]);
assert_eq!(result.columns[1].name, "label");
let completion = db.completion("test").await?;
assert_eq!(completion.default_schema, "main");
let items = completion.tables.iter().find(|t| t.schema == "main" && t.name == "items").expect("items");
assert_eq!(items.columns.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["id", "label"]);
assert_eq!(db.completion("test").await?.default_schema, "main");
db.execute("test", "create temporary table session_marker as select 42 as id", 1, &c).await?;
let stop = CancellationToken::new();
let (cancelled, ()) =
@@ -216,36 +213,3 @@ async fn unresponsive_driver_closes_before_reconnect() -> IdeResult<()> {
db.disconnect("test").await;
Ok(())
}
#[tokio::test]
#[ignore = "requires JDBC_FIXTURE_JAR (java/jdbc-bridge/build.py --test --out fixture.jar) and Java 17+"]
async fn a_lost_session_reconnects_on_the_next_statement() -> IdeResult<()> {
let tmp = tempfile::tempdir()?;
let db = manager(tmp.path());
db.save_jdbc_driver(DbJdbcDriver {
id: "fixture".into(),
name: "Fixture".into(),
jars: vec![std::env::var("JDBC_FIXTURE_JAR").unwrap()],
class_name: "ai.openidea.jdbc.SelfTest$Fixture".into(),
url_template: String::new(),
})?;
let source = DataSource {
id: "test".into(),
name: "Fixture".into(),
driver: DbDriver::Jdbc,
global: true,
jdbc_driver: "fixture".into(),
url: "jdbc:fixture:".into(),
..Default::default()
};
db.save_sources(vec![source]).await?;
let cancel = CancellationToken::new();
db.execute("test", "first", 1, &cancel).await?;
// The fixture's session reports itself invalid after "drop", like a connection a proxy reset.
assert!(db.execute("test", "drop", 1, &cancel).await.unwrap_err().message.contains("connection reset"));
assert!(!db.is_connected("test"), "a lost session is no longer listed as connected");
assert_eq!(db.execute("test", "after reconnect", 1, &cancel).await?.affected, Some(1.0));
assert!(db.is_connected("test"));
db.disconnect("test").await;
Ok(())
}
+9 -382
View File
@@ -7,10 +7,9 @@
use crate::{
COMPOSE_DIR, COMPOSE_FILES, COMPOSE_PROJECT, COMPOSE_SERVICE, ContainerOp, DockerAvailability, DockerContainer,
DockerEndpoint, DockerImage, DockerImageLayer, DockerLogLine, DockerNetwork, DockerObject, DockerProcessList,
DockerSnapshot, DockerVolume, split_csv,
DockerEndpoint, DockerImage, DockerNetwork, DockerObject, DockerSnapshot, DockerVolume, split_csv,
};
use ide_core::{CancellationToken, IdeError, IdeResult};
use ide_core::{IdeError, IdeResult};
use serde::Deserialize;
use std::collections::BTreeMap;
use std::io::{Read, Write};
@@ -194,15 +193,9 @@ fn request(addr: &Address, method: &str, path: &str, timeout: Duration) -> IdeRe
read_response(&mut conn)
}
/// A response's status line and body framing.
struct Head {
status: u16,
chunked: bool,
length: Option<usize>,
}
/// Reads an HTTP/1.1 response head until `\r\n\r\n`.
fn read_head(stream: &mut impl Read) -> IdeResult<Head> {
/// Reads an HTTP/1.1 response: head until `\r\n\r\n`, then the body per its
/// framing (chunked, `Content-Length`, or until the connection closes).
fn read_response(stream: &mut impl Read) -> IdeResult<Response> {
let mut head: Vec<u8> = Vec::new();
let mut byte = [0u8; 1];
loop {
@@ -235,27 +228,16 @@ fn read_head(stream: &mut impl Read) -> IdeResult<Head> {
length = value.parse().ok();
}
}
Ok(Head { status, chunked, length })
}
/// Reads an HTTP/1.1 response: its head, then the body per its framing
/// (chunked, `Content-Length`, or until the connection closes).
fn read_response(stream: &mut impl Read) -> IdeResult<Response> {
let head = read_head(stream)?;
let body = read_body(stream, &head)?;
Ok(Response { status: head.status, body })
}
fn read_body(stream: &mut impl Read, head: &Head) -> IdeResult<Vec<u8>> {
Ok(if head.chunked {
let body = if chunked {
read_chunked(stream)?
} else if let Some(n) = head.length {
} else if let Some(n) = length {
read_exact_n(stream, n)?
} else {
let mut body = Vec::new();
stream.read_to_end(&mut body)?;
body
})
};
Ok(Response { status, body })
}
/// Reads one `\n`-terminated line (returned without it).
@@ -500,292 +482,6 @@ pub(crate) fn inspect(
})())
}
/// The processes running in a container (`docker top`).
pub(crate) fn container_top(ep: &DockerEndpoint, id: &str, timeout: Duration) -> Option<IdeResult<DockerProcessList>> {
let addr = address(ep)?;
Some((|| {
let body = check(request(&addr, "GET", &format!("/containers/{}/top", path_segment(id)), timeout)?)?;
serde_json::from_str::<ApiTop>(&body)
.map(|t| DockerProcessList { titles: t.titles, processes: t.processes })
.map_err(|e| IdeError::internal(format!("the Docker daemon's process list is not JSON: {e}")))
})())
}
#[derive(Deserialize, Default)]
#[serde(rename_all = "PascalCase", default)]
struct ApiTop {
titles: Vec<String>,
processes: Vec<Vec<String>>,
}
/// An image's layers, newest first (`docker image history`).
pub(crate) fn image_history(
ep: &DockerEndpoint,
id: &str,
timeout: Duration,
) -> Option<IdeResult<Vec<DockerImageLayer>>> {
let addr = address(ep)?;
Some((|| {
let body = check(request(&addr, "GET", &format!("/images/{}/history", path_segment(id)), timeout)?)?;
let layers = serde_json::from_str::<Vec<ApiLayer>>(&body)
.map_err(|e| IdeError::internal(format!("the Docker daemon's image history is not JSON: {e}")))?;
Ok(map_layers(layers, unix_now()))
})())
}
#[derive(Deserialize, Default)]
#[serde(rename_all = "PascalCase", default)]
struct ApiLayer {
id: String,
created: i64,
created_by: String,
size: i64,
comment: String,
}
fn map_layers(layers: Vec<ApiLayer>, now: i64) -> Vec<DockerImageLayer> {
layers
.into_iter()
.map(|l| DockerImageLayer {
id: l.id,
created_by: l.created_by,
size: human_size(l.size),
created_since: human_duration((now - l.created).max(0)),
created_at: unix_utc(l.created),
comment: l.comment,
})
.collect()
}
fn unix_now() -> i64 {
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0)
}
/// How often a log stream that has nothing to read checks for cancellation.
const LOG_POLL: Duration = Duration::from_millis(200);
#[derive(Deserialize, Default)]
#[serde(rename_all = "PascalCase", default)]
struct ApiContainerInspect {
config: ApiContainerConfig,
}
#[derive(Deserialize, Default)]
#[serde(rename_all = "PascalCase", default)]
struct ApiContainerConfig {
tty: bool,
}
/// Streams a container's logs (`tail` last lines, then follows while `follow`)
/// from `ep`'s daemon until they end or `cancel` fires.
#[allow(clippy::too_many_arguments)]
pub(crate) fn logs(
ep: &DockerEndpoint,
id: &str,
tail: u32,
follow: bool,
timestamps: bool,
timeout: Duration,
cancel: &CancellationToken,
on_line: &dyn Fn(DockerLogLine),
) -> Option<IdeResult<()>> {
let addr = address(ep)?;
Some((|| {
// A TTY container's log is one raw stream; otherwise it is framed per stream.
let body = check(request(&addr, "GET", &format!("/containers/{}/json", path_segment(id)), timeout)?)?;
let tty = serde_json::from_str::<ApiContainerInspect>(&body).map(|c| c.config.tty).unwrap_or(false);
let path = format!(
"/containers/{}/logs?stdout=1&stderr=1&tail={tail}&follow={}&timestamps={}",
path_segment(id),
u8::from(follow),
u8::from(timestamps),
);
let mut conn = Conn::connect(&addr, timeout)?;
conn.write_all(
format!("GET {path} HTTP/1.1\r\nHost: docker\r\nUser-Agent: openidea\r\nConnection: close\r\n\r\n")
.as_bytes(),
)?;
let head = read_head(&mut conn)?;
if !(200..300).contains(&head.status) {
let body = read_body(&mut conn, &head)?;
check(Response { status: head.status, body })?;
}
conn.set_timeouts(LOG_POLL);
let mut decoder = LogDecoder::new(&head, tty);
let mut buf = [0u8; 8192];
while !decoder.done() {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
match conn.read(&mut buf) {
Ok(0) => break,
Ok(n) => decoder.feed(&buf[..n], &mut |line| on_line(line))?,
Err(e)
if matches!(
e.kind(),
std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut | std::io::ErrorKind::Interrupted
) => {}
Err(e) => return Err(e.into()),
}
}
decoder.finish(&mut |line| on_line(line));
Ok(())
})())
}
/// Turns a log response body, as it arrives, into lines: undoes the chunked
/// transfer encoding, then the per-stream frames (8-byte header: stream, 3 zero
/// bytes, big-endian length) unless the container has a TTY.
struct LogDecoder {
body: BodyFraming,
tty: bool,
header: Vec<u8>,
frame_left: usize,
frame_stderr: bool,
/// Partial lines of stdout and stderr.
partial: [Vec<u8>; 2],
}
enum BodyFraming {
Chunked { state: ChunkState, line: Vec<u8> },
Length(usize),
Close,
}
#[derive(Clone, Copy, PartialEq)]
enum ChunkState {
Size,
Data(usize),
DataEnd,
Trailer,
Done,
}
impl LogDecoder {
fn new(head: &Head, tty: bool) -> Self {
let body = if head.chunked {
BodyFraming::Chunked { state: ChunkState::Size, line: Vec::new() }
} else if let Some(n) = head.length {
BodyFraming::Length(n)
} else {
BodyFraming::Close
};
Self { body, tty, header: Vec::new(), frame_left: 0, frame_stderr: false, partial: [Vec::new(), Vec::new()] }
}
fn done(&self) -> bool {
matches!(self.body, BodyFraming::Chunked { state: ChunkState::Done, .. } | BodyFraming::Length(0))
}
fn feed(&mut self, mut bytes: &[u8], emit: &mut dyn FnMut(DockerLogLine)) -> IdeResult<()> {
let mut payload = Vec::new();
match &mut self.body {
BodyFraming::Close => payload.extend_from_slice(bytes),
BodyFraming::Length(left) => {
let take = (*left).min(bytes.len());
payload.extend_from_slice(&bytes[..take]);
*left -= take;
}
BodyFraming::Chunked { state, line } => {
while !bytes.is_empty() {
match *state {
ChunkState::Done => break,
ChunkState::Data(n) => {
let take = n.min(bytes.len());
payload.extend_from_slice(&bytes[..take]);
bytes = &bytes[take..];
*state = if take == n { ChunkState::DataEnd } else { ChunkState::Data(n - take) };
}
_ => {
let b = bytes[0];
bytes = &bytes[1..];
if b != b'\n' {
if b != b'\r' {
line.push(b);
}
continue;
}
let text = String::from_utf8_lossy(line).into_owned();
line.clear();
*state = match *state {
ChunkState::Size => {
let size = text.split(';').next().unwrap_or_default().trim();
match usize::from_str_radix(size, 16) {
Ok(0) => ChunkState::Trailer,
Ok(n) => ChunkState::Data(n),
Err(_) => {
return Err(IdeError::internal(
"the Docker daemon answered with a malformed chunked response",
));
}
}
}
ChunkState::DataEnd => ChunkState::Size,
_ if text.is_empty() => ChunkState::Done,
other => other,
};
}
}
}
}
}
self.frames(&payload, emit);
Ok(())
}
fn frames(&mut self, mut bytes: &[u8], emit: &mut dyn FnMut(DockerLogLine)) {
if self.tty {
self.lines(false, bytes, emit);
return;
}
while !bytes.is_empty() {
if self.frame_left == 0 {
let take = (8 - self.header.len()).min(bytes.len());
self.header.extend_from_slice(&bytes[..take]);
bytes = &bytes[take..];
if self.header.len() == 8 {
self.frame_stderr = self.header[0] == 2;
self.frame_left =
u32::from_be_bytes([self.header[4], self.header[5], self.header[6], self.header[7]]) as usize;
self.header.clear();
}
continue;
}
let take = self.frame_left.min(bytes.len());
self.lines(self.frame_stderr, &bytes[..take], emit);
self.frame_left -= take;
bytes = &bytes[take..];
}
}
fn lines(&mut self, stderr: bool, bytes: &[u8], emit: &mut dyn FnMut(DockerLogLine)) {
let partial = &mut self.partial[usize::from(stderr)];
for &b in bytes {
if b == b'\n' {
emit(DockerLogLine { stderr, text: line_text(partial) });
partial.clear();
} else {
partial.push(b);
}
}
}
/// Emits the last lines that ended without a newline.
fn finish(&mut self, emit: &mut dyn FnMut(DockerLogLine)) {
for stderr in [false, true] {
let partial = &mut self.partial[usize::from(stderr)];
if !partial.is_empty() {
emit(DockerLogLine { stderr, text: line_text(partial) });
partial.clear();
}
}
}
}
fn line_text(bytes: &[u8]) -> String {
String::from_utf8_lossy(bytes.strip_suffix(b"\r").unwrap_or(bytes)).into_owned()
}
/// One URL path segment, percent-encoded so an id cannot change the path.
fn path_segment(id: &str) -> String {
let mut out = String::with_capacity(id.len());
@@ -1121,75 +817,6 @@ mod tests {
assert!(read_response(&mut &garbage[..]).is_err());
}
/// Feeds `body` one byte at a time, as a slow connection delivers it.
fn decode(head: Head, tty: bool, body: &[u8]) -> (Vec<(bool, String)>, bool) {
let mut lines = Vec::new();
let mut decoder = LogDecoder::new(&head, tty);
for b in body {
decoder.feed(std::slice::from_ref(b), &mut |l| lines.push((l.stderr, l.text))).unwrap();
}
let done = decoder.done();
decoder.finish(&mut |l| lines.push((l.stderr, l.text)));
(lines, done)
}
fn frame(stream: u8, text: &str) -> Vec<u8> {
let mut f = vec![stream, 0, 0, 0];
f.extend((text.len() as u32).to_be_bytes());
f.extend(text.as_bytes());
f
}
#[test]
fn engine_image_history_reads_like_the_cli() {
let layers: Vec<ApiLayer> = serde_json::from_str(
r#"[{"Id":"sha256:abc","Created":1000,"CreatedBy":"CMD [\"python3\"]","Size":20500,"Comment":"buildkit","Tags":["py:3"]},
{"Id":"<missing>","Created":940,"CreatedBy":"RUN x","Size":0,"Comment":""}]"#,
)
.unwrap();
let rows = map_layers(layers, 1000 + 2 * 7 * 86_400);
assert_eq!(
rows.iter().map(|l| (l.id.as_str(), l.size.as_str(), l.created_since.as_str())).collect::<Vec<_>>(),
[("sha256:abc", "20.5kB", "2 weeks ago"), ("<missing>", "0B", "2 weeks ago")]
);
assert_eq!(rows[0].created_by, "CMD [\"python3\"]");
let top: ApiTop = serde_json::from_str(r#"{"Titles":["PID","CMD"],"Processes":[["1","sh"]]}"#).unwrap();
assert_eq!(
(top.titles, top.processes),
(vec!["PID".to_owned(), "CMD".to_owned()], vec![vec!["1".to_owned(), "sh".to_owned()]])
);
}
#[test]
fn container_logs_split_into_stream_lines_across_chunks_and_frames() {
// Frames split mid-line, a CRLF line, and a stderr line between stdout parts.
let mut framed = frame(1, "tick 1\r\ntick");
framed.extend(frame(2, "oops\n"));
framed.extend(frame(1, " 2\nlast"));
let mut chunked = Vec::new();
for part in framed.chunks(7) {
chunked.extend(format!("{:x}\r\n", part.len()).as_bytes());
chunked.extend(part);
chunked.extend(b"\r\n");
}
chunked.extend(b"0\r\n\r\n");
let (lines, done) = decode(Head { status: 200, chunked: true, length: None }, false, &chunked);
assert!(done);
let expected = [(false, "tick 1"), (true, "oops"), (false, "tick 2"), (false, "last")];
assert_eq!(lines, expected.map(|(e, t)| (e, t.to_owned())));
// A TTY container's log is one raw stream; the body may end with the connection.
let (lines, done) = decode(Head { status: 200, chunked: false, length: None }, true, b"a\r\nb\n");
assert!(!done);
assert_eq!(lines, [(false, "a".to_owned()), (false, "b".to_owned())]);
// A Content-Length body ends after its length.
let body = frame(1, "one\n");
let (lines, done) = decode(Head { status: 200, chunked: false, length: Some(body.len()) }, false, &body);
assert!(done);
assert_eq!(lines, [(false, "one".to_owned())]);
}
#[test]
fn daemon_errors_carry_their_message() {
let resp = Response { status: 404, body: br#"{"message":"No such container: missing"}"#.to_vec() };
-15
View File
@@ -287,11 +287,6 @@ fn check_id(id: &str) -> IdeResult<&str> {
/// `docker image history --no-trunc --format '{{json .}}'` of one image.
pub fn image_history(ep: &DockerEndpoint, id: &str) -> IdeResult<Vec<DockerImageLayer>> {
let id = check_id(id)?;
if docker_executable().is_none()
&& let Some(layers) = engine::image_history(ep, id, QUICK)
{
return layers;
}
let out = run(ep, &["image", "history", "--no-trunc", "--format", "{{json .}}", id], QUICK)?;
Ok(parse_image_history(&out))
}
@@ -299,11 +294,6 @@ pub fn image_history(ep: &DockerEndpoint, id: &str) -> IdeResult<Vec<DockerImage
/// `docker top <id>` of a running container.
pub fn container_top(ep: &DockerEndpoint, id: &str) -> IdeResult<DockerProcessList> {
let id = check_id(id)?;
if docker_executable().is_none()
&& let Some(processes) = engine::container_top(ep, id, QUICK)
{
return processes;
}
let out = run(ep, &["top", id], QUICK)?;
Ok(parse_container_top(&out))
}
@@ -326,11 +316,6 @@ pub fn logs(
cancel: &CancellationToken,
on_line: &dyn Fn(DockerLogLine),
) -> IdeResult<()> {
if docker_executable().is_none()
&& let Some(streamed) = engine::logs(ep, id, tail, follow, timestamps, QUICK, cancel, on_line)
{
return streamed;
}
let tail = tail.to_string();
let mut args = vec!["logs", "--tail", &tail];
if follow {
+12 -25
View File
@@ -84,7 +84,7 @@ pub fn project_libraries_stream(
cancel: &CancellationToken,
on_groups: &(dyn Fn(Vec<LibraryGroup>) + Sync),
) -> Vec<LibraryGroup> {
type Detect = fn(&Path, &Path, &Settings, &CancellationToken) -> Vec<LibraryGroup>;
type Detect = fn(&Path, &Settings, &CancellationToken) -> Vec<LibraryGroup>;
let detectors: [Detect; 6] = [python_groups, jdk_groups, node_groups, go_groups, ruby_groups, zig_groups];
let roots = library_project_roots(root, cancel);
let settings = module_settings(root, settings);
@@ -99,7 +99,7 @@ pub fn project_libraries_stream(
if cancel.is_cancelled() {
break;
}
let batch = d(dir, root, settings, cancel);
let batch = d(dir, settings, cancel);
if !cancel.is_cancelled() && !batch.is_empty() {
on_groups(batch.clone());
groups.extend(batch);
@@ -384,7 +384,7 @@ fn tool(bin: Option<PathBuf>, name: &str) -> Option<PathBuf> {
// ------------------------------------------------------------------ python
fn python_groups(root: &Path, _project: &Path, s: &Settings, cancel: &CancellationToken) -> Vec<LibraryGroup> {
fn python_groups(root: &Path, s: &Settings, cancel: &CancellationToken) -> Vec<LibraryGroup> {
let Some(python) = crate::apply::python_interpreter(root, s) else { return Vec::new() };
let mut files = vec![python.clone()];
files.extend(crate::venv_of(&python).map(|v| v.join("pyvenv.cfg")));
@@ -436,7 +436,7 @@ pub(crate) fn named_roots(roots: Vec<(String, PathBuf)>) -> Vec<LibraryRoot> {
// ------------------------------------------------------------------ ruby
fn ruby_groups(root: &Path, _project: &Path, s: &Settings, cancel: &CancellationToken) -> Vec<LibraryGroup> {
fn ruby_groups(root: &Path, s: &Settings, cancel: &CancellationToken) -> Vec<LibraryGroup> {
let Some(files) = manifests(root, RUBY_MANIFESTS) else { return Vec::new() };
if !root.join("Gemfile").is_file() && !root.join(".ruby-version").is_file() {
return Vec::new();
@@ -454,7 +454,7 @@ fn ruby_groups(root: &Path, _project: &Path, s: &Settings, cancel: &Cancellation
// ------------------------------------------------------------------ jdk
fn jdk_groups(root: &Path, _project: &Path, s: &Settings, cancel: &CancellationToken) -> Vec<LibraryGroup> {
fn jdk_groups(root: &Path, s: &Settings, cancel: &CancellationToken) -> Vec<LibraryGroup> {
// Java modules without a build manifest carry `.classpath` / `.project` /
// `.idea` instead; a configured JDK or declared source roots mark one too.
let files = match manifests(root, JAVA_MANIFESTS) {
@@ -731,7 +731,7 @@ pub(crate) fn gradle_jar(home: &Path, d: &BuildDependency) -> Option<PathBuf> {
// ------------------------------------------------------------------ node
fn node_groups(root: &Path, _project: &Path, s: &Settings, _cancel: &CancellationToken) -> Vec<LibraryGroup> {
fn node_groups(root: &Path, s: &Settings, _cancel: &CancellationToken) -> Vec<LibraryGroup> {
if !root.join("package.json").is_file() {
return Vec::new();
}
@@ -907,7 +907,7 @@ pub(crate) fn parse_cargo_metadata(json: &str) -> Option<Vec<(String, PathBuf)>>
// ------------------------------------------------------------------ go
fn go_groups(root: &Path, project: &Path, s: &Settings, cancel: &CancellationToken) -> Vec<LibraryGroup> {
fn go_groups(root: &Path, s: &Settings, cancel: &CancellationToken) -> Vec<LibraryGroup> {
let Some(mut files) = manifests(root, GO_MANIFESTS) else { return Vec::new() };
if !root.join("go.mod").is_file() && !root.join("go.work").is_file() {
return Vec::new();
@@ -958,7 +958,7 @@ fn go_groups(root: &Path, project: &Path, s: &Settings, cancel: &CancellationTok
} else if let Some(text) =
query_in_cancellable(&go, &["list", "-m", "-e", "-json", "all"], root, &env, GRAPH_TIMEOUT, cancel)
{
out.extend(group("Go Modules", "goModules", named_roots(parse_go_modules(&text, project))));
out.extend(group("Go Modules", "goModules", named_roots(parse_go_modules(&text))));
}
out
})
@@ -978,19 +978,8 @@ fn vendor_roots(vendor: &Path, text: &str) -> Vec<(String, PathBuf)> {
.collect()
}
/// True when `path` is source the user owns: inside `project` and not a `vendor` copy.
fn is_project_source(project: &Path, path: &Path) -> bool {
let project = project.canonicalize().unwrap_or_else(|_| project.to_path_buf());
let path = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
let Ok(relative) = path.strip_prefix(&project) else { return false };
!relative.components().any(|component| component.as_os_str() == "vendor")
}
/// `(path@version, dir)` of the modules that are libraries: everything whose source is
/// outside the opened project. Source inside it is the user's own code — the target of a
/// `replace`, say — and stays editable; a `vendor` copy is the exception, checked in and
/// kept read-only.
pub(crate) fn parse_go_modules(text: &str, project: &Path) -> Vec<(String, PathBuf)> {
/// `(path@version, dir)` of the downloaded non-main modules in `go list -m -json` output.
pub(crate) fn parse_go_modules(text: &str) -> Vec<(String, PathBuf)> {
#[derive(Deserialize)]
#[serde(rename_all = "PascalCase")]
struct Module {
@@ -1004,8 +993,6 @@ pub(crate) fn parse_go_modules(text: &str, project: &Path) -> Vec<(String, PathB
.into_iter::<Module>()
.map_while(Result::ok)
.filter(|m| !m.main)
// A module whose source sits in the project is the user's own code, not a library.
.filter(|m| m.dir.as_deref().is_none_or(|dir| !is_project_source(project, dir)))
.filter_map(|m| {
let name = match &m.version {
Some(v) => format!("{}@{v}", m.path),
@@ -1018,7 +1005,7 @@ pub(crate) fn parse_go_modules(text: &str, project: &Path) -> Vec<(String, PathB
// ------------------------------------------------------------------ zig
fn zig_groups(root: &Path, _project: &Path, s: &Settings, cancel: &CancellationToken) -> Vec<LibraryGroup> {
fn zig_groups(root: &Path, s: &Settings, cancel: &CancellationToken) -> Vec<LibraryGroup> {
let Some(files) = manifests(root, ZIG_MANIFESTS) else { return Vec::new() };
let Some(zig) = tool(crate::apply::zig_bin(root, s), "zig") else { return Vec::new() };
cached_cancellable(root, "zig", zig.display().to_string(), &files, cancel, || {
@@ -1587,7 +1574,7 @@ mod zig_tests {
std::fs::set_permissions(&zig, std::fs::Permissions::from_mode(0o755)).unwrap();
let mut settings = Settings::default();
settings.languages.zig.zig = "tools".into();
let groups = zig_groups(root, root, &settings, &CancellationToken::new());
let groups = zig_groups(root, &settings, &CancellationToken::new());
let summary: Vec<(&str, &str, Vec<&str>)> = groups
.iter()
.map(|g| (g.name.as_str(), g.kind.as_str(), g.roots.iter().map(|r| r.name.as_str()).collect()))
+1 -30
View File
@@ -1875,7 +1875,7 @@ fn go_modules_skip_the_main_module_and_missing_downloads() {
{"Path":"golang.org/x/text","Version":"v0.14.0","Dir":"/gopath/pkg/mod/golang.org/x/[email protected]"}
{"Path":"example.com/missing","Version":"v1.0.0","Error":{"Err":"module lookup disabled"}}"#;
assert_eq!(
crate::libraries::parse_go_modules(out, std::path::Path::new("/p")),
crate::libraries::parse_go_modules(out),
[(
"golang.org/x/[email protected]".to_owned(),
std::path::PathBuf::from("/gopath/pkg/mod/golang.org/x/[email protected]")
@@ -1883,35 +1883,6 @@ fn go_modules_skip_the_main_module_and_missing_downloads() {
);
}
#[test]
fn go_modules_skip_module_sources_inside_the_project() {
let out = r#"{"Path":"example.com/app","Main":true,"Dir":"/p/app"}
{"Path":"example.com/local","Version":"v0.0.0","Dir":"/p/local"}
{"Path":"example.com/vendored","Version":"v0.0.0","Dir":"/p/vendor/vendored"}
{"Path":"example.com/outside","Version":"v1.0.0","Dir":"/other/outside"}
{"Path":"golang.org/x/text","Version":"v0.14.0","Dir":"/gopath/pkg/mod/golang.org/x/[email protected]"}"#;
assert_eq!(
crate::libraries::parse_go_modules(out, std::path::Path::new("/p")),
[
("example.com/[email protected]".to_owned(), std::path::PathBuf::from("/p/vendor/vendored")),
("example.com/[email protected]".to_owned(), std::path::PathBuf::from("/other/outside")),
(
"golang.org/x/[email protected]".to_owned(),
std::path::PathBuf::from("/gopath/pkg/mod/golang.org/x/[email protected]")
),
]
);
// Opened from a root that does not contain it: the same folder is a library again.
assert!(
crate::libraries::parse_go_modules(
r#"{"Path":"example.com/local","Version":"v0.0.0","Dir":"/p/local"}"#,
std::path::Path::new("/p/app")
)
.iter()
.any(|(name, _)| name == "example.com/[email protected]")
);
}
#[test]
fn build_zig_zon_dependencies_are_parsed() {
let zon = r#"// the manifest is a Zig struct literal
-1
View File
@@ -850,7 +850,6 @@ mod tests {
"agent": "",
"agentModel": "",
"agentEffort": "",
"agentButton": true,
})
);
}
+1 -3
View File
@@ -55,9 +55,7 @@ Codex keeps its own project trust decision. If it disables the current project's
<Step title="Pick the agent and its settings">
Choose the agent, and its model, mode and other options when it offers them. Cached models appear immediately; the selected agent's catalog refreshes in the background when it is more than 15 minutes old, without sending a prompt or attaching project MCP servers.
Click the model name to switch models, or click the settings beside it (for example **High · 1M**) to change effort or context size directly. In the model list, use the arrow on a model's row to see its settings without selecting it. Changing a setting selects that model; going back without an edit keeps the previous selection. These controls are also available in an existing chat.
If settings aren't cached, OpenIDEA looks them up when you select or inspect the model. No prompt is sent. Each model keeps its own draft choices, and models that report no effort control do not borrow another model's levels.
Model-specific effort levels and context options are looked up when you select a model whose settings are not cached, even before its first task. **Loading model settings…** appears beside the model during this short-lived lookup; no prompt is sent and existing tasks are not changed. Each model keeps its own choices, and models that report no effort control do not borrow another model's levels.
After changing the agent CLI or account, open the model picker and choose **Refresh models**. Refreshes share one lookup and have a 30-second cooldown after completion, including failures. Selecting an uncached model's settings does not wait for another model's cooldown. Cached choices remain usable while refreshing or after a failure; use **Refresh models** to retry a failed lookup after its cooldown.
+1 -1
View File
@@ -123,7 +123,7 @@ These commands are in the **Run** menu and on the Debug tool window toolbar.
While the program is suspended:
- The **Variables** view shows the variables of the selected frame. Right-click a value for **Set Value…** (`F2`), **Copy Value**, **Copy Name**, **Jump to Source** (`F4`) and **Add to Watches**.
- **Watches** appear at the top of the Variables view and are re-evaluated on every stop and frame change. Add one with **Add to Watches**; remove it with **Remove Watch**, or all of them with **Remove All Watches**.
- **Watches** appear at the top of the Variables view and are re-evaluated on every stop and frame change. Add one with **Add to Watches**; remove it with **Remove Watch**.
- Hovering a variable in the editor shows its value. `⌥`-click (`Alt`-click) or **Quick Evaluate Expression** (`⌘⌥F8` / `Ctrl+Alt+F8`) evaluates the expression under the mouse or the selection.
- Values of local variables are shown inline after the lines that use them.
- **Evaluate Expression…** (`⌥F8` / `Alt+F8`) opens a dialog that evaluates any expression in the selected frame, keeps a history, and can add the expression to watches.
+1 -1
View File
@@ -160,7 +160,7 @@ A **Compound** configuration starts several configurations at once. Run it to st
Each launch opens a tab in the **Run** tool window (bottom). The toolbar has **Rerun**, **Debug**, **Rerun Failed Tests** (for test runs), **Update Application**, **Find…**, **Scroll to End**, **Soft-Wrap**, **Clear All** and **Edit Configurations…**.
- File paths and stack trace frames in the output are links.
- Repeated lines can be folded; configure the patterns in **Settings › Build, Execution, Deployment › Console**, along with the buffer size and the console encoding. **Fold Lines Like This** in the console's context menu opens that page with the selected text (or the clicked line) added as a pattern.
- Repeated lines can be folded; configure the patterns in **Settings › Build, Execution, Deployment › Console**, along with the buffer size and the console encoding.
- Log lines can take the colour of their level (`ERROR`, `WARN`, `INFO`, `DEBUG`, `TRACE`); colours the program prints itself are kept. Turn it on and pick the colours in **Settings › Build, Execution, Deployment › Console**.
- For test runs the tab shows a test tree next to the output. See [Testing](/en/guide/testing).
+1 -3
View File
@@ -55,9 +55,7 @@ Codex 有自己的项目信任设置。如果它禁用了当前项目的 `.codex
<Step title="选择 agent 及其设置">
选择 agent,以及它提供的模型、模式等选项。缓存的模型会立即显示;所选 agent 的模型列表超过 15 分钟未更新时,会在后台刷新,不发送提示词,也不接入项目 MCP 服务器。
点击模型名称可切换模型;点击旁边的设置(如 **High · 1M**)可直接调整思考强度或上下文大小。在模型列表中,点击一行右侧的箭头可以先查看该模型的设置。修改设置时才会选中该模型,直接返回则保留原来的选择。在已有对话中也可以这样操作。
选择模型或查看其设置时,如果还没有缓存,OpenIDEA 会按需查询,无需发送提示词。草稿分别保留各模型的选择;未提供思考强度的模型不会沿用其他模型的选项。
选择尚未缓存设置的模型时,会按需查询该模型的思考强度和上下文选项,无需先运行任务。短暂查询期间,模型旁会显示**正在加载模型设置…**;查询不发送提示词,也不更改现有任务。每个模型分别保留你选择的设置;明确不提供思考强度的模型不会沿用其他模型的强度选项。
更改 agent CLI 或账号后,打开模型选择器并单击 **刷新模型**。并发刷新会共用一次查询;每次查询完成后(包括失败)都有 30 秒冷却时间。查询其他未缓存模型的设置无需等待前一个模型的冷却时间。刷新中或刷新失败后,缓存选项仍可使用;查询失败后,可在冷却结束后用**刷新模型**重试。
+1 -1
View File
@@ -125,7 +125,7 @@ C 和 C++ 的配置也可以改用 GDB 14 及以上版本(`gdb -i dap`):
程序挂起时:
- **变量** 视图显示选中帧的变量。右键点击某个值,可以 **设置值…**(`F2`)、**复制值**、**复制名称**、**跳转到源代码**(`F4`)和 **添加到监视**。
- 监视表达式显示在变量视图顶部,每次停下或切换帧时重新计算。用 **添加到监视** 添加,用 **移除监视** 删除,用 **移除所有监视** 一次全部删除。
- 监视表达式显示在变量视图顶部,每次停下或切换帧时重新计算。用 **添加到监视** 添加,用 **移除监视** 删除。
- 在编辑器里悬停变量会显示它的值。`⌥` 点击(`Alt` 点击)或 **快速计算表达式**(`⌘⌥F8` / `Ctrl+Alt+F8`)计算鼠标下的表达式或选中的内容。
- 局部变量的值会内联显示在使用它们的行尾。
- **计算表达式…**(`⌥F8` / `Alt+F8`)打开对话框,在选中帧里计算任意表达式,带历史记录,也能把表达式加入监视。
+1 -1
View File
@@ -156,7 +156,7 @@ Maven 模块在 **自动** 和 **构建(Make)** 时由 jdtls(ECJ)构建
每次启动都会在底部的 **运行** 工具窗口里开一个标签页。工具栏有 **重新运行**、**调试**、**重新运行失败的测试**(测试运行时)、**更新应用**、**查找…**、**滚动到末尾**、**软换行**、**全部清除** 和 **编辑配置…**。
- 输出里的文件路径和堆栈帧都可以点击跳转。
- 重复的行可以折叠。折叠规则、缓冲区大小和控制台编码在 **设置 › 构建、执行、部署 › 控制台** 中配置。控制台右键菜单中的 **折叠与此类似的行** 会打开该页面,并把选中的文本(或右键所在的行)添加为折叠规则。
- 重复的行可以折叠。折叠规则、缓冲区大小和控制台编码在 **设置 › 构建、执行、部署 › 控制台** 中配置。
- 日志行可按级别着色(`ERROR`、`WARN`、`INFO`、`DEBUG`、`TRACE`);程序自行输出的颜色保持不变。默认关闭,可在 **设置 › 构建、执行、部署 › 控制台** 开启并修改颜色。
- 测试运行时,标签页会在输出旁显示测试树,参见[测试](/zh/guide/testing)。
+6 -50
View File
@@ -109,7 +109,6 @@ async function seed(
model = "atlas",
status: AgentTask["status"] = "ready",
catalogOnly = false,
offered = provider,
) {
await stubDesktop(page);
await page.evaluate(
@@ -219,7 +218,7 @@ async function seed(
if (surface === "new") store.openHome();
else store.openTask(firstTask.id);
},
{ placement, surface, provider: offered, firstTask, secondTask, subagent, model, status, modelId, catalogOnly },
{ placement, surface, provider, firstTask, secondTask, subagent, model, status, modelId, catalogOnly },
);
await expect(box(page)).toBeVisible();
await page.evaluate(() => document.fonts.ready);
@@ -234,8 +233,9 @@ function history(page: Page) {
function modelButton(page: Page) {
return page.getByRole("button", { name: "Model", exact: true }).filter({ visible: true });
}
/** The effort is shown on the model button, after the model's name. */
function effortLabel(page: Page) {
return page.getByRole("button", { name: /^Model settings:/ }).filter({ visible: true });
return modelButton(page).locator("[class*='modelDetail']");
}
async function expectEffort(page: Page, name: string) {
await expect(effortLabel(page)).toHaveText(name);
@@ -284,50 +284,6 @@ async function expectNoSubmission(page: Page) {
expect(await ipcCalls(page, "agent_create")).toEqual([]);
}
for (const surface of ["new", "task"] as const) {
test(`${surface}: configure another model from its row, then edit its context from the composer`, async ({
workbench: page,
}) => {
const context = option(
"context_tier",
"model_config",
[
["default", "200K"],
["long_context", "1M"],
],
"default",
);
const offered = {
...provider,
thoughtLevels: { ...provider.thoughtLevels, atlas: [atlas, context], swift: [swift, context] },
};
await seed(page, "editor", surface, "atlas", "ready", false, offered);
await box(page).fill("Review the project structure");
await modelButton(page).click();
const row = page.getByRole("option", { name: /^Swift\b/ });
await row.hover();
const configure = row.getByRole("button", { name: "Configure Swift…" });
if (surface === "task") await configure.press("Enter");
else await configure.click();
await expect(modelButton(page)).toHaveText("Atlas");
await expect(page.getByRole("radio", { name: "Gentle" })).toHaveCount(0);
await page.getByRole("radio", { name: "Thorough" }).click();
await expect(modelButton(page)).toHaveText("Swift");
await expect(page.getByRole("radio", { name: "Thorough" })).toBeChecked();
await page.keyboard.press("Escape");
const settings = page.getByRole("button", { name: /^Model settings:/ });
await expect(settings).toHaveText("Thorough · 200K");
await settings.click();
await page.getByRole("radio", { name: "1M" }).click();
await expect(settings).toHaveText("Thorough · 1M");
await page.getByRole("button", { name: "Back to models" }).click();
await expect(page.getByRole("listbox", { name: "Model", exact: true })).toBeVisible();
await page.keyboard.press("Escape");
await expect(box(page)).toHaveText("Review the project structure");
await expectNoSubmission(page);
});
}
for (const placement of ["editor", "toolWindow"] as const) {
test(`${placement}: existing task cycles advertised values and wraps without editing, moving focus or scrolling`, async ({
workbench: page,
@@ -423,7 +379,7 @@ test("Settings and effort popup exclude the agent shortcut", async ({ workbench:
await expect(search).toBeFocused();
await expect(search).toHaveValue("keymap");
await settings.getByRole("button", { name: "Cancel", exact: true }).click();
await effortLabel(page).click();
await modelButton(page).click();
const popup = page.getByRole("radiogroup", { name: "Effort Level", exact: true });
await expect(popup).toBeVisible();
await page.keyboard.press("Alt+t");
@@ -647,7 +603,7 @@ test("New Task discovers uncached model effort before the first prompt", async (
await page.screenshot({ path: testInfo.outputPath("model-settings-loading.png") });
await page.evaluate(() => document.dispatchEvent(new Event("test:model-settings-ready")));
await expectEffort(page, "Quick");
await effortLabel(page).click();
await modelButton(page).click();
const efforts = page.getByRole("radiogroup", { name: "Effort Level", exact: true });
await expect(efforts.getByRole("radio", { name: "Quick", exact: true })).toBeVisible();
await expect(efforts.getByRole("radio", { name: "Thorough", exact: true })).toBeVisible();
@@ -680,7 +636,7 @@ test("an existing chat can choose effort for a refreshed model before sending",
await expect(loading).toHaveCount(0);
await expect(modelButton(page)).toHaveAttribute("title", /^Model: Swift\b/);
await expectEffort(page, "Quick");
await effortLabel(page).click();
await modelButton(page).click();
const efforts = page.getByRole("radiogroup", { name: "Effort Level", exact: true });
await expect(efforts.getByRole("radio", { name: "Gentle", exact: true })).toHaveCount(0);
await efforts.getByRole("radio", { name: "Thorough", exact: true }).click();
-71
View File
@@ -1,71 +0,0 @@
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
test("Branch comparison keeps both commit ranges and the diff action visible", async ({ workbench: page }) => {
const branch = "feature/settlement-reconciliation-and-international-ledger-reporting";
const current = "feature/review-quarterly-settlement-audit";
const incomingSubject = "Keep regional settlement references stable during the report export";
const outgoingSubject = "Preserve the audit trail for settlement retries";
await page.setViewportSize({ width: 1120, height: 760 });
await stubDesktop(page);
await page.evaluate(
async ({ branch, current, incomingSubject, outgoingSubject }) => {
const root = "/dev/acme-api";
const branchInfo = {
head: current,
headCommit: "b".repeat(40),
upstream: null,
ahead: 0,
behind: 0,
operation: null,
};
const entry = (letter: string, summary: string) => ({
id: letter.repeat(40),
shortId: letter.repeat(8),
parents: ["a".repeat(40)],
refs: [],
summary,
message: summary + "\n\nUpdate the audit report context.",
author: "Sam Rivera",
email: "[email protected]",
timeMs: 1795100000000,
});
const h = window.__ipc.handlers;
h.vcs_roots = () => [{ root, ...branchInfo }];
h.vcs_branch_info = () => branchInfo;
h.vcs_status = () => [];
h.vcs_log = ({ query }) =>
(query as { range: string }).range === `HEAD..${branch}`
? [entry("c", incomingSubject)]
: [entry("b", outgoingSubject)];
h.window_open_comparison = () => null;
const store = "/src/features/vcs/store.ts";
const { useVcs } = await import(/* @vite-ignore */ store);
useVcs.setState({ available: true, root, repo: root, roots: [root], branch: branchInfo });
const path = "/src/features/vcs/CompareBranches.tsx";
(await import(/* @vite-ignore */ path)).showCompareBranches(branch);
},
{ branch, current, incomingSubject, outgoingSubject },
);
const dialog = page.getByRole("dialog", { name: new RegExp(`Compare ${current}`) });
await expect(dialog.getByRole("listbox")).toHaveCount(2);
const incoming = dialog.getByRole("listbox", { name: `In ${branch}, not in ${current}` });
const outgoing = dialog.getByRole("listbox", { name: `In ${current}, not in ${branch}` });
await expect(incoming.getByText(incomingSubject, { exact: true })).toBeVisible();
await expect(outgoing.getByText(outgoingSubject, { exact: true })).toBeVisible();
const divider = dialog.getByRole("separator", { name: "Resize branch comparison panes" });
await expect(divider).toHaveAttribute("aria-orientation", "horizontal");
const start = (await divider.boundingBox())!.y;
await divider.focus();
await page.keyboard.press("ArrowDown");
await expect.poll(async () => (await divider.boundingBox())!.y).toBeGreaterThan(start + 1);
await page.setViewportSize({ width: 440, height: 660 });
const heading = dialog.getByRole("heading", { name: new RegExp(`In ${branch}`) });
await expect.poll(() => heading.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await expect(incoming.getByRole("option")).toBeVisible();
await expect(outgoing.getByRole("option")).toBeVisible();
await dialog.getByRole("button", { name: "Show Diff", exact: true }).click();
await expect
.poll(() => ipcCalls(page, "window_open_comparison"))
.toMatchObject([{ comparison: { from: { rev: branch }, to: { rev: "HEAD" }, repo: "/dev/acme-api" } }]);
});
-40
View File
@@ -1,40 +0,0 @@
import { expect, test } from "./fixtures";
test("Color Scheme keeps the preview visible while editing an attribute in narrow Settings", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 1120, height: 760 });
await page.keyboard.press("Meta+,");
const settings = page.getByRole("dialog", { name: "Settings", exact: true });
const search = settings.getByRole("textbox", { name: "Search settings" });
await search.fill("Language Defaults");
await settings.getByRole("treeitem", { name: "Language Defaults", exact: true }).click();
await search.clear();
const divider = settings.getByRole("separator", { name: "Resize color scheme preview", exact: true });
const tree = settings.getByRole("tree", { name: "Color scheme attributes", exact: true });
const options = settings.getByRole("region", { name: "Color scheme options", exact: true });
const preview = settings.getByLabel("Color scheme preview", { exact: true });
await expect(divider).toHaveAttribute("aria-orientation", "horizontal");
expect((await tree.boundingBox())!.x).toBeLessThan((await options.boundingBox())!.x);
await page.setViewportSize({ width: 520, height: 660 });
await expect.poll(async () => (await tree.boundingBox())!.y).toBeLessThan((await options.boundingBox())!.y);
const previewTop = (await preview.boundingBox())!.y;
const token = preview.getByText("class", { exact: true }).first();
await token.click();
await expect(tree.getByRole("treeitem", { name: "Keyword", exact: true, selected: true })).toBeVisible();
await options.getByRole("textbox", { name: "Foreground hex", exact: true }).fill("#118899");
await expect(token).toHaveCSS("color", "rgb(17, 136, 153)");
await expect(preview).toBeInViewport();
expect((await preview.boundingBox())!.y).toBeCloseTo(previewTop, 0);
await expect
.poll(() => settings.locator("[class*='pageBody']").evaluate((el) => el.scrollWidth - el.clientWidth))
.toBeLessThanOrEqual(1);
await options.getByRole("checkbox", { name: "Semantic highlighting" }).scrollIntoViewIfNeeded();
expect((await preview.boundingBox())!.y).toBeCloseTo(previewTop, 0);
const before = (await divider.boundingBox())!.y;
await divider.press("ArrowUp");
await expect.poll(async () => (await divider.boundingBox())!.y).toBeLessThan(before - 1);
});
-75
View File
@@ -1,75 +0,0 @@
import { expect, stubDesktop, test } from "./fixtures";
const functionName = "calculateRegionalSettlementFromExternalOrderBeforeReconciliation";
const sourcePath = "/dev/acme-api/build.gradle.kts";
test("keeps frame sources and the keyboard selection visible in a narrow debug dock", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1120, height: 540 });
await stubDesktop(page);
await page.evaluate(
async ({ functionName, sourcePath }) => {
const debugModule = "/src/features/debugger/state.ts";
const layoutModule = "/src/workbench/toolwindows/store.ts";
const servicesModule = "/src/workbench/contributions.ts";
const { adoptSession } = await import(/* @vite-ignore */ debugModule);
const { moveToolWindow, setToolWindowSize } = await import(/* @vite-ignore */ layoutModule);
const { toolWindowService } = await import(/* @vite-ignore */ servicesModule);
const workerFrame = {
id: 51,
name: "processOrder",
path: sourcePath,
line: 5,
column: 0,
presentationHint: null,
};
window.__ipc.handlers.debug_scopes = () => [];
window.__ipc.handlers.debug_stack_trace = () => [workerFrame];
adoptSession(91, {
name: "Reconciliation",
adapter: "debugpy",
status: "paused",
stoppedThread: 1,
selectedThread: 1,
threads: [
{ id: 1, name: "MainThread" },
{ id: 2, name: "Order worker" },
],
selectedFrame: 1,
frames: Array.from({ length: 32 }, (_, index) => ({
id: index + 1,
name: index === 0 ? functionName : index === 1 ? "runBatch" : `reconcile(${index})`,
path: sourcePath,
line: index === 0 ? 41 : index,
column: 0,
presentationHint: null,
})),
});
moveToolWindow("debug", "right");
setToolWindowSize("right", 420);
toolWindowService().show("debug", true);
},
{ functionName, sourcePath },
);
const debug = page.getByRole("region", { name: "Debug", exact: true });
await debug.getByRole("tab", { name: "Threads & Variables", exact: true }).click();
const thread = debug.getByRole("button", { name: "Thread", exact: true });
const frames = debug.getByRole("listbox", { name: "Frames", exact: true });
const first = frames.getByRole("option", { selected: true });
await expect(first.getByText(functionName, { exact: true })).toBeVisible();
expect(await frames.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await expect(first.getByText(":42", { exact: true })).toBeInViewport({ ratio: 1 });
expect(await first.getByText(/build\.gradle\.kts/).evaluate((el) => el.clientWidth)).toBeGreaterThan(25);
const shortName = frames.getByText("runBatch", { exact: true });
expect(await shortName.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await frames.focus();
for (let i = 0; i < 25; i++) await page.keyboard.press("ArrowDown");
const selected = frames.getByRole("option", { selected: true });
await expect(selected.getByText("reconcile(25)", { exact: true })).toBeInViewport({ ratio: 0.95 });
expect(await frames.evaluate((el) => el.scrollTop)).toBeGreaterThan(0);
await thread.click();
await page.getByRole("option", { name: "Order worker", exact: true }).click();
await expect(thread).toContainText("Order worker");
await expect(frames.getByRole("option", { selected: true })).toContainText("processOrder");
});
-42
View File
@@ -1,42 +0,0 @@
import { expect, test } from "./fixtures";
test("Editor Font keeps the preview in view while editing and resizing the controls", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1200, height: 760 });
await page.keyboard.press("Meta+,");
const settings = page.getByRole("dialog", { name: "Settings", exact: true });
const search = settings.getByRole("textbox", { name: "Search settings" });
await search.fill("Show only monospaced fonts");
await settings.getByRole("treeitem", { name: "Font", exact: true, level: 2 }).click();
await search.clear();
const divider = settings.getByRole("separator", { name: "Resize font preview" });
const options = settings.getByRole("region", { name: "Font options", exact: true });
const preview = settings.getByRole("textbox", { name: "Font preview", exact: true });
const font = options.getByRole("combobox", { name: "Font", exact: true });
await expect(divider).toHaveAttribute("aria-orientation", "vertical");
expect((await font.boundingBox())!.x).toBeLessThan((await preview.boundingBox())!.x);
await expect.poll(() => preview.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await preview.fill("function main() { return 42; }");
await options.getByRole("textbox", { name: "Size", exact: true }).fill("18");
await options.getByRole("textbox", { name: "Line height", exact: true }).fill("25");
await expect(preview).toHaveCSS("font-size", "18px");
await expect(preview).toHaveCSS("line-height", "25px");
await page.setViewportSize({ width: 520, height: 620 });
await expect(divider).toHaveAttribute("aria-orientation", "horizontal");
expect((await font.boundingBox())!.y).toBeLessThan((await preview.boundingBox())!.y);
await expect(preview).toHaveValue("function main() { return 42; }");
const y = (await divider.boundingBox())!.y;
await divider.press("ArrowDown");
await expect.poll(async () => (await divider.boundingBox())!.y).toBeGreaterThan(y + 1);
await search.fill("Fallback font");
const fallback = options.getByRole("combobox", { name: "Fallback font", exact: true });
await fallback.scrollIntoViewIfNeeded();
await expect(fallback).toBeInViewport();
await fallback.fill("Consolas");
await expect(preview).toHaveCSS("font-family", /Consolas/);
await expect(preview).toBeInViewport();
await expect.poll(() => options.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
});
-12
View File
@@ -64,15 +64,3 @@ test("editor Git submenu keeps repository actions disabled without Git", async (
}
await expect(page.getByRole("menuitem", { name: "Clone…", exact: true })).toBeEnabled();
});
test("Project view Git submenu ends with Manage Remotes and Clone", async ({ workbench: page }) => {
await page.getByRole("treeitem", { name: /README\.md/ }).click({ button: "right" });
await page.getByRole("menuitem", { name: "Git", exact: true }).hover();
const git = page.getByRole("menu").filter({ has: page.getByRole("menuitem", { name: "Clone…", exact: true }) });
const items = git.locator('[role="menuitem"], [role="menuitemcheckbox"]');
await expect(items.nth(-3)).toHaveText(/Unstash Changes…/);
await expect(items.nth(-2)).toHaveText(/Manage Remotes…/);
await expect(items.nth(-1)).toHaveText(/Clone…/);
await git.getByRole("menuitem", { name: "Manage Remotes…", exact: true }).click();
await expect(page.getByRole("dialog", { name: "Git Remotes" })).toBeVisible();
});
-62
View File
@@ -1,62 +0,0 @@
import { expect, stubDesktop, test } from "./fixtures";
test("File Types keeps association editors usable and opens ignored rules from search", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1120, height: 760 });
await page.keyboard.press("Meta+,");
const settings = page.getByRole("dialog", { name: "Settings", exact: true });
await expect(settings).toBeVisible();
await stubDesktop(page);
await page.evaluate(() => {
window.__ipc.handlers.languages = () => [
{ id: "javascript", name: "JavaScript", extensions: ["js"] },
{ id: "python", name: "Python", extensions: ["py", "pyi", "pyw"], filenames: ["SConstruct", "SConscript"] },
];
});
const search = settings.getByRole("textbox", { name: "Search settings" });
await search.fill("File Types");
await settings.getByRole("treeitem", { name: "File Types", exact: true }).click();
await search.clear();
const tabs = settings.getByRole("tablist", { name: "File Types" });
const recognized = tabs.getByRole("tab", { name: "Recognized File Types" });
const ignored = tabs.getByRole("tab", { name: "Ignored Files and Folders" });
await expect(recognized).toHaveAttribute("aria-selected", "true");
const divider = settings.getByRole("separator", { name: "Resize file type panes" });
await expect(divider).toHaveAttribute("aria-orientation", "vertical");
await page.setViewportSize({ width: 520, height: 660 });
await expect(divider).toHaveAttribute("aria-orientation", "horizontal");
const types = settings.getByRole("listbox", { name: "Recognized file types", exact: true });
await types.getByRole("option", { name: "Python", exact: true }).click();
const patterns = settings.getByRole("listbox", { name: "File name patterns of Python" });
const hashbangLabel = settings.getByText("Hashbang patterns", { exact: true });
await expect
.poll(async () => {
const nameList = await patterns.boundingBox();
const hashbangHeading = await hashbangLabel.boundingBox();
return nameList && hashbangHeading ? hashbangHeading.y - (nameList.y + nameList.height) : -1;
})
.toBeGreaterThan(0);
await expect
.poll(() => settings.locator("[class*='_patterns_']").evaluate((el) => el.scrollWidth - el.clientWidth))
.toBeLessThanOrEqual(1);
const toolbar = settings.locator(`[role="toolbar"][aria-controls="${await patterns.getAttribute("id")}"]`);
await toolbar.getByRole("button", { name: "Add" }).click();
const pattern = patterns.getByRole("textbox", { name: "Pattern" });
await pattern.fill("*.layout-demo");
await pattern.press("Enter");
await expect(patterns.getByRole("option", { name: "*.layout-demo", exact: true })).toBeVisible();
await expect
.poll(() => settings.locator("[class*='pageBody']").evaluate((el) => el.scrollWidth - el.clientWidth))
.toBeLessThanOrEqual(1);
await search.fill("Exclude patterns");
await expect(ignored).toHaveAttribute("aria-selected", "true");
await expect(settings.getByRole("listbox", { name: "Exclude patterns" })).toBeVisible();
await expect(patterns).toBeHidden();
await ignored.click();
await search.clear();
await ignored.press("ArrowLeft");
await expect(recognized).toHaveAttribute("aria-selected", "true");
await expect(patterns.getByRole("option", { name: "*.layout-demo", exact: true })).toBeVisible();
});
-59
View File
@@ -1,59 +0,0 @@
import { expect, openFromTree, test } from "./fixtures";
test("Paste from History keeps the list and preview usable in a short dialog", async ({ workbench: page }) => {
const editor = await openFromTree(page, "App.tsx");
const content = editor.locator(".cm-content");
await content.focus();
const baseFont = Number.parseFloat(await content.evaluate((el) => getComputedStyle(el).fontSize));
await page.evaluate(async () => {
const source = await (await fetch("/src/editor/core/extras.ts")).text();
const imports = [...source.matchAll(/["'](\/src\/[^"']+)["']/g)].map((match) => match[1]!);
const activePath = (path: string) => imports.find((url) => url.split("?")[0] === path) ?? path;
const historyPath = activePath("/src/editor/core/clipboardHistory.ts");
const actionsPath = activePath("/src/platform/actions.ts");
const { recordClipboard } = await import(/* @vite-ignore */ historyPath);
const { executeAction } = await import(/* @vite-ignore */ actionsPath);
recordClipboard("const older = 2;");
recordClipboard("const newest = 1;\n// paste marker");
Object.defineProperty(navigator, "clipboard", { configurable: true, value: { writeText: async () => {} } });
for (let i = 0; i < 5; i++) await executeAction("editor.increaseFontSize");
});
const fontSize = `${baseFont + 5}px`;
await expect(content).toHaveCSS("font-size", fontSize);
await page.keyboard.press("Meta+Shift+v");
const dialog = page.getByRole("dialog", { name: "Choose Content to Paste" });
const divider = dialog.getByRole("separator", { name: "Resize paste preview" });
const list = dialog.getByRole("listbox", { name: "Clipboard history" });
const preview = dialog.getByLabel("Paste preview", { exact: true });
await expect(divider).toHaveAttribute("aria-orientation", "horizontal");
await expect(list.getByText("const newest = 1;", { exact: true })).toHaveCSS("font-size", fontSize);
await expect(preview).toHaveCSS("font-size", fontSize);
await expect(dialog.locator(".cm-gutters")).toHaveCount(0);
await page.setViewportSize({ width: 420, height: 440 });
const search = dialog.getByRole("textbox", { name: "Filter clipboard history" });
const remove = dialog.getByRole("button", { name: "Delete" });
await expect(search).toBeInViewport({ ratio: 1 });
await expect(remove).toBeInViewport({ ratio: 1 });
expect((await remove.boundingBox())!.y).toBeLessThan((await list.boundingBox())!.y);
const previous = Number(await divider.getAttribute("aria-valuenow"));
await divider.press("ArrowDown");
await expect.poll(async () => Number(await divider.getAttribute("aria-valuenow"))).toBeGreaterThan(previous);
const resized = await divider.getAttribute("aria-valuenow");
await expect(dialog.getByRole("button", { name: "Paste" })).toBeInViewport({ ratio: 1 });
await expect(preview).toContainText("// paste marker");
await search.fill("older");
await remove.click();
await expect(dialog.getByText("No matches", { exact: true })).toBeVisible();
await dialog.getByRole("button", { name: "Clear", exact: true }).click();
await expect(search).toHaveValue("");
await search.press("Enter");
await expect(dialog).toBeHidden();
await expect(content).toContainText("const newest = 1;");
await page.keyboard.press("Meta+Shift+v");
await expect(divider).toHaveAttribute("aria-valuenow", resized!);
await page.keyboard.press("Escape");
});
-83
View File
@@ -159,86 +159,3 @@ test("Find in Files streams matches by file and opens the chosen one at its line
}, `Editor for ${ROOT}/build.gradle.kts`);
await expect.poll(caretLine).toBe("import com.acme.orders.service.OrderService");
});
test("the Find tool window keeps the selected preview and replacement actions when narrowed", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 1500, height: 820 });
await stubDesktop(page);
await page.evaluate(
({ path, relPath }) => {
window.__ipc.handlers.search_validate = () => null;
window.__ipc.handlers.search_start = ({ query, onEvent }) => {
if ((query as SearchQuery).pattern !== "OrderService") return null;
setTimeout(() => {
window.__ipc.send(onEvent, {
type: "file",
file: {
path,
relPath,
matches: [
{
line: 2,
text: "import com.acme.orders.service.OrderService",
ranges: [[31, 43]],
textOffset: 0,
},
],
},
});
window.__ipc.send(onEvent, {
type: "done",
summary: { files: 1, matches: 1, limitHit: false, cancelled: false, elapsedMs: 1 },
});
}, 20);
return null;
};
},
{ path: `${ROOT}/build.gradle.kts`, relPath: "build.gradle.kts" },
);
await page.keyboard.press("Meta+Shift+r");
const popup = page.getByRole("dialog", { name: "Replace in Files" });
await popup.getByRole("textbox", { name: "Text to find" }).fill("OrderService");
await popup.getByRole("textbox", { name: "Replace with" }).fill("OrdersApi");
await expect(popup.getByRole("listbox", { name: "Matches" }).getByRole("option")).toHaveCount(1);
await popup.getByRole("button", { name: "Open in Find Window", exact: true }).click();
const find = page.getByRole("region", { name: "Find", exact: true });
await find.getByRole("button", { name: "Options", exact: true }).click();
await page.getByRole("menuitem", { name: "Move To", exact: true }).hover();
await page.getByRole("menuitem", { name: "Right Top", exact: true }).click();
const dockDivider = page.getByRole("separator", { name: "Resize right tool window", exact: true });
const resizeDock = async (width: number) => {
await expect(dockDivider).toBeVisible();
const handle = (await dockDivider.boundingBox())!;
const dock = (await find.boundingBox())!;
const x = handle.x + handle.width / 2;
const y = handle.y + handle.height / 2;
await page.mouse.move(x, y);
await page.mouse.down();
await page.mouse.move(x + dock.width - width, y, { steps: 5 });
await page.mouse.up();
};
await resizeDock(690);
const row = find.getByRole("treeitem", { name: /OrderService.*OrdersApi/ });
await row.click();
const preview = find.getByRole("region", { name: "Preview", exact: true });
await expect(preview.locator(".cm-content")).toContainText("OrderService");
const divider = find.getByRole("separator", { name: "Resize find preview" });
await expect(divider).toHaveAttribute("aria-orientation", "vertical");
await resizeDock(325);
await expect(divider).toHaveAttribute("aria-orientation", "horizontal");
await expect(row).toHaveAttribute("aria-selected", "true");
await expect(preview.locator(".cm-content")).toContainText("OrderService");
await expect(find.getByRole("toolbar", { name: "Find actions" })).toHaveAttribute("aria-orientation", "vertical");
for (const label of ["Preview", "Replace Selected", "Replace All"]) {
await expect(find.getByRole("button", { name: label, exact: true })).toBeInViewport({ ratio: 1 });
}
await find.getByRole("button", { name: "Replace All", exact: true }).click();
const confirmation = page.getByRole("dialog", { name: "Replace All" });
await expect(confirmation).toBeVisible();
await confirmation.getByRole("button", { name: "Cancel" }).click();
await expect(confirmation).toBeHidden();
});
-23
View File
@@ -80,29 +80,6 @@ test("⌘, opens Settings with the page tree; Escape closes", async ({ workbench
await expect(dialog).toBeHidden();
});
test("editor appearance groups related controls and keeps whitespace options editable", async ({ workbench: page }) => {
await page.keyboard.press("Meta+,");
const settings = page.getByRole("dialog", { name: "Settings", exact: true });
await settings.getByRole("textbox", { name: "Search settings" }).fill("Show whitespaces");
await settings.getByRole("treeitem", { name: "Appearance", exact: true }).click();
const section = (name: string) => settings.getByRole("region", { name, exact: true });
await expect(section("Caret").getByRole("checkbox", { name: "Use block caret" })).toBeVisible();
await expect(section("Code Structure").getByRole("checkbox", { name: "Show line numbers" })).toBeVisible();
await expect(section("Code Assistance").getByRole("checkbox", { name: "Show intention bulb" })).toBeVisible();
const presentation = section("Presentation");
await expect(presentation.getByRole("checkbox", { name: "Render documentation comments" })).toBeVisible();
await expect(presentation.getByRole("textbox", { name: "Distraction free mode text width:" })).toBeVisible();
const whitespace = presentation.getByRole("checkbox", { name: "Show whitespaces" });
const leading = presentation.getByRole("checkbox", { name: "Leading", exact: true });
if (await whitespace.isChecked()) await whitespace.uncheck();
await expect(leading).toBeDisabled();
await whitespace.check();
await expect(leading).toBeEnabled();
await settings.getByRole("button", { name: "Cancel", exact: true }).click();
await expect(settings).toBeHidden();
});
test("Language Servers page installs a tool with progress (in-memory installer)", async ({ workbench: page }) => {
await page.keyboard.press("Meta+,");
const dialog = page.getByRole("dialog", { name: "Settings" });
-93
View File
@@ -1,93 +0,0 @@
import { expect, stubDesktop, test } from "./fixtures";
test("Shelf keeps patch and file selection available in a narrow dock", async ({ workbench: page }) => {
const name = "Reconcile payment and settlement totals before exporting ledger reports";
const directory = "services/settlement/internal/payment-reconciliation/statement-generation";
const filename = "invoiceSettlementRowAssembler.ts";
const file = directory + "/" + filename;
await page.setViewportSize({ width: 1440, height: 760 });
await stubDesktop(page);
await page.evaluate(
async ({ name, file }) => {
const root = "/dev/acme-api";
const h = window.__ipc.handlers;
h.vcs_roots = () => [{ root, operation: null, head: "main", headCommit: "1111111" }];
h.vcs_branch_info = () => ({
head: "main",
headCommit: "1111111",
upstream: null,
ahead: 0,
behind: 0,
operation: null,
});
h.vcs_status = () => [];
h.vcs_shelves = () => [
{
id: "settlement",
name,
timeMs: null,
branch: "main",
files: [file, "README.md"].map((path) => ({ path, kind: "modified", oldPath: null })),
},
{
id: "docs",
name: "Update release notes",
timeMs: null,
branch: "main",
files: [{ path: "CHANGELOG.md", kind: "modified", oldPath: null }],
},
];
h.vcs_shelf_diff = () => [];
const vcs = "/src/features/vcs/store.ts";
const { useVcs } = await import(/* @vite-ignore */ vcs);
useVcs.setState({ root, repo: root, roots: [root], available: true });
const project = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ project);
const settings = useProject.getState().settings ?? {};
useProject.setState({ settings: { ...settings, vcs: { ...settings.vcs, commit: { nonModal: true } } } });
const context = "/src/platform/context.ts";
(await import(/* @vite-ignore */ context)).setContext("vcsAvailable", true);
const dock = "/src/workbench/toolwindows/store.ts";
(await import(/* @vite-ignore */ dock)).setToolWindowSize("left", 228);
const actions = "/src/platform/actions.ts";
await (await import(/* @vite-ignore */ actions)).executeAction("vcs.showShelf");
},
{ name, file },
);
const panel = page.locator("[data-shelf-panel]");
const patches = panel.getByRole("tree", { name: "Shelved changes" });
const patch = patches.getByRole("treeitem").filter({ hasText: name });
await patch.click({ position: { x: 90, y: 12 } });
if ((await patch.getAttribute("aria-expanded")) === "false") await page.keyboard.press("ArrowRight");
const location = panel.getByText(directory, { exact: true });
await expect.poll(() => location.evaluate((el) => el.clientWidth)).toBeGreaterThan(100);
const divider = panel.getByRole("separator", { name: "Resize shelf panes" });
await expect(divider).toHaveAttribute("aria-orientation", "horizontal");
const files = panel.getByRole("tree", { name: "Shelved files" });
await expect(files.getByRole("treeitem")).toHaveCount(2);
const pathBox = (await location.boundingBox())!;
const filesBox = (await files.boundingBox())!;
expect(pathBox.x).toBeLessThan(filesBox.x + filesBox.width - 50);
const row = files.getByRole("treeitem").filter({ hasText: filename });
await row.click({ position: { x: 90, y: 12 } });
await expect(row).toHaveAttribute("aria-selected", "true");
await panel.getByRole("button", { name: "Unshelve…", exact: true }).click();
const dialog = page.getByRole("dialog", { name: "Unshelve Changes" });
await expect(
dialog.getByRole("tree", { name: "Files to unshelve" }).getByText(filename, { exact: true }),
).toBeVisible();
await expect(dialog.getByText("README.md", { exact: true })).toHaveCount(0);
await dialog.getByRole("button", { name: "Cancel", exact: true }).click();
await page.evaluate(async () => {
const dock = "/src/workbench/toolwindows/store.ts";
(await import(/* @vite-ignore */ dock)).setToolWindowSize("left", 640);
});
await expect(divider).toHaveAttribute("aria-orientation", "vertical");
await expect(row).toHaveAttribute("aria-selected", "true");
await patches.getByRole("treeitem").filter({ hasText: "Update release notes" }).click();
await expect(files.getByRole("treeitem")).toHaveCount(1);
await expect(files.getByText("CHANGELOG.md", { exact: true })).toBeVisible();
});
-65
View File
@@ -1,65 +0,0 @@
import { expect, openFromTree, test } from "./fixtures";
test("Switcher keeps the open file list and path visible in a narrow workbench", async ({ workbench: page }) => {
await openFromTree(page, "README.md");
await openFromTree(page, "App.tsx");
await page.keyboard.down("Control");
await page.keyboard.press("Tab");
const switcher = page.getByRole("dialog", { name: "Switcher", exact: true });
const files = switcher.getByRole("listbox", { name: "Open files" });
const tools = switcher.getByRole("listbox", { name: "Tool windows" });
const selected = files.getByRole("option", { selected: true });
await expect(selected).toHaveText("README.md");
expect((await switcher.boundingBox())!.width).toBeLessThan(600);
await page.setViewportSize({ width: 400, height: 500 });
await expect.poll(async () => (await files.boundingBox())!.width).toBeGreaterThan(225);
const footer = switcher.locator("footer");
await expect(footer).toHaveText(/README\.md$/);
await expect(footer).toBeInViewport({ ratio: 1 });
await expect(footer).toHaveCSS("font-size", "12px");
expect(await tools.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
expect(await files.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
const structure = tools.getByText("Structure", { exact: true });
expect(await structure.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await page.keyboard.press("Tab");
const activeTool = tools.getByRole("option", { selected: true });
await expect(activeTool).toBeInViewport({ ratio: 1 });
const firstTool = await activeTool.getAttribute("aria-posinset");
await page.keyboard.press("PageDown");
await page.keyboard.press("PageDown");
await expect(activeTool).not.toHaveAttribute("aria-posinset", firstTool!);
await expect(activeTool).toBeInViewport({ ratio: 0.98 });
expect(await tools.evaluate((el) => el.scrollTop)).toBeGreaterThan(0);
await page.keyboard.press("Shift+Tab");
await expect(selected).toHaveText("README.md");
await page.keyboard.up("Control");
await expect(switcher).toBeHidden();
await expect(page.getByRole("tab", { name: "README.md", exact: true })).toHaveAttribute("aria-selected", "true");
});
test("Switcher takes up less space when both lists have only a few entries", async ({ workbench: page }) => {
await openFromTree(page, "README.md");
await openFromTree(page, "App.tsx");
await page.evaluate(async () => {
const path = "/src/workbench/contributions.ts";
const { useContributions } = (await import(
/* @vite-ignore */ path
)) as typeof import("../src/workbench/contributions");
useContributions.setState(({ toolWindows }) => ({
toolWindows: new Map([...toolWindows].filter(([id]) => id === "project" || id === "terminal")),
}));
});
await page.keyboard.down("Control");
await page.keyboard.press("Tab");
const switcher = page.getByRole("dialog", { name: "Switcher", exact: true });
const tools = switcher.getByRole("listbox", { name: "Tool windows" });
await expect(tools.getByRole("option")).toHaveCount(2);
await expect.poll(async () => (await switcher.boundingBox())!.height).toBeLessThan(380);
await expect(switcher.locator("footer")).toHaveText(/README\.md$/);
await page.keyboard.press("Escape");
await page.keyboard.up("Control");
});
-42
View File
@@ -1,42 +0,0 @@
import { expect, test } from "./fixtures";
test("Welcome keeps project search and actions on one row at a narrow width", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1080, height: 700 });
await page.evaluate(async () => {
const projectPath = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ projectPath);
useProject.setState({ project: null, lightEdit: false });
});
const projects = page.getByRole("region", { name: "Projects", exact: true });
const search = projects.getByRole("textbox", { name: "Search projects" });
const list = projects.getByRole("listbox", { name: "Recent projects" });
const more = projects.getByRole("button", { name: "More Actions", exact: true });
const open = projects.getByRole("button", { name: "Open", exact: true });
await expect(list.getByRole("option")).toHaveCount(4);
await expect(more).toBeVisible();
await expect(open).toHaveText("Open");
await page.setViewportSize({ width: 440, height: 620 });
const boxes = await Promise.all([search.boundingBox(), open.boundingBox(), more.boundingBox()]);
expect(boxes[0]!.width).toBeGreaterThan(95);
for (const box of boxes.slice(1)) {
expect(Math.abs(box!.y + box!.height / 2 - (boxes[0]!.y + boxes[0]!.height / 2))).toBeLessThan(2);
expect(box!.x + box!.width).toBeLessThanOrEqual(440);
}
await expect(open.getByText("Open", { exact: true })).toBeHidden();
await expect.poll(() => projects.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await search.fill("tokio");
await expect(list.getByRole("option")).toHaveCount(1);
await expect(list.getByRole("option")).toContainText("tokio");
await more.press("Enter");
const menu = page.getByRole("menu", { name: "More Actions" });
for (const label of ["New File", "Open File", "Remote Development"]) {
await expect(menu.getByRole("menuitem", { name: new RegExp(label) })).toBeVisible();
}
await page.keyboard.press("Escape");
await expect(menu).toBeHidden();
await expect(more).toBeFocused();
await expect(search).toHaveValue("tokio");
});
Binary file not shown.
@@ -120,17 +120,6 @@ public final class OpenIdeaJdbc {
n++;
}
}
} else if (op.equals("schemaColumns")) {
// Every column of the namespace in one call (SQL completion), without primary keys.
header(out, "table", "name", "type", "nullable", "default");
try (ResultSet rs = m.getColumns(catalog, schema, "%", "%")) {
int n = 0;
while (rs.next() && n < 100000) {
row(out, rs.getString("TABLE_NAME"), rs.getString("COLUMN_NAME"), rs.getString("TYPE_NAME"),
rs.getInt("NULLABLE") == 0 ? "0" : "1", rs.getString("COLUMN_DEF"));
n++;
}
}
} else {
header(out, "name", "type", "nullable", "default", "primary");
String table = a.get(1);
@@ -244,7 +233,7 @@ public final class OpenIdeaJdbc {
switch (op) {
case "open" -> open(a, reply);
case "schemas" -> schemas(reply);
case "tables", "columns", "schemaColumns" -> metadata(op, a, reply);
case "tables", "columns" -> metadata(op, a, reply);
case "namespace" -> {
header(reply, "namespace");
String name = null;
@@ -254,20 +243,6 @@ public final class OpenIdeaJdbc {
} catch (SQLException | AbstractMethodError ignored) {}
row(reply, name);
}
case "valid" -> {
// After a failed statement: whether the session survived (a dropped TCP
// connection leaves every later statement failing until the IDE reconnects).
header(reply, "valid");
boolean valid;
try {
valid = connection != null && !connection.isClosed() && connection.isValid(5);
} catch (AbstractMethodError | SQLFeatureNotSupportedException e) {
valid = true; // A pre-JDBC 4 driver cannot tell: keep the session.
} catch (SQLException e) {
valid = false;
}
row(reply, Boolean.toString(valid));
}
case "page" -> execute(work, a, reply, true);
case "query" -> {
if (a.size() == 3 || a.get(3).isEmpty()) {
-32
View File
@@ -14,7 +14,6 @@ import java.util.logging.Logger;
public class SelfTest {
public static class Fixture implements Driver {
private boolean readonly;
private boolean dropped;
private int changes;
private Path started;
@@ -30,12 +29,6 @@ public class SelfTest {
case "getDatabaseProductName" -> "Fixture";
case "getDatabaseProductVersion" -> "1";
case "getIdentifierQuoteString" -> "\"";
case "getSearchStringEscape" -> "\\";
case "getSchemas" -> rows(List.of(Map.of("TABLE_SCHEM", "app")));
case "getColumns" -> "app".equals(a[1]) && "%".equals(a[2]) ? rows(List.of(
Map.of("TABLE_NAME", "orders", "COLUMN_NAME", "id", "TYPE_NAME", "INT", "NULLABLE", 0),
Map.of("TABLE_NAME", "orders", "COLUMN_NAME", "note", "TYPE_NAME", "VARCHAR", "NULLABLE", 1,
"COLUMN_DEF", "'none'"))) : rows(List.of());
default -> throw new SQLFeatureNotSupportedException();
});
return proxy(Connection.class, (p, m, a) -> switch (m.getName()) {
@@ -43,21 +36,6 @@ public class SelfTest {
case "getMetaData" -> meta;
case "close" -> null;
case "createStatement" -> statement();
case "isClosed" -> false;
case "isValid" -> !dropped;
case "getCatalog" -> null;
default -> throw new SQLFeatureNotSupportedException();
});
}
/** A forward-only result set over `data`, read by column label. */
static ResultSet rows(List<Map<String, Object>> data) {
int[] at = {-1};
return proxy(ResultSet.class, (p, m, a) -> switch (m.getName()) {
case "next" -> ++at[0] < data.size();
case "getString" -> (String) data.get(at[0]).get((String) a[0]);
case "getInt" -> (Integer) data.get(at[0]).getOrDefault((String) a[0], 0);
case "close" -> null;
default -> throw new SQLFeatureNotSupportedException();
});
}
@@ -75,7 +53,6 @@ public class SelfTest {
throw new SQLException("statement cancelled");
}
if (sql.equals("write") && readonly) throw new SQLException("read-only");
if (sql.equals("drop")) { dropped = true; throw new SQLException("connection reset"); }
changes++;
yield false;
}
@@ -145,15 +122,6 @@ public class SelfTest {
send(out, 5, "query", "after cancel", "0", "2");
var result = reply(in);
assert result[0] == 1 && result[result.length - 1] == 2;
send(out, 6, "valid");
assert new String(reply(in), StandardCharsets.UTF_8).contains("true");
send(out, 7, "query", "drop", "0", "2");
assert reply(in)[0] == 0;
send(out, 8, "valid");
assert new String(reply(in), StandardCharsets.UTF_8).contains("false");
send(out, 9, "schemaColumns", "app");
var columns = new String(reply(in), StandardCharsets.UTF_8);
assert columns.contains("orders") && columns.contains("note") && columns.contains("'none'") : columns;
} finally {
child.destroyForcibly().waitFor();
}
+7 -177
View File
@@ -106,12 +106,7 @@ impl Forward {
type Channels = Arc<Mutex<HashMap<u64, (Channel<ChannelFrame>, u64)>>>;
#[derive(Default)]
pub struct Connections {
windows: Mutex<HashMap<String, Arc<Connection>>>,
/// The connect attempt allowed to publish for each window. A later connect, or a
/// disconnect, supersedes an attempt that is still starting the server.
attempts: Mutex<HashMap<String, u64>>,
}
pub struct Connections(Mutex<HashMap<String, Arc<Connection>>>);
impl Connection {
/// Commands of a remote window that run on this machine follow this machine's decision about the
@@ -148,13 +143,13 @@ impl Connection {
impl Connections {
pub fn get(&self, window: &str) -> Option<Arc<Connection>> {
self.windows.lock().get(window).cloned()
self.0.lock().get(window).cloned()
}
/// The window connected to folder `root` of `target`.
pub fn window_of(&self, target: &RemoteTarget, root: &str) -> Option<String> {
let root = root.trim_end_matches('/');
self.windows
self.0
.lock()
.iter()
// A dev container is one project: its folder there is only known once connected.
@@ -167,131 +162,17 @@ impl Connections {
/// Every connected window.
pub fn all(&self) -> Vec<(String, Arc<Connection>)> {
self.windows.lock().iter().map(|(w, c)| (w.clone(), c.clone())).collect()
}
/// Starts a connect for `window`. An older attempt can no longer publish.
pub fn begin(&self, window: &str) -> u64 {
self.bump(window)
}
fn bump(&self, window: &str) -> u64 {
let mut attempts = self.attempts.lock();
let next = attempts.get(window).copied().unwrap_or(0).wrapping_add(1);
attempts.insert(window.to_owned(), next);
next
}
/// Installs `connection` when `attempt` is still the one [`begin`] returned for `window`.
/// An older attempt leaves the connection a newer one published.
pub fn publish(&self, window: &str, attempt: u64, connection: Arc<Connection>) -> bool {
let attempts = self.attempts.lock();
if attempts.get(window).copied() != Some(attempt) {
return false;
}
if let Some(old) = self.windows.lock().insert(window.to_owned(), connection) {
old.peer.kill();
old.forwards.lock().clear();
}
true
self.0.lock().iter().map(|(w, c)| (w.clone(), c.clone())).collect()
}
pub fn disconnect(&self, window: &str) {
// Invalidate an attempt that has not published yet, or it would put the
// connection back after this disconnect.
self.bump(window);
if let Some(c) = self.windows.lock().remove(window) {
if let Some(c) = self.0.lock().remove(window) {
c.peer.kill();
c.forwards.lock().clear();
}
}
}
/// `ssh://` / `wsl://` / `devcontainer://` location, the same spelling the frontend stores.
pub fn remote_location(target: &RemoteTarget, path: &str) -> String {
let (scheme, name) = match target {
RemoteTarget::Ssh { config } => ("ssh", config.as_str()),
RemoteTarget::Wsl { distro } => ("wsl", distro.as_str()),
RemoteTarget::DevContainer { folder, .. } => ("devcontainer", folder.as_str()),
};
let config = match target {
RemoteTarget::DevContainer { config, .. } if !config.is_empty() => format!(":{}", encode_uri_component(config)),
_ => String::new(),
};
let path = if path.starts_with('/') { path.to_owned() } else { format!("/{path}") };
format!("{scheme}://{}{config}{path}", encode_uri_component(name))
}
/// The remote project a `ssh://`, `wsl://` or `devcontainer://` location names.
pub fn parse_remote_location(location: &str) -> Option<(RemoteTarget, String)> {
let (kind, rest) = if let Some(rest) = location.strip_prefix("ssh://") {
("ssh", rest)
} else if let Some(rest) = location.strip_prefix("wsl://") {
("wsl", rest)
} else {
("devcontainer", location.strip_prefix("devcontainer://")?)
};
let slash = rest.find('/')?;
if slash == 0 {
return None;
}
let authority = &rest[..slash];
let path = rest[slash..].to_owned();
let (name, config) = if kind == "devcontainer" {
match authority.split_once(':') {
Some((name, config)) => (name, config),
None => (authority, ""),
}
} else {
(authority, "")
};
let name = decode_uri_component(name)?;
let config = decode_uri_component(config)?;
if name.is_empty() {
return None;
}
let target = match kind {
"ssh" => RemoteTarget::Ssh { config: name },
"wsl" => RemoteTarget::Wsl { distro: name },
_ => RemoteTarget::DevContainer { folder: name, config },
};
Some((target, path))
}
/// `encodeURIComponent`: the frontend builds locations with it.
fn encode_uri_component(value: &str) -> String {
let mut out = String::new();
for b in value.bytes() {
match b {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'!' | b'~' | b'*' | b'\'' | b'(' | b')' => {
out.push(b as char)
}
_ => out.push_str(&format!("%{b:02X}")),
}
}
out
}
fn decode_uri_component(value: &str) -> Option<String> {
let bytes = value.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%' {
if i + 2 >= bytes.len() {
return None;
}
let hex = std::str::from_utf8(&bytes[i + 1..i + 3]).ok()?;
out.push(u8::from_str_radix(hex, 16).ok()?);
i += 3;
} else {
out.push(bytes[i]);
i += 1;
}
}
String::from_utf8(out).ok()
}
/// Where [`remote_connect`] is (`fraction`: 0..1 of a download / upload).
#[derive(Clone, Copy, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
@@ -631,9 +512,6 @@ pub async fn remote_connect(
});
progress(RemoteStage::Connecting, None);
let label = AppState::owner_window(window.label()).to_owned();
// A later connect or a disconnect supersedes this attempt, so it cannot replace
// the connection that one published — or put one back after it was dropped.
let attempt = state.remote_dev.begin(&label);
let channels: Channels = Arc::default();
let connection_slot: Arc<std::sync::OnceLock<std::sync::Weak<Connection>>> = Arc::default();
let handler = Arc::new(ClientHandler {
@@ -735,14 +613,10 @@ pub async fn remote_connect(
if let RemoteTarget::DevContainer { folder, config } = &target {
forward_configured_ports(&connection, folder, config).await;
}
if !state.remote_dev.publish(&label, attempt, connection.clone()) {
tracing::debug!("{label}: remote connection superseded");
connection.peer.kill();
connection.forwards.lock().clear();
return Err(IdeError::cancelled());
}
state.remote_dev.disconnect(&label);
state.host.close_project(&label);
state.host.mcp_reports.set_remote(&label, std::path::PathBuf::from(&connection.root));
state.remote_dev.0.lock().insert(label.clone(), connection.clone());
let weak = Arc::downgrade(&connection);
let peer = connection.peer.clone();
let auth_plugins = state.plugins.clone();
@@ -767,9 +641,6 @@ pub async fn remote_connect(
sync_plugin_languages(&plugins, &connection, &label).await;
sync_plugin_packages(&plugins, &connection, &label).await;
});
if let Err(error) = crate::window_groups::persist(window.app_handle()).await {
tracing::warn!(%error, "cannot save window session after opening remote project");
}
Ok(RemoteProject { target, root, host, server_version: info.version, os: info.os, commands, project })
}
@@ -1198,29 +1069,6 @@ async fn invoke_reply(peer: &Peer, call: Invoke, entries_timeout: std::time::Dur
mod tests {
use super::*;
#[test]
fn remote_locations_round_trip_like_the_frontend() {
let cases = [
(RemoteTarget::Wsl { distro: "Ubuntu-24.04".into() }, "/home/me/app", "wsl://Ubuntu-24.04/home/me/app"),
(RemoteTarget::Ssh { config: "my box".into() }, "/srv/app", "ssh://my%20box/srv/app"),
(
RemoteTarget::DevContainer { folder: "/work/app".into(), config: "devcontainer.json".into() },
"/workspaces/app",
"devcontainer://%2Fwork%2Fapp:devcontainer.json/workspaces/app",
),
(
RemoteTarget::DevContainer { folder: "/work/app".into(), config: String::new() },
"/workspaces/app",
"devcontainer://%2Fwork%2Fapp/workspaces/app",
),
];
for (target, path, location) in cases {
assert_eq!(remote_location(&target, path), location);
assert_eq!(parse_remote_location(location), Some((target, path.to_owned())));
}
assert!(parse_remote_location(r"\\wsl.localhost\Ubuntu\home\me\app").is_none());
}
#[test]
fn a_command_missing_on_a_server_of_another_version_says_which_versions() {
let missing = || IdeError::unavailable("-32601: command web_url is not available remotely");
@@ -1311,24 +1159,6 @@ mod tests {
}
}
#[tokio::test]
async fn a_later_connect_supersedes_an_earlier_attempt() {
let connections = Connections::default();
let first = connections.begin("main");
let second = connections.begin("main");
let older = Arc::new(connected(RemoteTarget::Wsl { distro: "Ubuntu".into() }, "/home/me/old"));
assert!(!connections.publish("main", first, older.clone()));
assert!(connections.get("main").is_none());
let newer = Arc::new(connected(RemoteTarget::Wsl { distro: "Ubuntu".into() }, "/home/me/new"));
assert!(connections.publish("main", second, newer.clone()));
assert!(Arc::ptr_eq(&connections.get("main").unwrap(), &newer));
connections.disconnect("main");
assert!(connections.get("main").is_none());
assert!(!connections.publish("main", second, newer.clone()));
older.peer.kill();
newer.peer.kill();
}
#[tokio::test]
async fn the_server_does_not_decide_trust_for_commands_run_here() {
let tmp = tempfile::tempdir().unwrap();
+4 -7
View File
@@ -143,11 +143,10 @@ impl AppState {
/// Opens `root` in `window` and records it in the recent projects.
pub fn open_project(&self, window: &str, root: &Path) -> IdeResult<Arc<Project>> {
// A local project replaces a remote one in this window.
self.remote_dev.disconnect(window);
let project = self.host.open_project(window, root)?;
self.record_project(&project)?;
// Drop the remote connection only once the local project is actually open.
// A failed open leaves the window on the host it is still routing to.
self.remote_dev.disconnect(window);
Ok(project)
}
@@ -167,16 +166,14 @@ impl AppState {
/// Opens `window` for editing the loose file `file` (LightEdit); not a recent project.
pub fn open_light(&self, window: &str, file: &Path) -> IdeResult<Arc<Project>> {
let project = self.host.open_light(window, file)?;
self.remote_dev.disconnect(window);
Ok(project)
self.host.open_light(window, file)
}
/// LightEdit without a file (File › New File from a welcome window).
pub fn open_light_empty(&self, window: &str) -> IdeResult<Arc<Project>> {
let project = self.host.open_light_empty(window)?;
self.remote_dev.disconnect(window);
Ok(project)
self.host.open_light_empty(window)
}
/// Called on the event-loop thread (window destruction, the `close_project`
+20 -28
View File
@@ -276,18 +276,10 @@ pub async fn persist(app: &AppHandle) -> IdeResult<()> {
}
let groups = state.groups.lock().groups().to_vec();
let windows = labels_in_order(app);
let project_of = |label: &str| {
if let Some(path) = windows::window_project_path(app, label) {
return Some(path);
}
// Taken its launch, not finished opening: keep the remote location or local folder.
state.pending(label).and_then(|launch| {
launch
.remote
.as_ref()
.map(|remote| PathBuf::from(crate::remote_dev::remote_location(&remote.target, &remote.path)))
.or_else(|| launch.project.clone().map(Into::into))
})
let project_of = |label: &str| match host.project(label) {
Ok(p) => (!p.light).then(|| p.root.clone()),
// A restored window may have taken its launch but not finished opening yet.
Err(_) => state.pending(label).and_then(|l| l.project).map(Into::into),
};
let Some(saved) = ide_workspace::window_groups::session(&groups, &windows, project_of) else {
return Ok(());
@@ -322,13 +314,8 @@ pub async fn restore(app: &AppHandle, caller: &str) -> IdeResult<()> {
}
let state = app.state::<WindowsState>();
let host = app.state::<AppState>();
// A remote window has no local project. Leave the flag clear until this window has
// one, so the call that runs once the connection is up can still restore its siblings.
let Some(root) = windows::window_project_path(app, caller) else {
return Ok(());
};
let settings = ide_host::ops::project::settings_get(&host.host, caller);
if !settings.general.reopen_last_project || state.groups_restored.swap(true, Ordering::SeqCst) {
let project = host.project(caller)?;
if !project.settings.effective().general.reopen_last_project || state.groups_restored.swap(true, Ordering::SeqCst) {
return Ok(());
}
let saved = {
@@ -340,25 +327,30 @@ pub async fn restore(app: &AppHandle, caller: &str) -> IdeResult<()> {
};
// The caller's own group first (it already shows one of its projects), then every other
// group and single window that was open at quit. Missing folders are skipped.
let owns = |group: &ide_workspace::window_groups::SavedWindows| {
group.projects.iter().any(|path| windows::same_saved_project(path, &root))
};
let order = saved.iter().filter(|group| owns(group)).chain(saved.iter().filter(|group| !owns(group)));
let order = saved
.iter()
.filter(|g| g.projects.contains(&project.root))
.chain(saved.iter().filter(|g| !g.projects.contains(&project.root)));
for group in order {
let mut labels = Vec::new();
let mut selected = None;
for path in &group.projects {
let label = if windows::same_saved_project(path, &root) {
let label = if path == &project.root {
Some(caller.to_owned())
} else {
match windows::reopen_saved_window(app, path) {
Ok(Some(w)) => Some(w.label().to_owned()),
Ok(None) => None,
} else if path.is_dir() {
let window = match windows::find_project_window(app, path) {
Some(w) => Ok(w),
None => windows::create_restored_window(app, path.clone()),
};
match window {
Ok(w) => Some(w.label().to_owned()),
Err(e) => {
tracing::warn!("cannot reopen {}: {e}", path.display());
None
}
}
} else {
None
};
if let Some(label) = label {
if group.projects.get(group.selected) == Some(path) {
+1 -99
View File
@@ -211,74 +211,6 @@ pub fn wsl_launch(path: &Path) -> Option<RemoteLaunch> {
Some(RemoteLaunch { target: RemoteTarget::Wsl { distro: w.distro }, path: w.path })
}
/// A saved project path that is a remote location: `ssh://`, `wsl://`, `devcontainer://`,
/// or a `\\wsl.localhost` share remembered before those locations existed.
pub(crate) fn saved_remote(path: &Path) -> Option<RemoteLaunch> {
if let Some(text) = path.to_str()
&& let Some((target, root)) = crate::remote_dev::parse_remote_location(text)
{
return Some(RemoteLaunch { target, path: root });
}
wsl_launch(path)
}
/// What reopening `path` should launch. A remote location is recognised before any stat,
/// so a WSL share that is down still comes back as a remote project.
pub(crate) fn saved_project_launch(path: &Path) -> Option<Launch> {
if let Some(remote) = saved_remote(path) {
return Some(Launch { remote: Some(remote), ..Default::default() });
}
path.is_dir().then(|| Launch { project: Some(path.to_path_buf().into()), ..Default::default() })
}
/// The same project, including a WSL share and the `wsl://` location of that folder.
pub(crate) fn same_saved_project(a: &Path, b: &Path) -> bool {
if a == b {
return true;
}
match (saved_remote(a), saved_remote(b)) {
(Some(left), Some(right)) => {
left.target == right.target && left.path.trim_end_matches('/') == right.path.trim_end_matches('/')
}
_ => false,
}
}
/// The project `label` has open: a remote location (`wsl://` and the rest), else its local root.
pub(crate) fn window_project_path(app: &AppHandle, label: &str) -> Option<PathBuf> {
let state = app.try_state::<AppState>()?;
if let Some(c) = state.remote_dev.get(label) {
return Some(PathBuf::from(crate::remote_dev::remote_location(&c.target, &c.root)));
}
state.project(label).ok().filter(|p| !p.light).map(|p| p.root.clone())
}
/// Reopens a project saved at quit. Remote locations become a remote launch; a missing
/// local folder is skipped. An already connected window is focused instead of duplicated.
pub(crate) fn reopen_saved_window(app: &AppHandle, path: &Path) -> IdeResult<Option<WebviewWindow>> {
let Some(launch) = saved_project_launch(path) else {
return Ok(None);
};
if let Some(remote) = launch.remote.clone() {
let open = app.try_state::<AppState>().and_then(|s| s.remote_dev.window_of(&remote.target, &remote.path));
if let Some(w) = open.and_then(|label| app.get_webview_window(&label)) {
return Ok(Some(w));
}
let title = remote
.path
.trim_end_matches('/')
.rsplit('/')
.next()
.filter(|n| !n.is_empty() && *n != "~")
.map(str::to_owned);
return Ok(Some(create_window_for(app, title, launch, true)?));
}
if let Some(w) = find_project_window(app, path) {
return Ok(Some(w));
}
Ok(Some(create_restored_window(app, path.to_path_buf())?))
}
#[derive(Default)]
pub struct WindowsState {
pub groups: Mutex<ide_workspace::window_groups::WindowGroups>,
@@ -2514,41 +2446,11 @@ mod tests {
let folder = launch_for(share.clone(), true);
let remote =
RemoteLaunch { target: RemoteTarget::Wsl { distro: "Ubuntu".into() }, path: "/home/me/app".into() };
assert_eq!((folder.remote, folder.project, folder.files.len()), (Some(remote.clone()), None, 0));
assert_eq!((folder.remote, folder.project, folder.files.len()), (Some(remote), None, 0));
let file = launch_for(share.join("main.py"), false);
assert_eq!((file.remote, file.project, file.files.len()), (None, None, 1));
}
#[test]
fn a_saved_wsl_project_reopens_as_a_remote_launch_without_the_share() {
let remote =
RemoteLaunch { target: RemoteTarget::Wsl { distro: "Ubuntu".into() }, path: "/home/me/app".into() };
for saved in [r"\\wsl.localhost\Ubuntu\home\me\app", "wsl://Ubuntu/home/me/app", "//wsl$/Ubuntu/home/me/app"] {
let launch = saved_project_launch(Path::new(saved)).expect(saved);
assert_eq!(launch.remote, Some(remote.clone()));
assert!(launch.project.is_none(), "{saved}");
}
assert!(same_saved_project(
Path::new(r"\\wsl.localhost\Ubuntu\home\me\app"),
Path::new("wsl://Ubuntu/home/me/app/")
));
let ssh = saved_project_launch(Path::new("ssh://box/srv/app")).unwrap();
assert_eq!(
ssh.remote,
Some(RemoteLaunch { target: RemoteTarget::Ssh { config: "box".into() }, path: "/srv/app".into() })
);
let container =
saved_project_launch(Path::new("devcontainer://%2Fwork%2Fapp:devcontainer.json/workspaces/app")).unwrap();
assert_eq!(
container.remote,
Some(RemoteLaunch {
target: RemoteTarget::DevContainer { folder: "/work/app".into(), config: "devcontainer.json".into() },
path: "/workspaces/app".into(),
})
);
assert!(saved_project_launch(Path::new("/no/such/local/project-openidea")).is_none());
}
fn p(s: &str) -> PathBuf {
PathBuf::from(s)
}
-2
View File
@@ -3770,8 +3770,6 @@ export type CommitSettings = {
agentModel?: string,
/** That model's thinking level for commit messages; empty keeps the agent's. */
agentEffort?: string,
/** Show the Generate Commit Message with Agent button above the commit message. */
agentButton?: boolean,
};
export type Commit_Deserialize = {
+2 -49
View File
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from "vitest";
import { describe, expect, it } from "vitest";
import { Compartment, EditorState } from "@codemirror/state";
import { Decoration, EditorView, WidgetType } from "@codemirror/view";
import { EditorView } from "@codemirror/view";
import { codeLenses } from "@/editor/api";
import { codeLensExtension, codeLensPositions, declarationStart, groupLenses, indentColumns } from "./codeLens";
@@ -95,50 +95,3 @@ describe("code lens position", () => {
v.destroy();
});
});
describe("inline lens against a folded chip", () => {
const doc = "def f():\n pass\n";
const lenses = [{ pos: 8, title: "1 usage", kind: "usages", order: 10 }];
class FakeChip extends WidgetType {
toDOM() {
const el = document.createElement("span");
el.className = "cm-foldPlaceholder";
el.getBoundingClientRect = () => ({ width: 18 }) as DOMRect;
return el;
}
override eq(other: WidgetType) {
return other instanceof FakeChip;
}
}
it("steps past a folded chip drawn after its anchor and back when it goes away", async () => {
vi.useFakeTimers();
const chip = new Compartment();
const chipDeco = () =>
EditorView.decorations.of(Decoration.set([Decoration.widget({ widget: new FakeChip(), side: 3 }).range(8)]));
const v = new EditorView({
state: EditorState.create({
doc,
extensions: [codeLensExtension, codeLenses.of(lenses), codeLensPositions.of({ usages: "right" }), chip.of([])],
}),
parent: document.body,
});
const inline = v.dom.querySelector<HTMLElement>(".cm-openidea-lensInline")!;
const inner = inline.firstElementChild as HTMLElement;
await vi.advanceTimersByTimeAsync(10);
expect(inner.style.left).toBe("");
// The fold appears after the lens mounted; side 3 mirrors the production DOM order, where
// CodeMirror draws the fold's replace widget after the side-1 line-end anchor.
v.dispatch({ effects: chip.reconfigure(chipDeco()) });
await vi.advanceTimersByTimeAsync(10);
expect(inner.style.left).toBe("calc(var(--openidea-hint-offset) + 18px)");
v.dispatch({ effects: chip.reconfigure([]) });
await vi.advanceTimersByTimeAsync(10);
expect(inner.style.left).toBe("");
v.destroy();
vi.useRealTimers();
});
});
-34
View File
@@ -7,7 +7,6 @@
import { EditorState, Facet, RangeSetBuilder, type Extension } from "@codemirror/state";
import { Decoration, EditorView, WidgetType, type DecorationSet } from "@codemirror/view";
import { codeLenses, type CodeLens } from "@/editor/api";
import { foldChipWidth } from "./folding";
import { showContextMenu } from "@/ui";
import { codeVisionMenuItems } from "../codeVision";
import { LINE_INSET } from "./lineInset";
@@ -100,21 +99,6 @@ class LensWidget extends WidgetType {
return this.key === other.key && this.lenses.every((l, i) => l.run === other.lenses[i]?.run);
}
/** The box parks a fixed offset past its zero-width anchor; a folded chip drawn after the
anchor paints under the box, so the box also steps past the chip's width (folding.ts). */
private stepPastFoldChip(el: HTMLElement) {
const inner = this.inline ? (el.firstElementChild as HTMLElement | null) : el;
if (!inner) return;
const chip = foldChipWidth(el);
if (chip === this.appliedChip) return;
this.appliedChip = chip;
if (chip) inner.style.left = `calc(var(--openidea-hint-offset) + ${chip}px)`;
else inner.style.removeProperty("left");
}
private appliedChip = -1;
private observer: MutationObserver | undefined;
override toDOM(view: EditorView): HTMLElement {
// The inline one shares no class with the row, so none of the row's block styles reach into the line.
const dom: HTMLElement = document.createElement(this.inline ? "span" : "div");
@@ -127,18 +111,6 @@ class LensWidget extends WidgetType {
dom.appendChild(host);
}
this.fill(host, view);
if (this.inline) {
// The chip can appear (or go away) after this widget mounted, hence the observer; the
// element is only measurable once CodeMirror has inserted it, so defer like the blame does.
setTimeout(() => {
if (!dom.isConnected) return;
this.stepPastFoldChip(dom);
const line = dom.closest(".cm-line");
if (!line) return;
this.observer = new MutationObserver(() => this.stepPastFoldChip(dom));
this.observer.observe(line, { childList: true, subtree: true, characterData: true });
}, 0);
}
dom.addEventListener("contextmenu", (e) => {
e.preventDefault();
e.stopPropagation();
@@ -154,7 +126,6 @@ class LensWidget extends WidgetType {
const host = this.inline ? (dom.firstElementChild as HTMLElement | null) : dom;
if (!host) return false;
this.fill(host, view);
if (this.inline) this.stepPastFoldChip(dom);
return true;
}
@@ -203,11 +174,6 @@ class LensWidget extends WidgetType {
return this.inline ? -1 : 16;
}
override destroy(): void {
this.observer?.disconnect();
this.observer = undefined;
}
override ignoreEvent(): boolean {
return true;
}
-39
View File
@@ -8,7 +8,6 @@ import {
backendFolds,
enclosingFoldRange,
expandToLevelEffects,
foldChipWidth,
foldSelectionEffects,
foldsFromRanges,
foldingExtension,
@@ -421,41 +420,3 @@ describe("comment placeholders", () => {
view.destroy();
});
});
describe("foldChipWidth", () => {
function editor(doc: string) {
return new EditorView({
state: EditorState.create({ doc, extensions: [foldingExtension()] }),
parent: document.body,
});
}
it("measures a folded chip drawn after the anchor", () => {
const view = editor("const a = 1\nconst b = 2");
view.dispatch({ effects: foldEffect.of({ from: view.state.doc.line(1).to, to: view.state.doc.line(2).to }) });
// jsdom has no layout: the chip's width is faked like the blame tests' hint boxes.
const chip = view.dom.querySelector(".cm-foldPlaceholder")!;
chip.getBoundingClientRect = () => ({ width: 18 }) as DOMRect;
// Production order: the zero-width anchor sits at the fold start, the chip after it.
const anchor = document.createElement("span");
chip.before(anchor);
expect(foldChipWidth(anchor)).toBe(18);
view.destroy();
});
it("is zero with no chip on the line, or when the chip precedes the anchor", () => {
const view = editor("const a = 1\nconst b = 2");
const other = document.createElement("span");
view.dom.querySelectorAll(".cm-line")[1]!.append(other);
expect(foldChipWidth(other)).toBe(0);
view.dispatch({ effects: foldEffect.of({ from: view.state.doc.line(1).to, to: view.state.doc.line(2).to }) });
// A chip earlier in the line (mid-line import folds) cannot overlap a later anchor;
// passing the chip itself as the anchor (nothing precedes itself) is also 0.
const chip = view.dom.querySelector(".cm-foldPlaceholder")!;
chip.getBoundingClientRect = () => ({ width: 18 }) as DOMRect;
const anchor = document.createElement("span");
chip.after(anchor);
expect(foldChipWidth(anchor)).toBe(0);
view.destroy();
});
});
-14
View File
@@ -463,20 +463,6 @@ export function backendFoldingChanged(update: ViewUpdate): boolean {
return update.startState.field(backendFolds, false) !== update.state.field(backendFolds, false);
}
/**
* The folded chip is an in-flow widget drawn at the fold start, which for header-line folds is
* the same position as the zero-width anchors of the line-end annotations (`codeLens.ts`, inline
* blame, plugin messages). Their absolutely positioned boxes park a fixed offset past those
* anchors, so a chip drawn after them paints under (over) the hint. Each consumer measures the
* chip and steps past it, but only when the chip follows its anchor in the DOM — a chip earlier
* in the line (mid-line import folds) already sits before the anchor and cannot overlap.
*/
export function foldChipWidth(el: HTMLElement): number {
const chip = el.closest(".cm-line")?.querySelector(".cm-foldPlaceholder");
if (!chip || !(el.compareDocumentPosition(chip) & Node.DOCUMENT_POSITION_FOLLOWING)) return 0;
return Math.round(chip.getBoundingClientRect().width);
}
export function foldingExtension(showOutline = true): Extension {
return [
// The chevron column sits right of contributed icon gutters (IDEA new UI).
-5
View File
@@ -394,11 +394,6 @@ describe("language modes", () => {
return found;
}
it("colours Go's `default` branch like the other keywords", async () => {
const support = await loadSupport(findLanguageDescription("Go", "/p/main.go")!);
expect(keywords(support!.language, "switch x {\ncase 1:\ndefault:\n}")).toEqual(["switch", "case", "default"]);
});
it("colours TOML keys as keywords in files, lock files and ```toml code blocks", async () => {
for (const path of ["/p/Cargo.toml", "/p/uv.lock"]) {
const support = await loadSupport(findLanguageDescription("TOML", path)!);
-4
View File
@@ -420,9 +420,6 @@ export const JAVA_TAGS: Parameters<typeof styleTags>[0] = {
this: t.keyword,
};
// @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]> = {
JavaScript: JS_TAGS,
@@ -440,7 +437,6 @@ const EXTRA_TAGS: Record<string, Parameters<typeof styleTags>[0]> = {
"MethodDeclaration/Name FunctionDefinition/Name": t.function(t.definition(t.variableName)),
"PropertyDeclaration/VariableDeclarator/VariableName": t.definition(t.propertyName),
},
Go: GO_TAGS,
CSS: CSS_TAGS,
SCSS: CSS_TAGS,
Sass: CSS_TAGS,
+3 -12
View File
@@ -276,23 +276,14 @@ export const openideaTheme = EditorView.theme({
},
".cm-openidea-laneDeleted": {
position: "absolute",
left: "-4px",
top: "-6px",
width: "12px",
height: "12px",
cursor: "pointer",
zIndex: "1",
},
".cm-openidea-laneDeleted::after": {
content: '""',
position: "absolute",
left: "4px",
top: "3px",
left: "0",
top: "-3px",
width: "0",
height: "0",
borderTop: "3px solid transparent",
borderBottom: "3px solid transparent",
borderLeft: "6px solid var(--lane-color)",
zIndex: "1",
},
".cm-foldGutter": { width: "16px" },
".cm-foldGutter .cm-gutterElement": {
@@ -11,37 +11,15 @@
.body {
display: flex;
flex-direction: column;
gap: var(--space-2);
flex: 1;
min-height: 0;
padding: var(--space-3);
}
.split {
flex: 1;
}
.history {
display: flex;
flex-direction: column;
gap: var(--space-1);
height: 100%;
min-height: 0;
padding-bottom: var(--space-2);
}
.toolbar {
display: flex;
flex: none;
align-items: center;
gap: var(--space-2);
}
.filter {
flex: 1;
}
.list {
flex: 1;
flex: 2;
min-height: 84px;
}
.label {
@@ -49,9 +27,7 @@
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
font-family: var(--paste-history-font-family, var(--font-mono));
font-size: var(--paste-history-font-size, var(--fs-code));
font-weight: var(--paste-history-font-weight, normal);
font-family: var(--font-mono);
}
.detail {
@@ -60,12 +36,8 @@
font-size: var(--fs-small);
}
.previewPanel {
padding-top: var(--space-2);
}
.preview {
height: 100%;
flex: 3;
min-height: 0;
overflow: hidden;
border: 1px solid var(--border-strong);
+40 -65
View File
@@ -1,7 +1,7 @@
import { useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type KeyboardEvent } from "react";
import { useEffect, useLayoutEffect, useRef, useState, type KeyboardEvent } from "react";
import { create } from "zustand";
import { EditorState } from "@codemirror/state";
import { EditorView, highlightSpecialChars } from "@codemirror/view";
import { EditorView, highlightSpecialChars, lineNumbers } from "@codemirror/view";
import { language, syntaxHighlighting } from "@codemirror/language";
import { tx } from "@/platform/i18n";
import { isImeKey } from "@/platform/ime";
@@ -9,14 +9,11 @@ import { executeAction, registerActions } from "@/platform/actions";
import { setContext } from "@/platform/context";
import { bindingsFor, normalizeBinding, strokeOf } from "@/platform/keymap";
import {
Button,
Dialog,
IconButton,
List,
SearchField,
SINGLE_FIRST,
SplitGroup,
SplitHandle,
SplitPanel,
T,
isRowSelected,
listNavigate,
@@ -25,11 +22,9 @@ import {
selectableText,
selectedRows,
} from "@/ui";
import { useRowHeight } from "@/ui/density";
import { clipLabel, clipboardHistory, removeClipboardEntries } from "../clipboardHistory";
import { openideaHighlightStyle } from "../cm/highlight";
import { compartments } from "../cm/setup";
import { fontZoom } from "../cm/prefs";
import { openideaTheme } from "../cm/theme";
import styles from "./PasteHistoryDialog.module.css";
@@ -87,11 +82,6 @@ function PasteHistoryDialog({ view, paste, onClose }: Request & { onClose: () =>
const [entries, setEntries] = useState(clipboardHistory);
const [query, setQuery] = useState("");
const [selection, setSelection] = useState(SINGLE_FIRST);
const [editorFont] = useState(() => {
const { fontFamily, fontSize, fontWeight } = getComputedStyle(view.contentDOM);
return { fontFamily, fontSize, fontWeight };
});
const rowHeight = Math.max(useRowHeight(), Math.ceil(Number.parseFloat(editorFont.fontSize) || 0) + 8);
const search = useRef<HTMLInputElement>(null);
const rows = entries
.filter(({ text }) => text.toLocaleLowerCase().includes(query.toLocaleLowerCase()))
@@ -166,7 +156,7 @@ function PasteHistoryDialog({ view, paste, onClose }: Request & { onClose: () =>
title="Choose Content to Paste"
onClose={onClose}
className={styles.dialog}
width={560}
width={680}
resizable="both"
minWidth={360}
minHeight={320}
@@ -179,63 +169,48 @@ function PasteHistoryDialog({ view, paste, onClose }: Request & { onClose: () =>
},
{ label: "Cancel", role: "cancel" },
]}
footerStart={
<Button disabled={!selected.length} onClick={runRemove}>
<T>Delete</T>
</Button>
}
>
<div
className={styles.body}
style={
{
"--paste-history-font-family": editorFont.fontFamily,
"--paste-history-font-size": editorFont.fontSize,
"--paste-history-font-weight": editorFont.fontWeight,
} as CSSProperties
}
onKeyDown={onKeyDown}
onFocusCapture={(e) => setContext("pasteHistoryListFocus", !!e.target.closest('[role="listbox"]'))}
onBlurCapture={() => setContext("pasteHistoryListFocus", false)}
>
<SplitGroup orientation="vertical" storageKey="openidea.editor.pasteHistory" className={styles.split}>
<SplitPanel id="clipboard" defaultSize="30%" minSize="96px">
<div className={styles.history}>
<div className={styles.toolbar}>
<IconButton icon="minus" size="small" title="Delete" disabled={!selected.length} onClick={runRemove} />
<SearchField
ref={search}
className={styles.filter}
data-autofocus=""
aria-label="Filter clipboard history"
placeholder="Filter clipboard history"
value={query}
onChange={filter}
/>
</div>
<List
items={rows}
getKey={(row) => row.key}
activeIndex={selection.lead}
onSelect={(index, e) => setSelection(selectRow(rows, selection, index, rowSelectionMode(e)))}
isSelected={(row) => isRowSelected(selection, row.key)}
onActivate={(row, _index, e) => {
if (e.type === "keydown") runPaste();
else if (e.detail === 2) runPaste(row.key);
}}
rowHeight={rowHeight}
className={styles.list}
aria-label={tx("Clipboard history")}
empty={<T>{entries.length ? "No matches" : "Nothing to paste: the clipboard history is empty"}</T>}
renderItem={(row) => (
<>
<span className={styles.label}>{row.label}</span>
<span className={styles.detail}>{row.detail ?? tx("1 line")}</span>
</>
)}
/>
</div>
</SplitPanel>
<SplitHandle aria-label={tx("Resize paste preview")} />
<SplitPanel id="preview" defaultSize="70%" minSize="100px" className={styles.previewPanel}>
<PastePreview source={view} text={preview} />
</SplitPanel>
</SplitGroup>
<SearchField
ref={search}
data-autofocus=""
aria-label="Filter clipboard history"
placeholder="Filter clipboard history"
value={query}
onChange={filter}
/>
<List
items={rows}
getKey={(row) => row.key}
activeIndex={selection.lead}
onSelect={(index, e) => setSelection(selectRow(rows, selection, index, rowSelectionMode(e)))}
isSelected={(row) => isRowSelected(selection, row.key)}
onActivate={(row, _index, e) => {
if (e.type === "keydown") runPaste();
else if (e.detail === 2) runPaste(row.key);
}}
rowHeight={28}
className={styles.list}
aria-label={tx("Clipboard history")}
empty={<T>{entries.length ? "No matches" : "Nothing to paste: the clipboard history is empty"}</T>}
renderItem={(row) => (
<>
<span className={styles.label}>{row.label}</span>
<span className={styles.detail}>{row.detail ?? tx("1 line")}</span>
</>
)}
/>
<PastePreview source={view} text={preview} />
</div>
</Dialog>
);
@@ -253,11 +228,11 @@ function PastePreview({ source, text }: { source: EditorView; text: string }) {
syntaxHighlighting(openideaHighlightStyle),
source.state.facet(language)?.extension ?? [],
compartments.font.get(source.state) ?? [],
fontZoom.init(() => source.state.field(fontZoom, false) ?? 0),
EditorState.tabSize.of(source.state.tabSize),
EditorState.readOnly.of(true),
EditorView.editable.of(false),
EditorView.contentAttributes.of({ "aria-label": tx("Paste preview"), class: selectableText, tabindex: "0" }),
lineNumbers(),
highlightSpecialChars(),
],
}),
+3 -8
View File
@@ -2,9 +2,8 @@
* The documentation view with its history toolbar, as IDEA's one documentation
* component: the F1 popup, the hover and the Documentation tool window show it.
*/
import { useLayoutEffect, useRef, type KeyboardEvent } from "react";
import { useEffect, useRef, type KeyboardEvent } from "react";
import { createRoot } from "react-dom/client";
import { flushSync } from "react-dom";
import clsx from "clsx";
import { useStore } from "zustand";
import { IconButton, selectableText } from "@/ui";
@@ -24,9 +23,7 @@ import styles from "./Popups.module.css";
export function DomContent({ build, className }: { build: () => HTMLElement; className?: string }) {
const ref = useRef<HTMLDivElement>(null);
// Build the body before paint: the popup is measured as soon as it is created, so an empty first
// frame would be placed and then moved once the text appeared.
useLayoutEffect(() => {
useEffect(() => {
const el = ref.current;
if (!el) return;
const node = build();
@@ -116,8 +113,6 @@ function HoverDocView({ doc }: { doc: HoverDoc }) {
/** Mounts a hover's documentation into its CodeMirror tooltip; returns its unmount. */
export function mountHoverDoc(el: HTMLElement, doc: HoverDoc): () => void {
const root = createRoot(el);
// Render before returning: CodeMirror measures the tooltip right after `create()`, so a popup
// that is still empty at that point is placed a second time when the text arrives.
flushSync(() => root.render(<HoverDocView doc={doc} />));
root.render(<HoverDocView doc={doc} />);
return () => queueMicrotask(() => root.unmount());
}
+4 -6
View File
@@ -261,7 +261,7 @@ describe("hover documentation", () => {
const frame = (el: Element) => el.querySelector<HTMLElement>('[data-lsp-doc="hover"]')!;
afterEach(() => document.body.replaceChildren());
it("shows the hovered documentation in the same view as F1's, laid out when create() returns", async () => {
it("shows the hovered documentation in the same view as F1's", async () => {
const docHover: ContributedHover = (state, pos) => {
const w = state.wordAt(pos);
return w ? { from: w.from, to: w.to, markdown: "hovered docs" } : null;
@@ -275,13 +275,11 @@ describe("hover documentation", () => {
});
const tooltip = await hoverSource(view, 2);
let created!: { dom: HTMLElement; destroy: () => void };
// Asserted inside a synchronous act(): `create()` has to leave a laid-out popup behind, since
// CodeMirror places the tooltip in the measure pass that follows it.
act(() => {
await act(async () => {
created = tooltip!.create() as typeof created;
expect(frame(created.dom).textContent).toContain("hovered docs");
document.body.appendChild(created.dom);
});
await act(async () => void document.body.appendChild(created.dom));
expect(frame(created.dom).textContent).toContain("hovered docs");
expect(screen.getByRole("button", { name: "Back" })).toBeTruthy();
created.destroy();
view.destroy();
+2 -40
View File
@@ -35,10 +35,6 @@ import {
import styles from "./AgentList.module.css";
const errorText = (e: unknown) => (e instanceof Error ? e.message : String(e));
const COPILOT_GITHUB_ACCOUNT_ENV = "OPENIDEA_COPILOT_GITHUB_ACCOUNT";
const launchEnv = (env: Record<string, string>) =>
Object.fromEntries(Object.entries(env).filter(([name]) => name !== COPILOT_GITHUB_ACCOUNT_ENV));
/** How often the page checks on installs it did not start. */
const BACKGROUND_POLL_MS = 1500;
@@ -823,26 +819,13 @@ function ProviderSettings({
onChanged?.();
return command === agent.defaultProgram ? "" : (command ?? "");
});
const accountBase = agent.env[COPILOT_GITHUB_ACCOUNT_ENV] ?? "";
const account = form.useExternal(`agents.${agent.id}.githubAccount`, accountBase, async (draft) => {
const next = { ...agent.env };
const value = draft.trim();
if (value) next[COPILOT_GITHUB_ACCOUNT_ENV] = value;
else delete next[COPILOT_GITHUB_ACCOUNT_ENV];
await backend.setEnv(agent.id, next);
await refresh();
onChanged?.();
return value;
});
const envBase = formatEnv(launchEnv(agent.env));
const envBase = formatEnv(agent.env);
const env = form.useExternal(`agents.${agent.id}.env`, envBase, async (draft) => {
const parsed = parseEnv(draft);
const account = agent.env[COPILOT_GITHUB_ACCOUNT_ENV];
if (account) parsed[COPILOT_GITHUB_ACCOUNT_ENV] = account;
await backend.setEnv(agent.id, parsed);
await refresh();
onChanged?.();
return formatEnv(launchEnv(parsed));
return formatEnv(parsed);
});
const [error, setError] = useState<string | null>(null);
// An edit can have been staged by a previous page instance. Its Apply callback
@@ -866,27 +849,6 @@ function ProviderSettings({
</Section>
<Section title="Launch">
<div className={styles.form}>
{agent.id === "copilot" && (
<Row
label={<T>GitHub account</T>}
htmlFor={`agent-github-account-${agent.id}`}
hint={
<T>
Leave empty to use the active GitHub CLI account. OpenIDEA resolves the token at launch and never
stores it.
</T>
}
>
<Input
id={`agent-github-account-${agent.id}`}
mono
value={account.value}
disabled={account.saving}
placeholder="github-username"
onChange={(e) => account.set(e.target.value)}
/>
</Row>
)}
<Row label={<T>Command</T>}>
<code className={styles.launch} title={launch}>
{launch}
+20 -46
View File
@@ -113,18 +113,10 @@
.spacer {
flex: 1;
}
.configPicker,
.modelControl {
.configPicker {
display: flex;
min-width: 0;
}
.modelControl {
align-items: center;
}
.modelDetail {
box-shadow: inset 1px 0 var(--border);
color: var(--fg-muted);
}
.configPicker > button {
max-width: 100%;
}
@@ -227,39 +219,37 @@
color: var(--fg-muted);
cursor: default;
}
/* The model popup's top: effort (and context size) as segmented controls. */
.quickSettings {
display: flex;
flex-direction: column;
gap: var(--space-3);
padding: 4px 12px 10px;
gap: var(--space-1-5);
padding: 4px 10px 10px;
margin-bottom: 4px;
border-bottom: 1px solid var(--border);
}
.modelSettingsHeader {
.quickRow {
display: flex;
align-items: center;
gap: var(--space-2);
}
.modelSettingsHeader strong {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.quickRow {
display: flex;
flex-direction: column;
gap: var(--space-1);
.quickRow > .segmented {
flex: 1;
min-width: 0;
}
.quickLabel {
color: var(--fg-secondary);
flex: none;
width: 72px;
color: var(--fg-muted);
font-size: var(--fs-small);
font-weight: 600;
}
/* A model's configure button shows on its row's hover only. */
.modelEffortPopup [role="option"] .modelRowConfigure {
opacity: 0;
}
.modelEffortPopup [role="option"]:hover .modelRowConfigure,
.modelEffortPopup [role="option"][aria-selected="true"] .modelRowConfigure,
.modelEffortPopup [role="option"]:focus-within .modelRowConfigure,
.modelEffortPopup [role="option"] .currentRowSettings {
.modelEffortPopup .modelRowConfigure:focus-visible {
opacity: 1;
}
.modelRowConfigure {
@@ -274,23 +264,6 @@
color: var(--fg-muted);
cursor: pointer;
}
.modelRowSettings {
display: inline-flex;
align-items: center;
gap: var(--space-0-5);
width: auto;
max-width: 120px;
padding-inline: 4px;
font-size: var(--fs-small);
}
.modelRowSettings span {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.modelRowSettings svg {
flex: none;
}
.modelRowConfigure:hover,
.modelRowConfigure:focus-visible {
outline: none;
@@ -353,7 +326,7 @@
outline-offset: -2px;
}
.segmentActive {
background: var(--bg-toolbar-hover);
background: var(--bg-floating-toolbar);
color: var(--fg-strong);
font-weight: 600;
}
@@ -428,12 +401,13 @@
text-overflow: ellipsis;
white-space: nowrap;
}
.chipDetail {
/* Details give way to the names, except the model's effort and context: the model's
name truncates first, since they are only shown here. */
.chipDetail:not(.modelDetail) {
display: none;
}
.modelDetail {
flex-shrink: 0;
max-width: 65%;
flex: none;
}
.inlineSetting {
display: none;
+13 -13
View File
@@ -340,10 +340,10 @@ describe("model settings", () => {
render(<ConfigPickers config={copilotConfig()} onChange={onChange} />);
const model = screen.getByRole("button", { name: "Model" });
expect(model).toHaveTextContent("Claude Sonnet 5.5");
const settings = screen.getByRole("button", { name: "Model settings: medium" });
expect(model).toHaveTextContent("medium");
expect(screen.getByRole("button", { name: "Mode" })).toHaveTextContent("AgentAllow All");
fireEvent.click(settings);
const dialog = screen.getByRole("dialog", { name: "Model settings" });
fireEvent.click(model);
const dialog = screen.getByRole("dialog", { name: "Model" });
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" }));
@@ -364,8 +364,10 @@ describe("model settings", () => {
: o,
);
render(<ConfigPickers config={config} onChange={onChange} />);
fireEvent.click(screen.getByRole("button", { name: "Model settings: Max" }));
const dialog = screen.getByRole("dialog", { name: "Model settings" });
const model = screen.getByRole("button", { name: "Model" });
expect(model).toHaveTextContent("Max");
fireEvent.click(model);
const dialog = screen.getByRole("dialog", { name: "Model" });
expect(within(dialog).queryByRole("radiogroup", { name: "Effort Level" })).not.toBeInTheDocument();
fireEvent.click(within(dialog).getByRole("button", { name: /Reasoning Effort/ }));
fireEvent.click(screen.getByRole("option", { name: /Extra high/ }));
@@ -387,12 +389,12 @@ describe("model settings", () => {
];
render(<ConfigPickers config={config} onChange={vi.fn()} />);
expect(screen.queryByRole("switch", { name: "Fast" })).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Model settings: Fast: Off" }));
const dialog = screen.getByRole("dialog", { name: "Model settings" });
fireEvent.click(screen.getByRole("button", { name: "Model" }));
const dialog = screen.getByRole("dialog", { name: "Model" });
expect(within(dialog).getByRole("switch", { name: "Fast" })).toHaveAttribute("aria-checked", "false");
});
it("opens settings from the selected row without choosing it and returns to a pinnable model list", () => {
it("lists models by name in one page, with context size, cost and pinning", () => {
const onChange = vi.fn();
const cfg = copilotConfig().map((o) =>
o.id === "model"
@@ -417,15 +419,14 @@ describe("model settings", () => {
render(<ConfigPickers config={cfg} onChange={onChange} />);
const model = screen.getByRole("button", { name: "Model" });
expect(model).toHaveTextContent("Claude Sonnet 5.5");
expect(screen.getByRole("button", { name: /^Model settings:/ })).toHaveTextContent("medium · 1M");
expect(model).toHaveTextContent("medium");
expect(model).toHaveTextContent("1M");
expect(model).toHaveAttribute("title", expect.stringContaining("Effort Level: medium · Context Size: 1M"));
fireEvent.click(model);
const dialog = screen.getByRole("dialog", { name: "Model" });
expect(within(dialog).queryByText("Balanced")).not.toBeInTheDocument();
expect(within(dialog).getByText("Medium cost")).toBeVisible();
expect(within(dialog).queryByRole("radio")).not.toBeInTheDocument();
fireEvent.click(within(dialog).getByRole("button", { name: "Configure Claude Sonnet 5.5…" }));
expect(onChange).not.toHaveBeenCalled();
const effortGroup = within(dialog).getByRole("radiogroup", { name: "Effort Level" });
expect(within(effortGroup).getByRole("radio", { name: "medium" })).toHaveAttribute("aria-checked", "true");
@@ -434,7 +435,6 @@ describe("model settings", () => {
fireEvent.click(within(contextGroup).getByRole("radio", { name: "200K" }));
expect(onChange).toHaveBeenCalledWith("contextTier", "default");
fireEvent.click(within(dialog).getByRole("button", { name: "Back to models" }));
fireEvent.click(within(dialog).getAllByRole("button", { name: "Pin model" })[0]!);
const listbox = within(dialog).getByRole("listbox", { name: "Model" });
expect(within(listbox).getByText("Pinned")).toBeVisible();
+139 -218
View File
@@ -1,5 +1,7 @@
/**
* Model and settings controls shared by the New Task and session composers.
* Model, effort, mode and approvals controls for a composer's bottom row. The model button
* opens a searchable model list (pinned models first) and keeps effort and context settings
* together above it.
*/
import { useEffect, useRef, useState, type KeyboardEvent } from "react";
import clsx from "clsx";
@@ -76,8 +78,6 @@ function switchValues(option: AgentConfigOption): { on: string; off: string } |
const selected = (option: AgentConfigOption, value: string | null) =>
option.values.find((v) => v.value === value) ?? null;
type ChangeOption = (option: string, value: string, forModel?: string) => void;
interface ModelRefresh {
draft?: boolean;
refreshing: boolean;
@@ -86,12 +86,6 @@ interface ModelRefresh {
error: string | null;
onOpen?: () => void;
onRefresh: () => void;
preview?: {
/** Undefined until discovery; an empty array means the agent reported no settings. */
settingsFor: (model: string) => AgentConfigOption[] | undefined;
load: (model: string) => void;
errorFor: (model: string) => string | null | undefined;
};
}
export function ConfigPickers({
@@ -103,7 +97,7 @@ export function ConfigPickers({
config: readonly AgentConfigOption[];
/** Chosen values that override `current`, by option id. */
values?: Record<string, string>;
onChange: ChangeOption;
onChange: (option: string, value: string) => void;
modelRefresh?: ModelRefresh;
}) {
const tx = useTx();
@@ -151,9 +145,10 @@ export function ConfigPickers({
<ModelPicker
model={o}
modelValue={valueOf(o)}
settings={(tuckedEffort ? [tuckedEffort, ...modelConfigs] : modelConfigs)
.filter((opt) => opt.values.length > 0)
.map((opt) => ({ ...opt, current: valueOf(opt) }))}
modelConfigs={modelConfigs}
effort={tuckedEffort}
effortValue={tuckedEffort ? valueOf(tuckedEffort) : null}
valueOf={valueOf}
onChange={onChange}
modelRefresh={modelRefresh}
/>
@@ -262,255 +257,181 @@ function ConfigPicker({
}
/** Effort levels that fit the popup's segmented control; more (Codex has six) get a dropdown. */
const SEGMENTED_EFFORT_MAX = 5;
function settingName(option: AgentConfigOption) {
return option.category === "thought_level"
? "Effort Level"
: isContextOption(option.id)
? "Context Size"
: option.name;
}
function settingValue(option: AgentConfigOption) {
return selected(option, option.current) ?? option.values[0];
}
function settingsSummary(options: AgentConfigOption[], tx: ReturnType<typeof useTx>) {
return options
.map((o) => {
const label = settingValue(o)?.name ?? tx("Default");
return o.category === "thought_level" || isContextOption(o.id) ? label : `${tx(o.name)}: ${label}`;
})
.join(" · ");
}
const SEGMENTED_EFFORT_MAX = 4;
/** The model button: a searchable model list, with effort, context size and model settings above it. */
function ModelPicker({
model,
modelValue,
settings,
modelConfigs,
effort,
effortValue,
valueOf,
onChange,
modelRefresh,
}: {
model: AgentConfigOption;
modelValue: string | null;
settings: AgentConfigOption[];
onChange: ChangeOption;
modelConfigs: AgentConfigOption[];
effort: AgentConfigOption | null;
effortValue: string | null;
valueOf: (o: AgentConfigOption) => string | null;
onChange: (option: string, value: string) => void;
modelRefresh?: ModelRefresh;
}) {
const tx = useTx();
const [page, setPage] = useState<"models" | { model: string | null } | null>(null);
const [open, setOpen] = useState(false);
const pinnedModels = useAgents((s) => s.pinnedModels);
const anchor = useRef<HTMLSpanElement>(null);
const anchor = useRef<HTMLButtonElement>(null);
const selectedModel = selected(model, modelValue);
const unavailable = !!modelRefresh && modelValue !== null && !selectedModel;
const unavailable = modelRefresh?.draft && modelValue !== null && !selectedModel;
const modelName = unavailable
? tx`${modelValue} (unavailable)`
: (selectedModel?.name ?? (modelRefresh ? modelValue : null) ?? tx("Default"));
const summary = settingsSummary(settings, tx);
const settingsFor = (id: string | null) =>
id === modelValue ? settings : id ? modelRefresh?.preview?.settingsFor(id) : undefined;
const details = page && page !== "models" && (page.model === modelValue || selected(model, page.model)) ? page : null;
const inspectedModel = details ? selected(model, details.model) : null;
const openModels = () => {
modelRefresh?.onOpen?.();
setPage("models");
};
const contextOption = modelConfigs.find((o) => isContextOption(o.id) && o.values.length > 0);
const contextValue = contextOption ? valueOf(contextOption) : null;
const contextLabel = contextOption
? ((selected(contextOption, contextValue) ?? contextOption.values[0])?.name ?? null)
: null;
const effortLabel = effort ? ((selected(effort, effortValue) ?? effort.values[0])?.name ?? null) : null;
const otherModelConfigs = modelConfigs.filter((o) => o !== contextOption);
const summary = [
effortLabel ? `${tx("Effort Level")}: ${effortLabel}` : null,
contextLabel ? `${tx("Context Size")}: ${contextLabel}` : null,
...otherModelConfigs.map((o) => {
const current = selected(o, valueOf(o));
return current ? `${tx(o.name)}: ${current.name}` : null;
}),
]
.filter(Boolean)
.join(" · ");
return (
<span ref={anchor} className={styles.modelControl}>
<>
<button
ref={anchor}
type="button"
className={styles.chip}
aria-label={tx(model.name)}
aria-haspopup="dialog"
aria-expanded={!!page && !details}
title={`${tx(model.name)}: ${modelName}`}
onClick={() => (page && !details ? setPage(null) : openModels())}
aria-expanded={open}
title={`${tx(model.name)}: ${modelName}${summary ? ` · ${summary}` : ""}`}
onClick={() => {
if (!open) modelRefresh?.onOpen?.();
setOpen(!open);
}}
>
<span className={styles.chipValue}>{modelName}</span>
{(effortLabel || contextLabel) && (
<span className={clsx(styles.chipDetail, styles.modelDetail)}>
{[effortLabel, contextLabel].filter(Boolean).join(" · ")}
</span>
)}
<Icon name="chevron-down" size={14} className={styles.chipChevron} />
</button>
{summary && !unavailable && (
<button
type="button"
className={clsx(styles.chip, styles.modelDetail)}
aria-label={tx`Model settings: ${summary}`}
title={tx`Configure ${modelName}…`}
aria-haspopup="dialog"
aria-expanded={!!details && details.model === modelValue}
onClick={() => setPage(details && details.model === modelValue ? null : { model: modelValue })}
>
<span className={styles.chipValue}>{summary}</span>
</button>
)}
<Popup
open={!!page}
open={open}
anchor={anchor}
onClose={() => setPage(null)}
aria-label={tx(details ? "Model settings" : "Model")}
onClose={() => setOpen(false)}
aria-label={tx("Model")}
className={styles.modelEffortPopup}
>
{details ? (
<ModelSettings
key={details.model}
id={details.model}
name={inspectedModel?.name ?? modelName}
settings={settingsFor(details.model)}
modelRefresh={modelRefresh}
onBack={openModels}
onChange={(option, value) => {
if (details.model && details.model !== modelValue) onChange(option, value, details.model);
else onChange(option, value);
}}
/>
) : (
<>
{unavailable && (
<p className={styles.catalogError} role="alert">
<T>Choose another model before starting.</T>
</p>
)}
{model.values.length > 0 || !modelRefresh ? (
<SelectListbox
aria-label={tx(model.name)}
value={modelValue}
options={configPickerOptions(model, pinnedModels, false)}
searchable
listClassName={styles.modelList}
onChoose={(v) => {
onChange(model.id, v);
setPage(null);
}}
renderAction={(opt) => {
const raw = model.values.find((v) => v.value === opt.value);
if (!raw) return null;
const pinned = pinnedModels.includes(raw.value);
const rowSettings = settingsFor(raw.value);
const configurable = rowSettings
? rowSettings.some((o) => o.values.length > 0)
: !!modelRefresh?.preview;
return (
<>
<CostBadge category={raw.costCategory} />
<button
type="button"
className={clsx(styles.modelRowConfigure, pinned && styles.pinnedButton)}
aria-label={pinned ? tx("Unpin model") : tx("Pin model")}
aria-pressed={pinned}
title={pinned ? tx("Unpin model") : tx("Pin model")}
onClick={() => togglePinnedModel(raw.value)}
>
<Icon name="pin" size={12} />
</button>
{configurable && (
<button
type="button"
className={clsx(
styles.modelRowConfigure,
styles.modelRowSettings,
raw.value === modelValue && styles.currentRowSettings,
)}
title={tx`Configure ${opt.label}…`}
aria-label={tx`Configure ${opt.label}…`}
aria-haspopup="dialog"
onClick={() => setPage({ model: raw.value })}
>
{rowSettings && <span>{settingsSummary(rowSettings, tx)}</span>}
<Icon name="chevron-right" size={14} />
</button>
)}
</>
);
}}
/>
) : (
<p className={styles.catalogNote} role="status">
{modelRefresh?.refreshing ? <T>Loading models…</T> : <T>No models reported by this agent.</T>}
</p>
)}
{modelRefresh && <ModelRefreshFooter key={modelRefresh.retryAtMs} {...modelRefresh} />}
</>
{unavailable && (
<p className={styles.catalogError} role="alert">
<T>Choose another model before starting.</T>
</p>
)}
</Popup>
</span>
);
}
function ModelSettings({
id,
name,
settings,
modelRefresh,
onBack,
onChange,
}: {
id: string | null;
name: string;
settings: AgentConfigOption[] | undefined;
modelRefresh?: ModelRefresh;
onBack: () => void;
onChange: ChangeOption;
}) {
const tx = useTx();
const attempted = useRef(false);
const lookup = modelRefresh?.preview;
const refreshing = modelRefresh?.refreshing;
useEffect(() => {
if (!id || settings || !lookup || refreshing || attempted.current) return;
attempted.current = true;
lookup.load(id);
}, [id, settings, lookup, refreshing]);
const loading = modelRefresh?.loadingSettings || (!settings && refreshing);
const error = !settings && id && lookup?.errorFor(id);
return (
<div className={styles.quickSettings}>
<div className={styles.modelSettingsHeader}>
<IconButton autoFocus icon="arrow-left" title="Back to models" size="small" onClick={onBack} />
<strong>{name}</strong>
</div>
{loading ? (
<p role="status">
<T>Loading model settings…</T>
</p>
) : error ? (
<p role="alert" className={styles.catalogError}>{tx`Could not refresh models: ${error}`}</p>
) : !settings?.some((o) => o.values.length) ? (
<p role="status">
<T>No settings reported for this model.</T>
</p>
) : (
settings
.filter((o) => o.values.length > 0)
.map((o) => {
const label = tx(settingName(o));
const segmented =
isContextOption(o.id) || (o.category === "thought_level" && o.values.length <= SEGMENTED_EFFORT_MAX);
return (
<div key={o.id} className={styles.quickRow}>
<span className={styles.quickLabel} title={o.description ?? undefined}>
{label}
{(effort || contextOption || otherModelConfigs.length > 0) && (
<div className={styles.quickSettings}>
{effort && (
<div className={styles.quickRow}>
<span className={styles.quickLabel}>
<T>Effort Level</T>
</span>
{segmented ? (
{effort.values.length <= SEGMENTED_EFFORT_MAX ? (
<SegmentedControl
ariaLabel={label}
options={o.values.map((v) => ({
ariaLabel={tx("Effort Level")}
options={effort.values.map((v) => ({
value: v.value,
label: v.name,
description: v.description ?? undefined,
}))}
value={settingValue(o)!.value}
onChange={(v) => onChange(o.id, v)}
value={effortValue ?? effort.values[0]!.value}
onChange={(v) => onChange(effort.id, v)}
/>
) : (
<ConfigPicker option={o} value={o.current} onChange={onChange} framed />
<ConfigPicker option={effort} value={effortValue} onChange={onChange} framed />
)}
</div>
);
})
)}
</div>
)}
{contextOption && (
<div className={styles.quickRow}>
<span className={styles.quickLabel}>
<T>Context Size</T>
</span>
<SegmentedControl
ariaLabel={tx("Context Size")}
options={contextOption.values.map((v) => ({
value: v.value,
label: v.name,
description: v.description ?? undefined,
}))}
value={contextValue ?? contextOption.values[0]!.value}
onChange={(v) => onChange(contextOption.id, v)}
/>
</div>
)}
{otherModelConfigs.map((o) => (
<div key={o.id} className={styles.quickRow}>
<span className={styles.quickLabel} title={o.description ?? undefined}>
{tx(o.name)}
</span>
<ConfigPicker option={o} value={valueOf(o)} onChange={onChange} framed />
</div>
))}
</div>
)}
{model.values.length > 0 || !modelRefresh ? (
<SelectListbox
aria-label={tx(model.name)}
value={modelValue}
options={configPickerOptions(model, pinnedModels, false)}
searchable
listClassName={styles.modelList}
onChoose={(v) => {
onChange(model.id, v);
setOpen(false);
}}
renderAction={(opt) => {
const raw = model.values.find((v) => v.value === opt.value);
if (!raw) return null;
const pinned = pinnedModels.includes(raw.value);
return (
<>
<CostBadge category={raw.costCategory} />
<button
type="button"
className={clsx(styles.modelRowConfigure, pinned && styles.pinnedButton)}
aria-label={pinned ? tx("Unpin model") : tx("Pin model")}
aria-pressed={pinned}
title={pinned ? tx("Unpin model") : tx("Pin model")}
onClick={() => togglePinnedModel(raw.value)}
>
<Icon name="pin" size={12} />
</button>
</>
);
}}
/>
) : (
<p className={styles.catalogNote} role="status">
{modelRefresh?.refreshing ? <T>Loading models…</T> : <T>No models reported by this agent.</T>}
</p>
)}
{modelRefresh && <ModelRefreshFooter key={modelRefresh.retryAtMs} {...modelRefresh} />}
</Popup>
</>
);
}
+11 -10
View File
@@ -90,16 +90,15 @@ beforeEach(() => {
});
const modelButton = () => screen.getByRole("button", { name: "Model" });
const settingsButton = () => screen.getByRole("button", { name: /^Model settings:/ });
async function chooseModel(model: string) {
if (!screen.queryByRole("dialog", { name: "Model" })) fireEvent.click(modelButton());
fireEvent.click(screen.getByTitle(model));
fireEvent.click(screen.getByRole("option", { name: model }));
fireEvent.pointerDown(document.body);
}
async function chooseEffort(effort: string) {
fireEvent.click(settingsButton());
if (!screen.queryByRole("dialog", { name: "Model" })) fireEvent.click(modelButton());
const group = screen.getByRole("radiogroup", { name: "Effort Level" });
fireEvent.click(within(group).getByRole("radio", { name: effort }));
fireEvent.keyDown(document, { key: "Escape" });
@@ -108,14 +107,14 @@ async function chooseEffort(effort: string) {
it("switches model-specific levels and restores each draft effort before starting", async () => {
render(<HomeEditor />);
expect(modelButton()).toHaveTextContent("big");
expect(settingsButton()).toHaveTextContent("high");
expect(modelButton()).toHaveTextContent("high");
await chooseModel("small");
expect(settingsButton()).toHaveTextContent("minimal");
expect(modelButton()).toHaveTextContent("minimal");
await chooseEffort("medium");
await chooseModel("big");
expect(settingsButton()).toHaveTextContent("high");
expect(modelButton()).toHaveTextContent("high");
await chooseModel("small");
expect(settingsButton()).toHaveTextContent("medium");
expect(modelButton()).toHaveTextContent("medium");
fireEvent.click(screen.getByRole("button", { name: "Start" }));
await waitFor(() => expect(backend.create).toHaveBeenCalled());
expect(backend.create.mock.calls[0]![0].config).toEqual([
@@ -144,10 +143,12 @@ it("uses GitHub Copilot's own defaults and preserves per-model context tier and
useAgents.setState({ providers: [copilot], draft: savedDraft({ provider: "copilot", config: {} }) });
render(<HomeEditor />);
expect(modelButton()).toHaveTextContent("gemini-4-carbon");
expect(settingsButton()).toHaveTextContent("medium · default");
expect(modelButton()).toHaveTextContent("medium");
expect(modelButton()).toHaveTextContent("default");
await chooseModel("gpt-5.6-sol");
expect(modelButton()).toHaveTextContent("gpt-5.6-sol");
expect(settingsButton()).toHaveTextContent("medium · default");
expect(modelButton()).toHaveTextContent("medium");
expect(modelButton()).toHaveTextContent("default");
fireEvent.click(screen.getByRole("button", { name: "Start" }));
await waitFor(() => expect(backend.create).toHaveBeenCalled());
expect(backend.create.mock.calls[0]![0].config).toEqual([
@@ -181,7 +182,7 @@ it("ignores old provider-wide effort choices and refreshes unsupported per-model
draft: savedDraft({ provider: "fake", config: { effort: "low" }, thoughtLevels: { big: { effort: "removed" } } }),
});
render(<HomeEditor />);
expect(settingsButton()).toHaveTextContent("high");
expect(modelButton()).toHaveTextContent("high");
fireEvent.click(screen.getByRole("button", { name: "Start" }));
await waitFor(() => expect(backend.create).toHaveBeenCalled());
expect(backend.create.mock.calls[0]![0].config).toContainEqual({ id: "effort", value: "high" });
+2 -17
View File
@@ -23,7 +23,6 @@ import {
HOME,
NO_COMMANDS,
draftConfig,
draftModelSettings,
refreshProviders,
refreshModels,
setDraftMcpOverrides,
@@ -100,8 +99,7 @@ export function HomeEditor({ docked = false, input }: { docked?: boolean; input?
const requestingModels = useAgents((s) => s.modelRequests.has(provider?.id ?? ""));
const requestTarget = useAgents((s) => s.modelRequestTargets.get(provider?.id ?? ""));
const { defaults, fitWindowWidth } = useAgentSettings();
const providerDefaults = (provider && defaults[provider.id]) || {};
const config = draftConfig(provider, draft, providerDefaults);
const config = draftConfig(provider, draft, (provider && defaults[provider.id]) || {});
const model = config.find((o) => o.category === "model");
const selectedModel = model?.current ?? null;
const selectedModelRef = useRef(selectedModel);
@@ -231,10 +229,7 @@ export function HomeEditor({ docked = false, input }: { docked?: boolean; input?
<ConfigPickers
key={provider?.id}
config={config}
onChange={(option, value, forModel) => {
if (forModel && model) setDraftOption(model.id, forModel);
setDraftOption(option, value);
}}
onChange={setDraftOption}
modelRefresh={
provider?.installed
? {
@@ -247,16 +242,6 @@ export function HomeEditor({ docked = false, input }: { docked?: boolean; input?
: null,
error: !requestingModels && currentModelRequest ? (catalog?.error ?? null) : null,
onRefresh: () => void executeAction("agents.refreshModels", null),
preview: {
settingsFor: (id) =>
draftModelSettings(
(catalog ?? provider).thoughtLevels?.[id],
draft.thoughtLevels?.[id],
providerDefaults,
),
load: (id) => void refreshModels(provider.id, false, id),
errorFor: (id) => (requestTarget === id ? catalog?.error : null),
},
}
: undefined
}
+2 -34
View File
@@ -469,7 +469,7 @@ describe("Built-in executable overrides", () => {
dispose();
});
const openCommands = async (commands: FakeCommands, onChanged = vi.fn(), name = "Claude Code") => {
const openCommands = async (commands: FakeCommands, onChanged = vi.fn()) => {
const backend = new FakeBackend();
dispose = registerSettingsPage({
id: REGISTRY_PAGE,
@@ -478,7 +478,7 @@ describe("Built-in executable overrides", () => {
component: () => <RegistryPage backend={backend} commandBackend={commands} onChanged={onChanged} />,
});
render(<SettingsDialog />);
return screen.findByRole("region", { name });
return screen.findByRole("region", { name: "Claude Code" });
};
const apply = () => screen.getByRole("button", { name: "Apply" });
const field = () => screen.getByRole("textbox", { name: "Executable" });
@@ -564,38 +564,6 @@ describe("Built-in executable overrides", () => {
expect(commands.savedEnv.at(-1)).toEqual(["claude", {}]);
});
it("writes a Copilot GitHub account without storing a token or exposing the control variable", async () => {
const commands = new FakeCommands();
commands.list = [
{
...claudeProvider("copilot"),
id: "copilot",
name: "GitHub Copilot",
command: "copilot --acp",
defaultProgram: "copilot",
commandReadOnlyReason: "registry",
env: { COPILOT_TELEMETRY_OPTOUT: "1" },
},
];
await openCommands(commands, vi.fn(), "GitHub Copilot");
const account = screen.getByRole("textbox", { name: "GitHub account" });
expect(screen.queryByRole("textbox", { name: "Environment variables" })).toBeNull();
fireEvent.change(account, { target: { value: "dengliu_microsoft" } });
await act(async () => fireEvent.click(apply()));
expect(commands.savedEnv).toEqual([
[
"copilot",
{
COPILOT_TELEMETRY_OPTOUT: "1",
OPENIDEA_COPILOT_GITHUB_ACCOUNT: "dengliu_microsoft",
},
],
]);
expect(JSON.stringify(commands.savedEnv)).not.toMatch(/gho_|ghp_|token/i);
});
it("Cancel discards command edits without writing", async () => {
const commands = new FakeCommands();
commands.list = [
+2 -17
View File
@@ -6,8 +6,6 @@
import { createElement } from "react";
import { registerActions } from "@/platform/actions";
import { useProject } from "@/platform/project";
import { clearContext, setContext } from "@/platform/context";
import { onWorkflowSettingsChange, workflowSettings } from "@/platform/workflowSettings";
import { executeAction } from "@/platform/actions";
import { lazyComponent, lazyWhen } from "@/ui";
import { isVirtualUri } from "@/platform/virtualDocs";
@@ -49,18 +47,6 @@ import { replyActions } from "./replyActions";
export { activateSettingsPages } from "./settingsPages";
function trackAgentButtonSetting(): () => void {
setContext("commitAgentButton", workflowSettings().vcs.commit.agentButton);
const stop = onWorkflowSettingsChange(
(s) => s.vcs.commit.agentButton,
(on) => setContext("commitAgentButton", on),
);
return () => {
stop();
clearContext("commitAgentButton");
};
}
export function activate(): () => void {
const sync = (root: string | null | undefined) => {
disconnect();
@@ -167,13 +153,12 @@ export function activate(): () => void {
accepts: (type) => type === TASK_DRAG,
drop: ({ payload }) => void executeAction("agents.openTaskInEditor", payload),
}),
// The button above the commit message (the Commit tool window and dialog), unless turned off.
trackAgentButtonSetting(),
// The button above the commit message (the Commit tool window and dialog).
registerMenuSlotItem("commitMessage", {
action: "agents.generateCommitMessage",
label: "Generate Commit Message with Agent",
icon: "toolwindow-agents",
when: "projectOpen && vcsAvailable && commitAgentButton",
when: "projectOpen && vcsAvailable",
}),
registerStatusItem({ id: "agents.status", align: "right", priority: 3, title: "Agents", component: AgentsStatus }),
registerMenuGroup({
+13 -84
View File
@@ -220,7 +220,7 @@ it("refreshes an existing chat's searchable model choices and switches through i
expect(modelButton).toHaveTextContent("old");
expect(screen.getByRole("option", { name: "session-only" })).toBeVisible();
expect(screen.getByRole("button", { name: /^Model settings:/ })).toHaveTextContent("low");
expect(modelButton).toHaveTextContent("low");
expect(screen.getByRole("button", { name: "Mode" })).toHaveTextContent("plan");
expect(screen.getByText("Earlier message")).toBeVisible();
expect(screen.queryByText("catalog-only")).not.toBeInTheDocument();
@@ -251,44 +251,6 @@ it("refreshes an existing chat's searchable model choices and switches through i
expect(useAgents.getState().draft).toBe(draft);
});
it("recovers a model picker after a Copilot ACP fallback removed the session option", async () => {
const task: AgentTask = {
id: "fallback-task",
title: "Recovered chat",
provider: "first",
status: "ready",
isolation: "local",
model: "stale-model",
cwd: "/models",
branch: null,
base: null,
baseCommit: null,
error: null,
createdMs: 0,
updatedMs: 0,
config: [{ ...option("mode", "mode", ["plan", "act"]), name: "Mode" }],
commands: [],
usage: null,
queue: [],
};
const input = { kind: SESSION_KIND, key: sessionKey(task.id), data: { task: task.id } };
backend.providers[0]!.config = [];
backend.tasks = [task];
backend.activeInput = input;
await connect();
backend.refresh.mockResolvedValueOnce(ok(catalog("first", { config: [option("model", "model", ["auto"])] })));
render(<SessionEditor input={input} />);
const modelButton = screen.getByRole("button", { name: "Model" });
expect(modelButton).toHaveTextContent("stale-model (unavailable)");
fireEvent.click(modelButton);
expect(await screen.findByRole("option", { name: "auto" })).toBeVisible();
fireEvent.click(screen.getByRole("option", { name: "auto" }));
expect(backend.refresh).toHaveBeenCalledWith("first", false, null);
expect(backend.setConfig).toHaveBeenCalledExactlyOnceWith("fallback-task", "model", "auto");
});
it("keeps cached choices usable while refreshing and shares the completion/cooldown from another window", async () => {
backend.refresh.mockImplementation(async (id: string) => ok(catalog(id, { refreshing: true })));
render(<HomeEditor />);
@@ -363,7 +325,7 @@ it("retains cached model and effort choices after a command failure and retries
draft: savedDraft({ provider: "first", config: { model: "big" }, thoughtLevels: { big: { effort: "low" } } }),
});
render(<HomeEditor />);
expect(screen.getByRole("button", { name: /^Model settings:/ })).toHaveTextContent("low");
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("low");
fireEvent.click(screen.getByRole("button", { name: "Model" }));
expect(await screen.findByRole("alert")).toHaveTextContent("connection lost");
fireEvent.click(screen.getByRole("option", { name: "small" }));
@@ -390,7 +352,7 @@ it("preserves a valid remembered model and effort when discovery changes the def
render(<HomeEditor />);
await waitFor(() => expect(useAgents.getState().modelRequests.size).toBe(0));
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("big");
expect(screen.getByRole("button", { name: /^Model settings:/ })).toHaveTextContent("low");
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("low");
fireEvent.click(screen.getByRole("button", { name: "Model" }));
expect(screen.getByRole("option", { name: "new" })).toBeVisible();
fireEvent.keyDown(document, { key: "Escape" });
@@ -528,18 +490,16 @@ it("discovers an uncached model's own settings before its first task and restore
),
);
expect(screen.queryByText("Loading model settings…")).not.toBeInTheDocument();
const settings = screen.getByRole("button", { name: /^Model settings:/ });
expect(settings).toHaveTextContent("medium");
fireEvent.click(settings);
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("medium");
fireEvent.click(screen.getByRole("button", { name: "Model" }));
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: "Back to models" }));
fireEvent.click(screen.getByTitle("big"));
expect(settings).toHaveTextContent("high");
fireEvent.click(screen.getByRole("option", { name: "big" }));
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("high");
fireEvent.click(screen.getByRole("button", { name: "Model" }));
fireEvent.click(screen.getByTitle("small"));
expect(settings).toHaveTextContent("max");
fireEvent.click(screen.getByRole("option", { name: "small" }));
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("max");
expect(backend.refresh).toHaveBeenCalledTimes(2);
fireEvent.click(screen.getByRole("button", { name: "Start" }));
await waitFor(() => expect(backend.create).toHaveBeenCalled());
@@ -557,44 +517,13 @@ it("does not rediscover a model that explicitly reports no per-model controls",
await waitFor(() => expect(useAgents.getState().modelRequests.size).toBe(0));
for (const model of ["small", "big", "small"]) {
fireEvent.click(screen.getByRole("button", { name: "Model" }));
fireEvent.click(screen.getByTitle(model));
fireEvent.click(screen.getByRole("option", { name: model }));
}
expect(backend.refresh).toHaveBeenCalledExactlyOnceWith("first", false, "big");
expect(screen.queryByText("Loading model settings…")).not.toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Reasoning" })).not.toBeInTheDocument();
});
it("inspects uncached settings without switching models or borrowing the current model's levels", async () => {
delete backend.providers[0]!.thoughtLevels!.small;
await connect();
render(<HomeEditor />);
await waitFor(() => expect(useAgents.getState().modelRequests.size).toBe(0));
const pending = deferred<CatalogReply>();
backend.refresh.mockReturnValueOnce(pending.promise);
fireEvent.click(screen.getByRole("button", { name: "Model" }));
fireEvent.click(screen.getByRole("button", { name: "Configure small…" }));
expect(backend.refresh).toHaveBeenLastCalledWith("first", false, "small");
expect(screen.getByRole("status")).toHaveTextContent("Loading model settings…");
expect(screen.queryByRole("radio")).not.toBeInTheDocument();
await act(async () =>
pending.resolve(
ok(
catalog("first", {
thoughtLevels: {
...catalog().thoughtLevels,
small: [option("effort", "thought_level", ["quick", "thorough"])],
},
}),
),
),
);
expect(screen.getByRole("radio", { name: "quick" })).toBeVisible();
fireEvent.click(screen.getByRole("button", { name: "Back to models" }));
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("big");
expect(backend.setConfig).not.toHaveBeenCalled();
expect(backend.create).not.toHaveBeenCalled();
});
it("waits for an unrelated lookup and discovers only the latest selected model", async () => {
backend.providers[0]!.config = [option("model", "model", ["big", "small", "latest"])];
await connect();
@@ -620,7 +549,7 @@ it("waits for an unrelated lookup and discovers only the latest selected model",
ok(catalog("first", { thoughtLevels: { latest: [option("effort", "thought_level", ["medium", "max"])] } })),
),
);
expect(screen.getByRole("button", { name: /^Model settings:/ })).toHaveTextContent("medium");
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("medium");
expect(backend.refresh).toHaveBeenCalledTimes(2);
expect(backend.create).not.toHaveBeenCalled();
});
@@ -661,7 +590,7 @@ it("does not leak a delayed model's levels or failure into a newer selection", a
backend.refresh.mockReturnValueOnce(pending.promise);
for (const model of ["small", "big"]) {
fireEvent.click(screen.getByRole("button", { name: "Model" }));
fireEvent.click(screen.getByTitle(model));
fireEvent.click(screen.getByRole("option", { name: model }));
}
await act(async () =>
pending.resolve(
@@ -678,7 +607,7 @@ it("does not leak a delayed model's levels or failure into a newer selection", a
),
);
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("big");
expect(screen.getByRole("button", { name: /^Model settings:/ })).toHaveTextContent("low");
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("low");
fireEvent.click(screen.getByRole("button", { name: "Model" }));
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
expect(screen.getByRole("button", { name: "Refresh models" })).toBeEnabled();
+11 -48
View File
@@ -1,4 +1,4 @@
import type { AgentChange, AgentCommit, AgentConfigOption, AgentEntry, AgentTask } from "@/bindings";
import type { AgentChange, AgentCommit, AgentEntry, AgentTask } from "@/bindings";
import { executeAction } from "@/platform/actions";
import { tx, useTx } from "@/platform/i18n";
import { useProject } from "@/platform/project";
@@ -160,39 +160,19 @@ export function SessionComposer({
const provider = useAgents((s) => s.providers.find((p) => p.id === task.provider));
const catalog = useAgents((s) => s.modelCatalogs.get(task.provider));
const requestingModels = useAgents((s) => s.modelRequests.has(task.provider));
const requestTarget = useAgents((s) => s.modelRequestTargets.get(task.provider));
const model = task.config.find((o) => o.category === "model");
const catalogModel = (catalog?.config ?? provider?.config)?.find((o) => o.category === "model");
const canRefreshModels =
task.status !== "archived" &&
(!!model || !!task.model || !!catalogModel) &&
!!provider?.installed &&
project?.trusted !== false;
const canRefreshModels = task.status !== "archived" && !!model && !!provider?.installed && project?.trusted !== false;
const candidateModels = canRefreshModels
? (catalog?.config ?? provider?.config)?.find((o) => o.category === "model")?.values
: undefined;
const pickerConfig = useMemo(() => {
if (!canRefreshModels) return task.config;
if (!model) {
const recovered: AgentConfigOption =
catalogModel === undefined
? {
id: "model",
name: "Model",
description: null,
category: "model",
current: task.model,
values: [],
via: "option",
}
: { ...catalogModel, current: task.model ?? catalogModel.current };
return [...task.config, recovered];
}
const candidateModels = catalogModel?.values;
if (!candidateModels?.length) return task.config;
if (!model || !candidateModels?.length) return task.config;
const sessionModels = new Set(model.values.map((v) => v.value));
const extra = candidateModels.filter((v) => !sessionModels.has(v.value));
if (!extra.length) return task.config;
const pickerModel = { ...model, values: [...model.values, ...extra] };
return task.config.map((o) => (o === model ? pickerModel : o));
}, [task.config, task.model, model, catalogModel, canRefreshModels]);
}, [task.config, model, candidateModels]);
const [sending, setSending] = useState(false);
const configChange = useRef<{ loadingModel: boolean } | null>(null);
const [configuring, setConfiguring] = useState<typeof configChange.current>(null);
@@ -226,28 +206,16 @@ export function SessionComposer({
)
.finally(() => setSending(false));
};
const setOption = (id: string, value: string, forModel?: string) => {
const pickerModel = pickerConfig.find((o) => o.category === "model");
const changingModel = id === pickerModel?.id;
const loadingModel = !!forModel || (changingModel && !model?.values.some((v) => v.value === value));
const setOption = (id: string, value: string) => {
const changingModel = id === model?.id;
const loadingModel = changingModel && !model.values.some((v) => v.value === value);
const pendingModel = model?.current != null && model.current !== task.model;
const change = loadingModel || (changingModel && configChange.current) || pendingModel ? { loadingModel } : null;
if (change) {
configChange.current = change;
setConfiguring(change);
}
const apply = async () => {
if (forModel && pickerModel) {
await setTaskConfig(task.id, pickerModel.id, forModel);
// A later model choice supersedes both halves of this edit.
const latest = useAgents.getState().tasks.get(task.id);
const selected = latest?.config.find((o) => o.category === "model")?.current ?? latest?.model;
if (configChange.current !== change) return;
if (selected !== forModel) throw new Error(tx("The model changed before its setting could be applied."));
}
await setTaskConfig(task.id, id, value);
};
void apply()
void setTaskConfig(task.id, id, value)
.catch((e: unknown) =>
notifications().notify({
level: "error",
@@ -326,11 +294,6 @@ export function SessionComposer({
error: requestingModels ? null : (catalog?.error ?? null),
onOpen: () => void refreshTaskModels(task.id, false),
onRefresh: () => void executeAction("agents.refreshModels", task.id),
preview: {
settingsFor: (id) => (catalog ?? provider)?.thoughtLevels?.[id],
load: (id) => void refreshTaskModels(task.id, false, id),
errorFor: (id) => (requestTarget === id ? catalog?.error : null),
},
}
: undefined
}
+11 -20
View File
@@ -279,28 +279,19 @@ export function draftConfig(
const model = config.find((o) => o.category === "model")?.current;
if (model) {
config.push(
...(draftModelSettings((catalog ?? provider)?.thoughtLevels?.[model], draft.thoughtLevels?.[model], defaults) ??
[]),
...((catalog ?? provider)?.thoughtLevels?.[model] ?? []).map((o) => {
const choice = draft.thoughtLevels?.[model]?.[o.id] ?? defaults[o.id];
return {
...o,
defaultValue: o.defaultValue ?? o.current,
current: choice !== undefined && o.values.some((v) => v.value === choice) ? choice : o.current,
};
}),
);
}
return config;
}
export function draftModelSettings(
options: AgentConfigOption[] | undefined,
choices: Record<string, string> | undefined,
defaults: Record<string, string>,
) {
return options?.map((o) => {
const choice = choices?.[o.id] ?? defaults[o.id];
return {
...o,
defaultValue: o.defaultValue ?? o.current,
current: choice !== undefined && o.values.some((v) => v.value === choice) ? choice : o.current,
};
});
}
export function setDraftOption(id: string, value: string) {
const { draft, providers } = useAgents.getState();
const config = draftConfig(
@@ -427,13 +418,13 @@ export async function refreshModels(
}
/** Discover switch candidates without using or updating the session's settings. */
export async function refreshTaskModels(id: string, force = true, model: string | null = null): Promise<void> {
export async function refreshTaskModels(id: string, force = true): Promise<void> {
const { tasks, providers } = useAgents.getState();
const task = tasks.get(id);
if (!task || task.status === "archived" || (!task.model && !task.config.some((o) => o.category === "model"))) return;
if (!task || task.status === "archived" || !task.config.some((o) => o.category === "model")) return;
const provider = providers.find((p) => p.id === task.provider);
if (!provider?.installed || useProject.getState().project?.trusted === false) return;
await refreshProviderModels(provider, force, model, null);
await refreshProviderModels(provider, force, null, null);
}
async function refreshProviderModels(
+1 -17
View File
@@ -130,7 +130,7 @@ describe("Maven tree", () => {
it("shows profiles, then the aggregator with lifecycle, plugins and its modules", () => {
const roots = mavenRoots(maven);
expect(labels(roots)).toEqual(["Profiles", "Multi Demo"]);
expect(labels(children(roots[0]!))).toEqual(["ci", "dev"]);
expect(labels(children(roots[0]!))).toEqual(["dev", "ci"]);
const top = children(roots[1]!);
expect(labels(top)).toEqual(["Lifecycle", "Plugins", "core", "Demo App"]);
expect(labels(children(top[0]!))).toEqual([
@@ -148,22 +148,6 @@ describe("Maven tree", () => {
expect(nodeIcon(roots[1]!)).toBe("maven-project");
});
it("sorts Maven profiles by ID ignoring case while preserving the order used for Maven arguments", () => {
const model = {
...maven,
profiles: [
{ id: "zulu", activeByDefault: false },
{ id: "Beta", activeByDefault: false },
{ id: "alpha_ci", activeByDefault: false },
{ id: "alpha", activeByDefault: true },
{ id: "alpha-edge", activeByDefault: false },
],
};
const group = mavenRoots(model)[0]!;
expect(labels(mavenChildren(group, model, [])!)).toEqual(["alpha", "alpha-edge", "alpha_ci", "Beta", "zulu"]);
expect(profilesArg(model.profiles, { zulu: true, alpha_ci: true, alpha: false })).toBe("zulu,alpha_ci,!alpha");
});
it("expands plugins to goals and dependencies to their transitive ones", () => {
const core = children(mavenRoots(maven)[1]!)[2]!;
const kids = children(core);
-5
View File
@@ -187,11 +187,6 @@ export function mavenChildren(
case "profiles":
return model.profiles
.filter((p) => p.projectRoot === node.projectRoot)
.sort((a, b) => {
const aId = a.id.toLowerCase();
const bId = b.id.toLowerCase();
return aId < bId ? -1 : aId > bId ? 1 : 0;
})
.map((profile) => ({ kind: "profile", key: `mvn:profile:${profileKey(profile)}`, profile }));
case "mavenProject": {
const p = node.project;
+6 -8
View File
@@ -1020,16 +1020,14 @@ export function SourceDialog({
}
onChange={(e) => setOptions({ timeZone: e.target.value })}
/>
<SecondsOption
label="Run keep-alive query each"
value={options.keepAliveSecs}
fallback={60}
onChange={(keepAliveSecs) => setOptions({ keepAliveSecs })}
/>
</>
)}
{!sqlite && (
<SecondsOption
label="Run keep-alive query each"
value={options.keepAliveSecs}
fallback={60}
onChange={(keepAliveSecs) => setOptions({ keepAliveSecs })}
/>
)}
<SecondsOption
label="Auto-disconnect after"
value={options.autoDisconnectSecs}
-14
View File
@@ -1072,18 +1072,6 @@ function promptOf(id: string): string {
* `schema` is a console's active context: the backend puts the connection that runs
* each statement in it, so unqualified names resolve there.
*/
/** Shows `id` disconnected when the backend closed its connection (it reconnects on next use). */
async function syncDropped(id: string) {
const server = await call(commands.dbConnected()).catch(() => null);
if (!server || server.includes(id) || !useDatabase.getState().connected.has(id)) return;
useDatabase.setState((s) => {
const connected = new Set(s.connected);
connected.delete(id);
return { connected };
});
log("info", `${targetLabel(id)}: the connection was lost; the next statement reconnects`);
}
async function run(
id: string,
statements: SqlStatement[],
@@ -1099,8 +1087,6 @@ async function run(
);
if (!current()) return outcomes;
if (!wasConnected) log("info", "Connected");
// A failed statement can have found the session dead; the backend then dropped it.
if (outcomes.some((o) => o.error)) void syncDropped(id);
const prompt = schema || promptOf(id);
for (const o of outcomes) {
log("statement", o.statement.text, `${prompt}>`);
@@ -292,7 +292,7 @@ describe("debug tool window", () => {
expect(screen.getByRole("tab", { name: /main/ })).toBeTruthy();
expect(screen.getByRole("tab", { name: "Threads & Variables" })).toBeTruthy();
expect(screen.getByRole("tab", { name: "Console" })).toBeTruthy();
expect(screen.getByRole("option", { selected: true })).toHaveTextContent("main:12, main.py");
expect(screen.getByText(", main.py:12")).toBeTruthy();
expect(screen.getByPlaceholderText("Evaluate expression (↩) or add a watch (⇧⌘↩)")).toBeTruthy();
expect(await screen.findByText("{int}")).toBeTruthy();
expect(screen.getByText("'hi'")).toBeTruthy();
@@ -396,32 +396,6 @@ describe("variables the adapter computes after the stop", () => {
}
});
it("offers Remove All Watches on a watch's context menu", async () => {
useDebug.setState({ watches: ["count + 1", "label.upper()"] });
const menu = (text: string) => {
fireEvent.contextMenu(screen.getByText(text).closest("[role=treeitem]")!);
const items = useContextMenuStore.getState().menu?.items ?? [];
act(() => hideContextMenu());
return items.flatMap((i) => ("label" in i && i.label ? [i] : []));
};
try {
setup();
await screen.findByText("label.upper()");
await screen.findByText("'hi'");
expect(menu("label").map((i) => i.label)).not.toContain("Remove All Watches");
const items = menu("count + 1");
expect(items.map((i) => i.label)).toContain("Remove Watch");
const removeAll = items.find((i) => i.label === "Remove All Watches");
expect(removeAll).toBeTruthy();
act(() => (removeAll as { run: () => void }).run());
expect(useDebug.getState().watches).toEqual([]);
await waitFor(() => expect(screen.queryByText("label.upper()")).toBeNull());
expect(screen.getByText("'hi'")).toBeTruthy();
} finally {
useDebug.setState({ watches: [] });
}
});
it("reloads after Set Value", async () => {
setup();
await screen.findByText("Collecting data…");
@@ -1,5 +1,5 @@
import { beforeEach, describe, expect, it } from "vitest";
import { addWatch, loadWatches, removeAllWatches, useDebug } from "../state";
import { addWatch, loadWatches, useDebug } from "../state";
const SHARED = "openidea.debugger.watches";
const of = (root: string) => `${SHARED}:${root}`;
@@ -41,23 +41,6 @@ describe("watch storage", () => {
expect(watches()).toEqual([]);
});
it("Remove All Watches empties the project's stored list", () => {
localStorage.setItem(SHARED, '["legacy"]');
loadWatches("/a");
addWatch("x");
addWatch("y");
loadWatches("/b");
addWatch("z");
loadWatches("/a");
removeAllWatches();
expect(watches()).toEqual([]);
expect(localStorage.getItem(of("/a"))).toBe("[]");
loadWatches("/a");
expect(watches()).toEqual([]);
loadWatches("/b");
expect(watches()).toEqual(["legacy", "z"]);
});
it("without a project nothing is stored", () => {
loadWatches(null);
addWatch("z");
-5
View File
@@ -1221,11 +1221,6 @@ export function removeWatch(expression: string) {
persistWatches();
}
export function removeAllWatches() {
useDebug.setState({ watches: [] });
persistWatches();
}
/** Watches used to be one list for every project; it is only read now, as a project's first list. */
const SHARED_WATCH_KEY = "openidea.debugger.watches";
const watchKey = (root: string) => `${SHARED_WATCH_KEY}:${root}`;
@@ -102,20 +102,11 @@
display: flex;
flex-direction: column;
min-height: 0;
padding-bottom: var(--space-1);
}
.threadHeader {
display: flex;
align-items: center;
flex: none;
height: 30px;
padding: 0 var(--space-1);
border-bottom: 1px solid var(--border);
padding: 4px 0;
}
.threadSelect {
max-width: 100%;
margin: 0 8px 4px;
}
.frameList {
@@ -125,7 +116,7 @@
display: flex;
flex-direction: column;
outline: none;
padding: var(--space-1) var(--space-1) 0;
padding: 0 4px;
}
.frame {
@@ -159,36 +150,24 @@
flex: none;
}
.frameText,
.frameLabel {
display: flex;
align-items: baseline;
min-width: 0;
}
.frameText {
flex: 1;
}
.frameLine {
.frameName {
flex: none;
}
.frameName,
.frameFile {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
}
.frameFile {
flex: 0 1000 auto;
min-width: min(12ch, 32%);
flex: 1;
min-width: 0;
/* ", File.java:12" hugs the name, cancelling the row gap. */
margin-left: -6px;
color: var(--fg-subtle);
font-size: var(--fs-small);
overflow: hidden;
text-overflow: ellipsis;
}
.hiddenFrames {
display: block;
overflow: hidden;
text-overflow: ellipsis;
color: var(--fg-subtle);
font-style: italic;
}
+18 -33
View File
@@ -1,6 +1,6 @@
/** Debug tool window: toolbar, Threads & Variables (frames + variables), Console. */
import { writeClipboardText } from "@/platform/clipboard";
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";
import { useEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";
import clsx from "clsx";
import { executeAction } from "@/platform/actions";
import { basename, useProject } from "@/platform/project";
@@ -22,7 +22,6 @@ import {
type TabItem,
T,
} from "@/ui";
import { revealVertically } from "@/ui/Tabs";
import { setMuted, useBreakpoints } from "../breakpoints/store";
import { frameLabel, groupFrames } from "../frames";
import { blurDebugView, focusDebugView } from "./focusedView";
@@ -348,15 +347,10 @@ function ThreadsAndVariables({ session }: { session: DebugSession }) {
function FramesPane({ session }: { session: DebugSession }) {
const root = useProject((s) => s.project?.root ?? null);
const [showAll, setShowAll] = useState(false);
const list = useRef<HTMLDivElement>(null);
const selectedRow = useRef<HTMLButtonElement>(null);
const items = useMemo(
() => groupFrames(session.frames, root, session.selectedFrame, showAll),
[session.frames, root, session.selectedFrame, showAll],
);
useLayoutEffect(() => {
if (list.current && selectedRow.current) revealVertically(list.current, selectedRow.current);
}, [items]);
const paused = session.status === "paused";
const onKeyDown = (e: KeyboardEvent) => {
if (e.key !== "ArrowDown" && e.key !== "ArrowUp") return;
@@ -371,24 +365,19 @@ function FramesPane({ session }: { session: DebugSession }) {
return (
<div className={styles.frames}>
{session.threads.length > 0 && (
<div className={styles.threadHeader}>
<Select
value={session.selectedThread != null ? String(session.selectedThread) : null}
options={session.threads.map((t) => ({
value: String(t.id),
label: t.name,
verbatim: true,
detail: t.id === session.stoppedThread ? "suspended" : undefined,
}))}
onChange={(v) => void selectThread(session.id, +v)}
aria-label="Thread"
variant="ghost"
className={styles.threadSelect}
/>
</div>
<Select
value={session.selectedThread != null ? String(session.selectedThread) : null}
options={session.threads.map((t) => ({
value: String(t.id),
label: t.name,
detail: t.id === session.stoppedThread ? "suspended" : undefined,
}))}
onChange={(v) => void selectThread(session.id, +v)}
aria-label="Thread"
className={styles.threadSelect}
/>
)}
<div
ref={list}
className={styles.frameList}
role="listbox"
aria-label={tx("Frames")}
@@ -426,11 +415,9 @@ function FramesPane({ session }: { session: DebugSession }) {
) : (
<button
key={item.frame.id}
ref={item.frame.id === session.selectedFrame ? selectedRow : undefined}
type="button"
role="option"
aria-selected={item.frame.id === session.selectedFrame}
title={item.frame.path ? `${frameLabel(item.frame)}, ${basename(item.frame.path)}` : item.frame.name}
className={clsx(
styles.frame,
item.frame.id === session.selectedFrame && styles.frameSelected,
@@ -472,15 +459,13 @@ function FramesPane({ session }: { session: DebugSession }) {
}}
>
<Icon name="method" size={16} className={styles.frameIcon} />
<span className={styles.frameText}>
<span className={styles.frameLabel}>
<span className={styles.frameName}>{item.frame.name}</span>
{item.frame.path && item.frame.line >= 0 && (
<span className={styles.frameLine}>:{item.frame.line + 1}</span>
)}
<span className={styles.frameName}>{item.frame.name}</span>
{item.frame.path && (
<span className={styles.frameFile}>
, {basename(item.frame.path)}
{item.frame.line >= 0 ? `:${item.frame.line + 1}` : ""}
</span>
{item.frame.path && <span className={styles.frameFile}>, {basename(item.frame.path)}</span>}
</span>
)}
</button>
),
)}
+2 -14
View File
@@ -9,15 +9,7 @@ import { activeEditor } from "@/editor/api";
import { notifications } from "@/workbench/contributions";
import { addFieldWatchpoint } from "../breakpoints/special";
import { methodAt } from "../breakpoints/symbols";
import {
activeSession,
addWatch,
removeAllWatches,
removeWatch,
revealFrame,
sessionSupports,
setVariableValue,
} from "../state";
import { activeSession, addWatch, removeWatch, revealFrame, sessionSupports, setVariableValue } from "../state";
import { blurDebugView, focusDebugView } from "./focusedView";
import { classifyValue, oneLine, shownValue, sortVariables } from "../values";
import { valueText } from "../valueText";
@@ -308,11 +300,7 @@ export function VariablesView({
{ label: "Set Value…", icon: "edit", shortcut: "F2", run: () => startEdit(node) },
{ kind: "separator" },
);
if (node.kind === "watch")
items.push(
{ label: "Remove Watch", icon: "minus", run: () => removeWatch(node.name) },
{ label: "Remove All Watches", run: removeAllWatches },
);
if (node.kind === "watch") items.push({ label: "Remove Watch", icon: "minus", run: () => removeWatch(node.name) });
if (node.kind !== "scope") {
items.push({ label: "Copy Value", icon: "copy", run: () => void copyValue(node) });
items.push({ label: "Copy Name", run: () => void writeClipboardText(node.name) });
+1 -1
View File
@@ -265,7 +265,7 @@ function HeaderTable({ headers }: { headers: Array<[string, string]> }) {
export function HttpClientView() {
const history = useHttpClient((s) => s.history);
const selected = useHttpClient((s) => s.selected);
const exchange = useHttpClient((s) => s.exchanges.find((e) => e.entry.id === s.selected));
const exchange = useHttpClient((s) => (s.selected ? s.exchanges[s.selected] : undefined));
const running = useHttpClient((s) => s.running);
useEffect(() => {
void refreshHistory();
@@ -39,11 +39,11 @@ const exchange: HttpExchange = {
};
describe("HTTP response find", () => {
afterEach(() => useHttpClient.setState({ history: [], exchanges: [], selected: null }));
afterEach(() => useHttpClient.setState({ history: [], exchanges: {}, selected: null }));
it("opens a find bar with ⌘F in the response and marks the matches", () => {
Element.prototype.scrollIntoView ??= () => {};
useHttpClient.setState({ history: [exchange.entry], exchanges: [exchange], selected: "e1" });
useHttpClient.setState({ history: [exchange.entry], exchanges: { e1: exchange }, selected: "e1" });
render(<HttpClientView />);
const body = screen.getByLabelText("Response body");
fireEvent.keyDown(body, { key: "f", metaKey: true, ctrlKey: true });
+2 -8
View File
@@ -237,12 +237,6 @@ function annotation(p: Param, name: string): Annotation | undefined {
const isMap = (type: string) =>
/^(java\.util\.)?(Map|MultiValueMap|HttpHeaders|LinkedMultiValueMap|HashMap)\b/.test(type);
/** `name=value` of a `params`/`headers` condition. Only the first "=" divides it: `Accept=text/plain;charset=UTF-8`. */
function condition(cond: string): [name: string, value: string | undefined] {
const at = cond.indexOf("=");
return at < 0 ? [cond, undefined] : [cond.slice(0, at), cond.slice(at + 1)];
}
function endpoint(cls: ClassDecl, method: ClassDecl["methods"][number], c: Constants): Endpoint | null {
const m = mapping(method.annotations);
if (!m) return null;
@@ -273,12 +267,12 @@ function endpoint(cls: ClassDecl, method: ClassDecl["methods"][number], c: Const
}
// `params = "a=1"` / `headers = "X-Api=1"` narrow the mapping: the request must carry them.
for (const cond of [...c.strings(classMapping?.args.get("params")), ...c.strings(m.ann.args.get("params"))]) {
const [name, value] = condition(cond);
const [name, value] = cond.split("=", 2);
if (name && !cond.includes("!") && !query.some((q) => q.name === name.trim()))
query.push({ name: name.trim(), value: value?.trim() ?? null });
}
for (const cond of [...c.strings(classMapping?.args.get("headers")), ...c.strings(m.ann.args.get("headers"))]) {
const [name, value] = condition(cond);
const [name, value] = cond.split("=", 2);
if (name && !cond.includes("!") && value !== undefined) headers.push({ name: name.trim(), value: value.trim() });
}
const first = (key: string) =>
@@ -198,32 +198,6 @@ describe("Spring mappings (Kotlin)", () => {
});
});
describe("mapping conditions", () => {
it("keeps a value that has its own '='", () => {
const [controller] = springControllers(`package demo;
import org.springframework.web.bind.annotation.*;
@RestController
public class ReportController {
@GetMapping(path = "/report", headers = "Accept=text/plain;charset=UTF-8", params = "range=a=b")
public String report() { return ""; }
@PostMapping(path = "/upload", headers = {"Content-Type=multipart/form-data; boundary=xyz", "X-Token=YWJj=="})
public void upload() {}
}
`);
const [report, upload] = controller!.endpoints;
expect(report).toMatchObject({
query: [{ name: "range", value: "a=b" }],
headers: [{ name: "Accept", value: "text/plain;charset=UTF-8" }],
});
expect(upload!.headers).toEqual([
{ name: "Content-Type", value: "multipart/form-data; boundary=xyz" },
{ name: "X-Token", value: "YWJj==" },
]);
});
});
describe("non-controllers", () => {
it("ignores classes that are not controllers and files without any", () => {
expect(springControllers('@Service class A { @GetMapping("/x") void a() {} }')).toEqual([]);
+1 -39
View File
@@ -1,11 +1,10 @@
import { beforeEach, expect, it, vi } from "vitest";
import type { HttpExchange, HttpRequestBlock } from "@/platform/ipc";
import { runAll, runRequest, selectEntry, setEnvironment, useHttpClient } from "./store";
import { runAll, runRequest, setEnvironment, useHttpClient } from "./store";
const backend = vi.hoisted(() => ({
httpEnvironments: vi.fn(),
httpExecute: vi.fn(),
httpHistoryGet: vi.fn(),
httpRequests: vi.fn(),
}));
vi.mock("@/platform/ipc", async (importOriginal) => {
@@ -96,40 +95,3 @@ it.each(["A", "missing"])("validates the starting choice %s once when environmen
expect(backend.httpExecute).toHaveBeenNthCalledWith(1, expect.any(Number), path, text, 0, environment);
expect(backend.httpExecute).toHaveBeenNthCalledWith(2, expect.any(Number), path, text, 1, environment);
});
function response(id: string): HttpExchange {
return { ...exchange, entry: { ...exchange.entry, id } };
}
it("keeps 100 history rows and the four most recently used exchanges", async () => {
for (let n = 0; n < 101; n++) {
backend.httpExecute.mockResolvedValueOnce(ok(response(String(n))));
await runRequest(null, text, 0);
}
const state = useHttpClient.getState();
expect(state.history).toHaveLength(100);
expect(state.history.at(-1)?.id).toBe("1");
expect(state.exchanges).toHaveLength(4);
await selectEntry("97"); // Touch the oldest resident before opening a cold row.
backend.httpHistoryGet.mockResolvedValueOnce(ok(response("1")));
await selectEntry("1");
await selectEntry("97");
expect(backend.httpHistoryGet.mock.calls).toEqual([["1"]]);
expect(useHttpClient.getState().exchanges.map((e) => e.entry.id)).toEqual(["97", "1", "100", "99"]);
});
it("keeps the latest selection when two cold reads finish out of order", async () => {
let finishFirst!: (result: ReturnType<typeof ok<HttpExchange>>) => void;
const first = new Promise<ReturnType<typeof ok<HttpExchange>>>((resolve) => {
finishFirst = resolve;
});
backend.httpHistoryGet.mockReturnValueOnce(first).mockResolvedValueOnce(ok(response("b")));
const pending = selectEntry("a");
await selectEntry("b");
finishFirst(ok(response("a")));
await pending;
const { selected, exchanges } = useHttpClient.getState();
expect(selected).toBe("b");
expect(exchanges).toEqual([response("b")]);
});
+9 -22
View File
@@ -14,9 +14,6 @@ import { writeClipboardText } from "@/platform/clipboard";
import { editorService, notifications, showServiceView, showStatusInfo } from "@/workbench/contributions";
export const SERVICE_VIEW = "httpClient";
// Same bound as ide_http::history::MAX_ENTRIES. Only recent rows keep their bodies in the UI.
const HISTORY_LIMIT = 100;
const EXCHANGE_LIMIT = 4;
const ENV_KEY = "openidea.httpClient.environments";
function readEnvChoices(): Record<string, string> {
@@ -44,8 +41,8 @@ interface HttpClientState {
environments: Record<string, string[]>;
/** History entries, newest first (this session's runs included). */
history: HttpHistoryEntry[];
/** Loaded exchanges, most recently viewed first. */
exchanges: HttpExchange[];
/** Loaded exchanges by entry id. */
exchanges: Record<string, HttpExchange>;
selected: string | null;
running: Running | null;
}
@@ -54,7 +51,7 @@ export const useHttpClient = create<HttpClientState>(() => ({
envByFile: readEnvChoices(),
environments: {},
history: [],
exchanges: [],
exchanges: {},
selected: null,
running: null,
}));
@@ -99,10 +96,6 @@ function effectiveEnvironment(path: string | null, selection?: string | null): s
return null;
}
function rememberExchange(exchange: HttpExchange, recent: HttpExchange[]) {
return [exchange, ...recent.filter((e) => e.entry.id !== exchange.entry.id)].slice(0, EXCHANGE_LIMIT);
}
export async function refreshHistory() {
try {
const history = await call(commands.httpHistory());
@@ -113,18 +106,12 @@ export async function refreshHistory() {
}
export async function selectEntry(id: string) {
const { exchanges } = useHttpClient.getState();
const cached = exchanges.find((e) => e.entry.id === id);
if (cached) {
useHttpClient.setState({ selected: id, exchanges: rememberExchange(cached, exchanges) });
return;
}
useHttpClient.setState({ selected: id });
if (useHttpClient.getState().exchanges[id]) return;
try {
const ex = await call(commands.httpHistoryGet(id));
useHttpClient.setState((s) => (s.selected === id ? { exchanges: rememberExchange(ex, s.exchanges) } : s));
useHttpClient.setState((s) => ({ exchanges: { ...s.exchanges, [id]: ex } }));
} catch (e) {
if (useHttpClient.getState().selected !== id) return;
notifications().notify({
level: "error",
title: "Cannot open the response",
@@ -135,7 +122,7 @@ export async function selectEntry(id: string) {
export async function clearHistory() {
await call(commands.httpHistoryClear());
useHttpClient.setState({ history: [], exchanges: [], selected: null });
useHttpClient.setState({ history: [], exchanges: {}, selected: null });
}
export function parseRequests(text: string): Promise<HttpRequestBlock[]> {
@@ -172,8 +159,8 @@ export async function runRequest(
const env = batchEnvironment === undefined ? effectiveEnvironment(path) : batchEnvironment;
const ex = await call(commands.httpExecute(request, path, text, index, env));
useHttpClient.setState((s) => ({
history: [ex.entry, ...s.history.filter((h) => h.id !== ex.entry.id)].slice(0, HISTORY_LIMIT),
exchanges: rememberExchange(ex, s.exchanges),
history: [ex.entry, ...s.history.filter((h) => h.id !== ex.entry.id)],
exchanges: { ...s.exchanges, [ex.entry.id]: ex },
selected: ex.entry.id,
}));
return true;
@@ -248,5 +235,5 @@ export function cancelRunning() {
/** The window switched projects: history, responses and environments belong to the previous one. */
export function resetHttpClient() {
cancelRunning();
useHttpClient.setState({ environments: {}, history: [], exchanges: [], selected: null, running: null });
useHttpClient.setState({ environments: {}, history: [], exchanges: {}, selected: null, running: null });
}
+1 -4
View File
@@ -2,7 +2,6 @@ import { StateEffect, StateField, type Text } from "@codemirror/state";
import { Decoration, EditorView, WidgetType, type DecorationSet as CmDecorations } from "@codemirror/view";
import type { DecorationSet, Range } from "@/bindings";
import { registerEditorContribution, useEditorRegistry, type EditorDocContext } from "@/editor/api";
import { foldChipWidth } from "@/editor/core/cm/folding";
import { commands, isTauri } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { addPathIconProvider, bumpFileIconRevision } from "@/ui";
@@ -148,10 +147,8 @@ class AfterText extends WidgetType {
if (!line || !inner) return;
const own = offsetOf(el, "--openidea-message-offset");
const hint = line.querySelector<HTMLElement>(".cm-openidea-lensInlineInner");
// A folded chip drawn after this anchor paints under the box; step past it first (folding.ts).
let width = foldChipWidth(el);
// The hint's inner box sits `--openidea-hint-offset` past its zero-width anchor.
if (hint) width += Math.round(hint.getBoundingClientRect().width) + offsetOf(hint, "--openidea-hint-offset");
let width = hint ? Math.round(hint.getBoundingClientRect().width) + offsetOf(hint, "--openidea-hint-offset") : 0;
// Every message before this one adds its own width and offset.
for (const other of line.querySelectorAll<HTMLElement>(".cm-plugin-after")) {
if (other === el || other.compareDocumentPosition(el) & Node.DOCUMENT_POSITION_FOLLOWING) continue;
-3
View File
@@ -417,9 +417,6 @@ export function contextMenuItems(nodes: ProjectNode[]): MenuItem[] {
{ kind: "separator" },
act("vcs.stash", undefined, "Stash Changes…"),
act("vcs.unstash", undefined, "Unstash Changes…"),
{ kind: "separator" },
act("vcs.manageRemotes", undefined, "Manage Remotes…"),
act("vcs.clone", undefined, "Clone…"),
],
"branch",
),
-25
View File
@@ -29,7 +29,6 @@ import { useConsoleSelection } from "./useConsoleSelection";
import { hostBinding, formatBinding, hasPrimaryModifier, registerKeyClaim } from "@/platform/keymap";
import { WidestColumns } from "@/platform/consoleColumns";
import { tx } from "@/platform/i18n";
import { executeAction } from "@/platform/actions";
import { ConsoleFindBar } from "@/ui/ConsoleFindBar";
import { DEFAULT_FIND_OPTIONS, findInLines, type FindOptions } from "@/ui/consoleFind";
@@ -116,15 +115,6 @@ export interface Fold {
*/
export type DisplayRow = { kind: "line"; index: number; fold?: Fold } | { kind: "fold"; fold: Fold };
/**
* IDEA's Fold Lines Like This: the selection when it stays on one line, else the clicked line;
* trimmed, and `null` when that leaves nothing to fold on.
*/
export function foldLineText(selection: string, line: string | null): string | null {
const text = (selection || (line ?? "")).trim();
return text && !/[\r\n]/.test(text) ? text : null;
}
/**
* Folds runs of consecutive output lines (one or more) that contain one of
* `patterns`; runs whose first line id is in `expanded` stay open.
@@ -431,18 +421,9 @@ export function ConsoleView({
/** The selected text; after Select All the whole buffer, including rows that are not mounted. */
const selectedOutput = () => (allSelected() ? model.text() : (window.getSelection()?.toString() ?? ""));
/** The output line a context menu opened on; folds and the input row have none. */
const lineAt = (target: EventTarget) => {
const index = (target as Element).closest?.("[data-index]")?.getAttribute("data-index");
const row = index == null ? undefined : rows[Number(index)];
const line = row?.kind === "line" ? lines[row.index] : undefined;
return line && line.kind !== "system" ? line.text : null;
};
const onContextMenu = (e: MouseEvent) => {
e.preventDefault();
const selection = selectedOutput();
const foldText = foldLineText(selection, lineAt(e.target));
showContextMenu(e, [
{
label: "Copy",
@@ -460,12 +441,6 @@ export function ConsoleView({
run: openFind,
},
{ kind: "separator" },
{
label: "Fold Lines Like This",
disabled: !foldText,
// Opens Settings › Console with the text added to the fold patterns, for OK / Cancel there.
run: () => void executeAction("file.settings", `build.console#${foldText}`),
},
{ label: "Clear All", icon: "trash", disabled: !onClear, run: () => onClear?.() },
...(input
? [{ kind: "separator" } as const, { label: "Send EOF", shortcut: "⌃D", run: () => input.onEof() }]
+1 -25
View File
@@ -47,10 +47,7 @@ vi.mock("@/platform/javaLaunch", async (original) => ({
...(await original<typeof import("@/platform/javaLaunch")>()),
resolveJavaModule: async () => "app",
}));
vi.mock("./buildUpdate", async (original) => ({
...(await original<typeof import("./buildUpdate")>()),
runUpdateBuild: mocks.runBuild,
}));
vi.mock("./buildUpdate", () => ({ runUpdateBuild: mocks.runBuild }));
vi.mock("./tomcat", () => ({ buildTomcatArtifact: mocks.build, syncTomcatOutputs: mocks.sync }));
vi.mock("./store", () => ({
rerunConfig: (s: Pick<RunSession, "config">) => mocks.state.configs.find((c) => c.id === s.config.id) ?? s.config,
@@ -160,27 +157,6 @@ describe("Spring Boot application updates", () => {
expect.objectContaining({ body: expect.stringContaining("Restart the application") }),
);
});
it("names the compile errors when the update's Java build fails", async () => {
mocks.resolve.mockResolvedValueOnce({
status: "ok",
data: {
build: "withErrors",
classPaths: [],
pathListSeparator: ":",
errors: [{ path: "/p/app/src/A.java", line: 1, column: 1, message: "illegal character: '\\ufeff'" }],
errorCount: 1,
hints: [],
},
} as never);
await updateTomcat(boot, "classes");
expect(mocks.runBuild).not.toHaveBeenCalled();
expect(mocks.notify).toHaveBeenCalledWith(
expect.objectContaining({
level: "error",
body: "Application update build failed\n/p/app/src/A.java:1:1: error: illegal character: '\\ufeff'",
}),
);
});
it("never publishes resources after a failed build", async () => {
mocks.runBuild.mockRejectedValueOnce(new Error("failed"));
await updateTomcat(boot, "resources");
+3 -8
View File
@@ -12,7 +12,7 @@ import {
} from "@/workbench/contributions";
import { showContextMenu } from "@/ui";
import { buildTomcatArtifact, syncTomcatOutputs } from "./tomcat";
import { runUpdateBuild, updateBuildError } from "./buildUpdate";
import { runUpdateBuild } from "./buildUpdate";
import { rerunConfig, startRun, stopSession, useRun, waitForExit, type RunSession } from "./store";
import { isUpdatable, updateAllowed, type UpdateMode } from "./updatePolicies";
@@ -51,7 +51,7 @@ async function updateSpringBoot(config: RunConfig, mode: UpdateMode, debugging:
),
);
if (info.build === "failed" || info.build === "withErrors" || info.build === "cancelled")
throw updateBuildError(info);
throw new Error(tx("Application update build failed"));
await runUpdateBuild(await call(commands.runApplicationBuild(config, module)));
const classPaths = parsed.explicitClasspath?.split(info.pathListSeparator) ?? info.classPaths;
await call(commands.runApplicationPublish(config, classPaths, parsed.mainClass));
@@ -106,12 +106,7 @@ export async function updateApplication(session: UpdateSession, mode: string): P
}
if (!session.debug) useRun.setState({ activeSession: session.id });
} catch (e) {
notifications().notify({
group: "run",
level: "error",
title: "Application update failed",
body: e instanceof Error ? e.message : String(e),
});
notifications().notify({ group: "run", level: "error", title: "Application update failed", body: String(e) });
} finally {
updatingConfigs.delete(session.config.id);
useApplicationUpdates.setState((s) => ({ ids: new Set([...s.ids].filter((id) => id !== session.id)) }));
-31
View File
@@ -1,31 +0,0 @@
import { describe, expect, it, vi } from "vitest";
vi.mock("./store", () => ({ startRun: vi.fn() }));
import { compileErrorCollector } from "./buildUpdate";
describe("compileErrorCollector", () => {
it("keeps the compiler errors of Maven, javac and Kotlin output without colour codes", () => {
const errors = compileErrorCollector();
errors.add("[INFO] Compiling 3 source files with javac [debug release 17] to target/classes");
errors.add("\u001b[1;31m[ERROR] /p/src/main/java/a/XxxServiceImpl.java:[1,1] 非法字符: '\\ufeff'\u001b[m");
errors.add("[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.13.0:compile");
// Maven's failure summary repeats the error.
errors.add("[ERROR] /p/src/main/java/a/XxxServiceImpl.java:[1,1] 非法字符: '\\ufeff'");
errors.add("/p/src/main/java/a/B.java:12: error: ';' expected\n int x = 1\n");
errors.add("e: file:///p/src/main/kotlin/a/C.kt:3:5 Unresolved reference: foo");
expect(errors.lines()).toEqual([
"[ERROR] /p/src/main/java/a/XxxServiceImpl.java:[1,1] 非法字符: '\\ufeff'",
"/p/src/main/java/a/B.java:12: error: ';' expected",
"e: file:///p/src/main/kotlin/a/C.kt:3:5 Unresolved reference: foo",
]);
});
it("keeps the first ten and counts the rest", () => {
const errors = compileErrorCollector();
for (let i = 1; i <= 13; i++) errors.add(`[ERROR] /p/A.java:[${i},1] cannot find symbol`);
const lines = errors.lines();
expect(lines).toHaveLength(11);
expect(lines[9]).toBe("[ERROR] /p/A.java:[10,1] cannot find symbol");
expect(lines[10]).toBe("… and 3 more");
});
});
+3 -47
View File
@@ -1,59 +1,15 @@
import { tx } from "@/platform/i18n";
import type { JavaLaunchInfo, RunConfig } from "@/platform/ipc";
import { formatCompileErrors } from "@/platform/javaLaunch";
import { stripAnsi } from "@/ui/ansi";
import type { RunConfig } from "@/platform/ipc";
import { startRun } from "./store";
const MAX_ERRORS = 10;
/**
* A compiler error line of a Maven or Gradle build: Maven's `[ERROR] /p/A.java:[1,1] …`,
* javac's `/p/A.java:1: error: …` and Kotlin's `e: file:///p/A.kt:1:1 …`.
*/
const COMPILE_ERROR = [
/^\[ERROR\] .+\.(?:java|kt|groovy|scala):\[\d+,\d+\]/,
/^.+\.(?:java|groovy|scala):\d+: error: /,
/^e: .+\.kts?:\d+:\d+ /,
];
/** Collects the distinct compiler errors of a build's output, without colour codes; `lines()` keeps the first `MAX_ERRORS`. */
export function compileErrorCollector() {
const errors: string[] = [];
// Maven repeats each compiler error in its failure summary.
const seen = new Set<string>();
return {
add(text: string) {
for (const raw of text.split("\n")) {
const line = stripAnsi(raw).trimEnd();
if (seen.has(line) || !COMPILE_ERROR.some((re) => re.test(line))) continue;
seen.add(line);
if (seen.size <= MAX_ERRORS) errors.push(line);
}
},
lines: () => (seen.size > MAX_ERRORS ? [...errors, `… and ${seen.size - MAX_ERRORS} more`] : errors),
};
}
function failure(details: readonly string[]): Error {
const title = tx("Application update build failed");
return new Error(details.length ? `${title}\n${details.join("\n")}` : title);
}
export async function runUpdateBuild(build: RunConfig): Promise<void> {
let finish!: (ok: boolean) => void;
const exited = new Promise<boolean>((resolve) => {
finish = resolve;
});
const errors = compileErrorCollector();
const session = await startRun(build, undefined, undefined, {
onLine: errors.add,
onExit: (code, stopped) => finish(code === 0 && !stopped),
});
if (!session || session.status === "failed" || !(await exited)) throw failure(errors.lines());
}
/** The error for an update whose Java build failed, with the compiler's errors so the user sees what to fix. */
export function updateBuildError(info: JavaLaunchInfo): Error {
const errors = formatCompileErrors(info).trimEnd();
return failure(errors ? errors.split("\n") : []);
if (!session || session.status === "failed" || !(await exited))
throw new Error(tx("Application update build failed"));
}
-129
View File
@@ -1,129 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, fireEvent, render, within } from "@testing-library/react";
import { useProject } from "@/platform/project";
import { hideContextMenu, useContextMenuStore } from "@/ui";
import { ConsoleModel } from "./console";
import { ConsoleView, foldLineText } from "./ConsoleView";
const actions = vi.hoisted(() => ({ executeAction: vi.fn(async () => {}) }));
vi.mock("@/platform/actions", async (orig) => ({ ...(await orig<object>()), executeAction: actions.executeAction }));
vi.mock("@tanstack/react-virtual", () => ({
useVirtualizer: ({ count }: { count: number }) => ({
getTotalSize: () => count * 20,
getVirtualItems: () => Array.from({ length: count }, (_, index) => ({ index, start: index * 20, key: index })),
scrollToIndex: () => {},
measureElement: () => {},
measure: () => {},
}),
}));
beforeEach(() => {
actions.executeAction.mockClear();
useProject.setState({ settings: null });
window.getSelection()?.removeAllRanges();
});
afterEach(() => act(hideContextMenu));
function setup(chunks: { kind: "stdout" | "stderr" | "system"; text: string }[]) {
const model = new ConsoleModel();
for (const c of chunks) model.append(c);
model.flush();
const { container } = render(
<ConsoleView model={model} version={1} softWrap={false} follow={false} onFollowChange={() => {}} cwd="/" />,
);
return within(container).getByRole("log");
}
function foldItem(target: Element) {
fireEvent.contextMenu(target);
const items = useContextMenuStore.getState().menu?.items ?? [];
return items.find((i) => "label" in i && i.label === "Fold Lines Like This") as
| { disabled?: boolean; run?: () => void }
| undefined;
}
function select(node: Node, start: number, end: number) {
const range = document.createRange();
range.setStart(node, start);
range.setEnd(node, end);
window.getSelection()!.removeAllRanges();
window.getSelection()!.addRange(range);
}
describe("foldLineText", () => {
it("takes a one-line selection, else the clicked line, trimmed", () => {
expect(foldLineText(" at org.junit.Assert ", "ignored")).toBe("at org.junit.Assert");
expect(foldLineText("", "\tat java.base/Thread.run(Thread.java:1583) ")).toBe(
"at java.base/Thread.run(Thread.java:1583)",
);
// A whole row picked by a triple click ends in its line break.
expect(foldLineText("DEBUG pool\n", null)).toBe("DEBUG pool");
});
it("has nothing for a selection across lines, a blank selection or a blank line", () => {
expect(foldLineText("first\nsecond", "first")).toBeNull();
expect(foldLineText("first\r\nsecond", "first")).toBeNull();
expect(foldLineText(" ", "a line")).toBeNull();
expect(foldLineText("", " ")).toBeNull();
expect(foldLineText("", null)).toBeNull();
});
});
describe("Fold Lines Like This", () => {
it("opens Settings › Console with the clicked line to add as a fold pattern", () => {
const log = setup([
{
kind: "stdout",
text: "start\n at org.springframework.test.context.TestContextManager.prepare(TestContextManager.java:248)\n",
},
]);
const row = log.querySelectorAll("[data-index]")[1]!;
const item = foldItem(row.firstElementChild ?? row)!;
expect(item.disabled).toBeFalsy();
item.run!();
expect(actions.executeAction).toHaveBeenCalledWith(
"file.settings",
"build.console#at org.springframework.test.context.TestContextManager.prepare(TestContextManager.java:248)",
);
});
it("uses the selected part of a line rather than the whole line", () => {
const log = setup([{ kind: "stdout", text: "12:00 DEBUG pool: idle\n" }]);
const row = log.querySelector("[data-index]")!;
const text = document.createTreeWalker(row, NodeFilter.SHOW_TEXT).nextNode()!;
select(text, 6, 11);
foldItem(row)!.run!();
expect(actions.executeAction).toHaveBeenCalledWith("file.settings", "build.console#DEBUG");
});
it("is disabled for a selection over several lines", () => {
const log = setup([{ kind: "stdout", text: "one\ntwo\n" }]);
const rows = log.querySelectorAll("[data-index]");
const range = document.createRange();
range.setStart(rows[0]!, 0);
range.setEnd(rows[1]!, rows[1]!.childNodes.length);
window.getSelection()!.removeAllRanges();
window.getSelection()!.addRange(range);
expect(foldItem(rows[0]!)!.disabled).toBe(true);
});
it("is disabled on a blank line, the IDE's own messages and a folded run", () => {
useProject.setState({ settings: { console: { foldPatterns: ["at org."] } } as never });
const log = setup([
{ kind: "stdout", text: "\n" },
{ kind: "system", text: "Process finished with exit code 0\n" },
]);
const rows = log.querySelectorAll("[data-index]");
expect(foldItem(rows[0]!)!.disabled).toBe(true);
expect(foldItem(rows[1]!)!.disabled).toBe(true);
act(hideContextMenu);
const folded = setup([{ kind: "stdout", text: "at org.a\nat org.b\n" }]);
const fold = folded.querySelector("[data-index]")!;
expect(fold.textContent).toContain("internal lines");
expect(foldItem(fold)!.disabled).toBe(true);
expect(actions.executeAction).not.toHaveBeenCalled();
});
});
+3 -2
View File
@@ -1,7 +1,8 @@
import { tx } from "@/platform/i18n";
import { call, commands, nextRequestId, type RunConfig } from "@/platform/ipc";
import type { RunConfigTypeContribution } from "@/workbench/contributions";
import { updatePolicyDefaults, updatePolicyFields } from "./updatePolicies";
import { runUpdateBuild, updateBuildError } from "./buildUpdate";
import { runUpdateBuild } from "./buildUpdate";
const validatePort = (value: string) =>
/^\d+$/.test(value) && Number(value) > 0 && Number(value) <= 65535 ? null : "Port must be between 1 and 65535";
@@ -166,7 +167,7 @@ export async function syncTomcatOutputs(config: RunConfig, resourcesOnly: boolea
);
if (!info) return false;
if (info.build === "failed" || info.build === "withErrors" || info.build === "cancelled")
throw updateBuildError(info);
throw new Error(tx("Application update build failed"));
return call(commands.runTomcatSync(config, artifact.module, info.classPaths, resourcesOnly));
}
@@ -1,31 +1,16 @@
.root {
height: 100%;
display: flex;
flex-direction: column;
min-height: 0;
min-width: 0;
}
.tabs {
min-width: 0;
border: 0;
background: none;
}
.toolbar {
flex: none;
width: 32px;
display: flex;
flex-direction: column;
align-items: center;
gap: var(--space-0-5);
padding: var(--space-1) 0;
border-right: 1px solid var(--border);
overflow-y: auto;
}
.toolbar > button {
flex: none;
}
.body {
flex: 1;
min-width: 0;
min-height: 0;
display: flex;
flex-direction: column;
@@ -35,24 +20,23 @@
display: flex;
align-items: center;
gap: var(--space-2);
min-height: 26px;
padding: var(--space-0-5) var(--space-2);
height: 26px;
padding: 0 10px;
color: var(--fg-subtle);
font-size: var(--fs-ui);
font-size: var(--fs-small);
}
.title {
color: var(--fg-secondary);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.count {
min-width: 0;
overflow-wrap: anywhere;
}
.replaceActions {
flex: none;
display: flex;
align-items: center;
justify-content: flex-end;
flex-wrap: wrap;
gap: var(--space-1) var(--space-2);
padding: var(--space-1) var(--space-2);
border-top: 1px solid var(--border);
color: var(--fg-faint);
}
.spacer {
flex: 1;
}
.tree {
flex: 1;
@@ -63,7 +47,6 @@
}
.node {
display: flex;
flex: 1;
align-items: center;
gap: var(--space-1-5);
min-width: 0;
@@ -73,8 +56,6 @@
color: var(--fg-muted);
}
.label {
flex: none;
max-width: 56%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
@@ -84,20 +65,12 @@
color: var(--fg-faint);
font-size: var(--fs-small);
}
.directory {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: var(--fg-subtle);
font-size: var(--fs-small);
}
.lineNo {
flex: none;
min-width: 3ch;
color: var(--fg-line-number);
min-width: 28px;
color: var(--fg-gutter);
font-family: var(--font-mono);
font-size: var(--fs-ui);
font-size: var(--fs-small);
text-align: right;
}
.code {
@@ -106,7 +79,6 @@
text-overflow: ellipsis;
white-space: pre;
font-family: var(--font-mono);
font-size: var(--fs-code);
}
.nodeWrap {
display: contents;
+134 -148
View File
@@ -1,5 +1,5 @@
import { menuGroupItems } from "@/workbench/contributions";
import { useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";
import { useMemo, useRef, useState, type KeyboardEvent } from "react";
import clsx from "clsx";
import { create } from "zustand";
import { executeAction } from "@/platform/actions";
@@ -218,26 +218,16 @@ export function FindToolWindow() {
</EmptyState>
);
}
return <FindTabView key={tab.id} tab={tab} />;
return (
<div className={styles.root}>
<FindTabView key={tab.id} tab={tab} />
</div>
);
}
function FindTabView({ tab }: { tab: FindTab }) {
const groupByDirectory = useFindViewOptions((o) => o.groupByDirectory);
const showPreview = useFindViewOptions((o) => o.preview);
const body = useRef<HTMLDivElement>(null);
const [stacked, setStacked] = useState(false);
useLayoutEffect(() => {
const frame = body.current;
if (!showPreview || !frame) return;
const measure = () => setStacked(frame.clientWidth < 580);
measure();
if (typeof ResizeObserver === "undefined") return;
const observer = new ResizeObserver(measure);
observer.observe(frame);
return () => observer.disconnect();
}, [showPreview]);
const previewLayout = stacked ? "openidea.find.previewSplit.vertical" : "openidea.find.previewSplit";
const minPanelSize = stacked ? "30%" : 160;
const roots = useMemo(() => buildFindTree(tab.state.files, groupByDirectory), [tab.state.files, groupByDirectory]);
const tree = useRef<TreeHandle>(null);
const [leadNode, setLeadNode] = useState<Node | null>(null);
@@ -391,118 +381,26 @@ function FindTabView({ tab }: { tab: FindTab }) {
const selectedPending = pendingUsages(selectedGroups(), marks);
return (
<div className={styles.root} onKeyDown={onKeyDown}>
<FindActions tab={tab} roots={roots} canExclude={selection.size > 0} onExclude={exclude} />
<div ref={body} className={styles.body}>
<div className={styles.summary}>
{(st.status === "searching" || busy) && <Spinner size={16} variant="spokes" />}
<span className={styles.count}>
{st.status === "invalid" || st.status === "error"
? (st.error ?? tx("Search failed"))
: progress
? tx`Replacing… ${progress.done}/${progress.total} files`
: t(st.summary?.limitHit ? "search.find.matchesIncomplete" : "search.find.matches", {
matches: st.matchCount,
files: st.files.length,
}) + (marks.excluded.size ? ` · ${tx`${marks.excluded.size} excluded`}` : "")}
</span>
</div>
<SplitGroup
orientation={showPreview && stacked ? "vertical" : "horizontal"}
className={styles.split}
id="find-results-split"
storageKey={showPreview ? previewLayout : undefined}
>
<SplitPanel id="results" minSize={showPreview ? minPanelSize : undefined} className={styles.splitPanel}>
<Tree<Node>
className={styles.tree}
aria-label="Find results"
handleRef={tree}
roots={roots}
getKey={(n) => n.key}
getLabel={(n) => (n.kind === "dir" ? n.label : n.kind === "file" ? n.name : n.text)}
getChildren={(n) => (n.kind === "match" ? undefined : n.children)}
isExpandable={(n) => n.kind !== "match"}
isOccurrence={(n) => n.kind === "match" && groupState(nodeGroups(n)[0]!, marks) !== "excluded"}
expanded={expanded}
onExpandedChange={(next) => {
const all = allExpandableKeys(roots);
setCollapsed(tab.id, new Set([...all].filter((k) => !next.has(k))));
}}
selected={selection}
onSelectionChange={(next, lead) => {
setSelection(next);
setLeadNode(lead);
if (tab.editorResults && lead?.kind === "match")
void openLocation(
lead.path,
{ line: lead.line, col: lead.col, endLine: lead.line, endCol: lead.endCol },
{ focus: false },
);
}}
multiSelect
onActivate={(n) => {
if (n.kind === "match")
void openLocation(
n.path,
{ line: n.line, col: n.col, endLine: n.line, endCol: n.endCol },
{ focus: true },
);
else if (n.kind === "file")
void openLocation(n.path, previewOf(n) ? { line: previewOf(n)!.line } : null);
}}
onContextMenu={(_n, sel, e) => {
const groups = [...sel].flatMap((k) => (byKey.get(k) ? nodeGroups(byKey.get(k)!) : []));
const excludedAll = groups.length > 0 && groups.every((g) => groupState(g, marks) === "excluded");
showContextMenu(e, [
...(_n?.kind === "match"
? menuGroupItems("searchResults", { paths: [_n.path], line: _n.line, column: _n.col })
: []),
{
id: "exclude",
label: excludedAll ? "Include" : "Exclude",
shortcut: "⌫",
disabled: !groups.length,
run: exclude,
},
...(replaceMode
? [
{
id: "replace",
label: "Replace Selected",
disabled: busy || !pendingUsages(groups, marks).length,
run: () => void replace(pendingUsages(groups, marks)),
},
{
id: "preview",
label: "Preview Replacement",
disabled: busy || !groups.length,
run: () => void previewReplace(),
},
]
: []),
]);
}}
activateExpandable={false}
renderNode={(n, s) => <FindNode node={n} state={s} tab={tab} marks={marks} />}
empty={
<span className={styles.empty}>
{st.status === "searching" || st.status === "validating" ? "Searching…" : "No matches"}
</span>
}
/>
</SplitPanel>
{showPreview && (
<>
<SplitHandle aria-label={tx("Resize find preview")} />
<SplitPanel id="preview" minSize={minPanelSize} defaultSize="45%" className={styles.splitPanel}>
<CodePreview path={preview?.path ?? null} line={preview?.line ?? 0} highlights={highlights} />
</SplitPanel>
</>
)}
</SplitGroup>
<div className={styles.body} onKeyDown={onKeyDown}>
<div className={styles.summary}>
{(st.status === "searching" || busy) && <Spinner size={16} variant="spokes" />}
<span className={styles.title}>{tab.title}</span>
<span className={styles.count}>
{st.status === "invalid" || st.status === "error"
? (st.error ?? tx("Search failed"))
: progress
? tx`Replacing… ${progress.done}/${progress.total} files`
: t(st.summary?.limitHit ? "search.find.matchesIncomplete" : "search.find.matches", {
matches: st.matchCount,
files: st.files.length,
}) + (marks.excluded.size ? ` · ${tx`${marks.excluded.size} excluded`}` : "")}
</span>
<span className={styles.spacer} />
<Button size="small" variant="ghost" disabled={!selection.size} onClick={exclude} title="Exclude / include (⌫)">
<T>Exclude</T>
</Button>
{replaceMode && (
<div className={styles.replaceActions}>
<>
{running && (
<Button size="small" onClick={() => running.cancel()}>
<T>Stop</T>
@@ -530,9 +428,102 @@ function FindTabView({ tab }: { tab: FindTab }) {
>
<T>Replace All</T>
</Button>
</div>
</>
)}
</div>
<SplitGroup
orientation="horizontal"
className={styles.split}
id="find-results-split"
storageKey={showPreview ? "openidea.find.previewSplit" : undefined}
>
<SplitPanel id="results" minSize={120} className={styles.splitPanel}>
<Tree<Node>
className={styles.tree}
aria-label="Find results"
handleRef={tree}
roots={roots}
getKey={(n) => n.key}
getLabel={(n) => (n.kind === "dir" ? n.label : n.kind === "file" ? n.name : n.text)}
getChildren={(n) => (n.kind === "match" ? undefined : n.children)}
isExpandable={(n) => n.kind !== "match"}
isOccurrence={(n) => n.kind === "match" && groupState(nodeGroups(n)[0]!, marks) !== "excluded"}
expanded={expanded}
onExpandedChange={(next) => {
const all = allExpandableKeys(roots);
setCollapsed(tab.id, new Set([...all].filter((k) => !next.has(k))));
}}
selected={selection}
onSelectionChange={(next, lead) => {
setSelection(next);
setLeadNode(lead);
if (tab.editorResults && lead?.kind === "match")
void openLocation(
lead.path,
{ line: lead.line, col: lead.col, endLine: lead.line, endCol: lead.endCol },
{ focus: false },
);
}}
multiSelect
onActivate={(n) => {
if (n.kind === "match")
void openLocation(
n.path,
{ line: n.line, col: n.col, endLine: n.line, endCol: n.endCol },
{ focus: true },
);
else if (n.kind === "file") void openLocation(n.path, previewOf(n) ? { line: previewOf(n)!.line } : null);
}}
onContextMenu={(_n, sel, e) => {
const groups = [...sel].flatMap((k) => (byKey.get(k) ? nodeGroups(byKey.get(k)!) : []));
const excludedAll = groups.length > 0 && groups.every((g) => groupState(g, marks) === "excluded");
showContextMenu(e, [
...(_n?.kind === "match"
? menuGroupItems("searchResults", { paths: [_n.path], line: _n.line, column: _n.col })
: []),
{
id: "exclude",
label: excludedAll ? "Include" : "Exclude",
shortcut: "⌫",
disabled: !groups.length,
run: exclude,
},
...(replaceMode
? [
{
id: "replace",
label: "Replace Selected",
disabled: busy || !pendingUsages(groups, marks).length,
run: () => void replace(pendingUsages(groups, marks)),
},
{
id: "preview",
label: "Preview Replacement",
disabled: busy || !groups.length,
run: () => void previewReplace(),
},
]
: []),
]);
}}
activateExpandable={false}
renderNode={(n, s) => <FindNode node={n} state={s} tab={tab} marks={marks} />}
empty={
<span className={styles.empty}>
{st.status === "searching" || st.status === "validating" ? "Searching…" : "No matches"}
</span>
}
/>
</SplitPanel>
{showPreview && (
<>
<SplitHandle />
<SplitPanel id="preview" minSize={120} defaultSize="45%" className={styles.splitPanel}>
<CodePreview path={preview?.path ?? null} line={preview?.line ?? 0} highlights={highlights} />
</SplitPanel>
</>
)}
</SplitGroup>
</div>
);
}
@@ -564,11 +555,7 @@ function FindNodeContent({ node, state, tab }: { node: Node; state: TreeRowState
<Icon name={fileIconName(node.name)} size={16} className={styles.icon} />
<span className={styles.label}>{node.name}</span>
<span className={styles.meta}>{node.count}</span>
{!state.depth && node.dir && (
<span className={styles.directory} title={node.dir}>
{node.dir}
</span>
)}
{!state.depth && node.dir && <span className={styles.meta}>{node.dir}</span>}
</span>
);
case "match":
@@ -590,20 +577,15 @@ function FindNodeContent({ node, state, tab }: { node: Node; state: TreeRowState
}
}
function FindActions({
tab,
roots,
canExclude,
onExclude,
}: {
tab: FindTab;
roots: readonly Node[];
canExclude: boolean;
onExclude: () => void;
}) {
/** Header controls of the Find tool window. */
export function FindToolWindowActions() {
const tabs = useFindWindow((s) => s.tabs);
const activeId = useFindWindow((s) => s.active);
const tab = tabs.find((t) => t.id === activeId) ?? tabs[tabs.length - 1];
if (!tab) return null;
const searching = tab.state.status === "searching";
return (
<div className={styles.toolbar} role="toolbar" aria-orientation="vertical" aria-label={tx("Find actions")}>
<>
<IconButton icon="arrow-up" action="navigate.prevOccurrence" size="small" />
<IconButton icon="arrow-down" action="navigate.nextOccurrence" size="small" />
{searching ? (
@@ -622,10 +604,14 @@ function FindActions({
icon="collapse-all"
title="Collapse All"
size="small"
onClick={() => setCollapsed(tab.id, allExpandableKeys(roots))}
onClick={() =>
setCollapsed(
tab.id,
allExpandableKeys(buildFindTree(tab.state.files, useFindViewOptions.getState().groupByDirectory)),
)
}
/>
<IconButton icon="minus" title="Exclude / include (⌫)" size="small" disabled={!canExclude} onClick={onExclude} />
<IconButton icon="close" title="Close Tab" size="small" onClick={() => closeFindTab(tab.id)} />
</div>
</>
);
}
+1
View File
@@ -221,6 +221,7 @@ export function activate(): void | (() => void) {
order: 5,
component: lazyComponent(() => import("./find/FindToolWindow").then((m) => m.FindToolWindow)),
headerContent: lazyComponent(() => import("./find/FindToolWindow").then((m) => m.FindTabs)),
headerActions: lazyComponent(() => import("./find/FindToolWindow").then((m) => m.FindToolWindowActions)),
headerMenu: useFindHeaderMenu,
}),
@@ -102,20 +102,6 @@
.locations > * {
flex: 1;
}
.switcher {
min-height: min(350px, 80vh);
}
.switcher .columns {
flex: auto;
height: auto;
max-height: 440px;
}
.switcher .tools {
width: clamp(112px, 32%, 184px);
}
.switcher .footer {
font-size: var(--fs-small);
}
.locationsLink {
flex: none;
display: flex;
@@ -281,13 +267,6 @@
.tools .shortcut {
display: none;
}
.switcher .columns {
--list-inset: var(--space-1);
}
.switcher .columns [role="option"] {
gap: var(--space-1);
padding-inline: var(--space-1);
}
.locationsLink {
margin-inline: var(--space-1);
}
+2 -2
View File
@@ -325,9 +325,9 @@ function RecentFilesDialog() {
open
onClose={hideRecentPopup}
restoreFocus={keepFocus}
width={switcher ? 560 : 720}
width={720}
aria-label={title}
className={clsx(styles.dialog, switcher && styles.switcher)}
className={styles.dialog}
>
<header className={styles.header}>
<span className={styles.title}>
@@ -1,61 +0,0 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const backend = vi.hoisted(() => ({
snapshot: vi.fn(),
op: vi.fn(),
remove: vi.fn(),
}));
vi.mock("@tauri-apps/api/core", () => ({ Channel: class {} }));
vi.mock("@/platform/ipc", async (original) => ({
...(await original<typeof import("@/platform/ipc")>()),
isTauri: () => true,
commands: {
dockerSnapshot: backend.snapshot,
dockerContainerOp: backend.op,
dockerRemove: backend.remove,
},
}));
import type { DockerContainer } from "@/platform/ipc";
import type { DockerTarget } from "./model";
import { canRestart, canStart, canStop, restart, start, targetBusy } from "./ops";
import { busyOp, containerOp, useServices } from "./store";
const ok = <T>(data: T) => ({ status: "ok" as const, data });
const box = { id: "box", name: "Box", endpoint: { kind: "default" } };
const container = { id: "c1", name: "web", state: "exited", status: "Exited (0)" } as DockerContainer;
const target: DockerTarget = { conn: "box", node: { kind: "container", key: "container:c1", container } };
beforeEach(() => {
for (const f of Object.values(backend)) f.mockReset();
backend.snapshot.mockResolvedValue(ok({ availability: { kind: "ready", context: null }, errors: [] }));
useServices.setState({ settings: { connections: [box], registries: [] } as never, conns: {}, task: null });
});
describe("container operations in progress", () => {
it("disable the container's actions until the snapshot after them has loaded", async () => {
let finish!: () => void;
backend.op.mockReturnValue(new Promise((resolve) => (finish = () => resolve(ok(null)))));
const running = start(target);
await vi.waitFor(() => expect(backend.op).toHaveBeenCalledTimes(1));
expect(busyOp("box", ["c1"])).toBe("start");
expect(targetBusy(target)).toBe("start");
expect([canStart(target), canStop(target), canRestart(target)]).toEqual([false, false, false]);
// A second click while the first runs does nothing.
await restart(target);
expect(backend.op).toHaveBeenCalledTimes(1);
finish();
await running;
expect(backend.snapshot).toHaveBeenCalled();
expect(busyOp("box", ["c1"])).toBeNull();
expect(canStart(target)).toBe(true);
});
it("release the container when the operation fails", async () => {
backend.op.mockRejectedValue(new Error("daemon gone"));
expect(await containerOp("box", ["c1"], "stop")).toBe(false);
expect(busyOp("box", ["c1"])).toBeNull();
});
});
+21 -63
View File
@@ -37,21 +37,9 @@ import {
treeKey,
type DockerTarget,
} from "./model";
import {
canRemove,
canRestart,
canStart,
canStop,
execShell,
remove,
restart,
showDetail,
start,
stop,
targetBusy,
} from "./ops";
import { canRemove, canRestart, canStart, canStop, execShell, remove, restart, showDetail, start, stop } from "./ops";
import { openContainerLogInEditor } from "./logEditor";
import { containerOp, endpointOf, errorMessage, useServices } from "./store";
import { containerOp, endpointOf, errorMessage } from "./store";
import { useServicesTree } from "./tree";
import styles from "./Services.module.css";
@@ -670,26 +658,6 @@ function ContainerLinkChip({ conn, container }: { conn: string; container: Docke
// ---------------------------------------------------------------------------
// Container Dashboard & Processes View
/** A dashboard action button that shows a spinner while its operation runs. */
function OpButton({
busy,
disabled,
onClick,
children,
}: {
busy: boolean;
disabled: boolean;
onClick: () => void;
children: string;
}) {
return (
<Button size="small" disabled={disabled} aria-busy={busy || undefined} onClick={onClick}>
{busy && <Spinner size={12} />}
<T>{children}</T>
</Button>
);
}
export function ContainerDashboard({
conn,
container,
@@ -706,7 +674,6 @@ export function ContainerDashboard({
conn,
node: { kind: "container", key: `container:${container.id}`, container },
};
const busy = useServices((s) => targetBusy(target, s));
const inspect = useMemo(() => parseContainerInspect(inspectText, container.ports), [inspectText, container.ports]);
const ports = useMemo(() => inspect?.ports ?? parsePortMappings(container.ports), [inspect, container.ports]);
const matchedImage = useMemo(() => findImageForContainer(snapshot, container), [snapshot, container]);
@@ -741,33 +708,25 @@ export function ContainerDashboard({
return (
<div className={styles.dashboard} tabIndex={0} onKeyDown={copySelectionOnKeyDown}>
<div className={styles.dashboardActions}>
<OpButton busy={busy === "start"} disabled={!canStart(target)} onClick={() => void start(target)}>
<Button size="small" disabled={!canStart(target)} onClick={() => void start(target)}>
Start
</OpButton>
<OpButton busy={busy === "stop"} disabled={!canStop(target)} onClick={() => void stop(target)}>
</Button>
<Button size="small" disabled={!canStop(target)} onClick={() => void stop(target)}>
Stop
</OpButton>
<OpButton busy={busy === "restart"} disabled={!canRestart(target)} onClick={() => void restart(target)}>
</Button>
<Button size="small" disabled={!canRestart(target)} onClick={() => void restart(target)}>
Restart
</OpButton>
</Button>
{container.state === "paused" ? (
<OpButton
busy={busy === "unpause"}
disabled={!!busy}
onClick={() => void containerOp(conn, [container.id], "unpause")}
>
<Button size="small" onClick={() => void containerOp(conn, [container.id], "unpause")}>
Unpause
</OpButton>
</Button>
) : (
<OpButton
busy={busy === "pause"}
disabled={!running || !!busy}
onClick={() => void containerOp(conn, [container.id], "pause")}
>
<Button size="small" disabled={!running} onClick={() => void containerOp(conn, [container.id], "pause")}>
Pause
</OpButton>
</Button>
)}
<Button size="small" disabled={!running || !!busy} onClick={() => execShell(target)}>
<Button size="small" disabled={!running} onClick={() => execShell(target)}>
Create Terminal
</Button>
<Button size="small" onClick={() => showDetail("log")}>
@@ -776,9 +735,9 @@ export function ContainerDashboard({
<Button size="small" onClick={() => openContainerLogInEditor(conn, container)}>
Open Log in Editor
</Button>
<OpButton busy={busy === "remove"} disabled={!canRemove(target)} onClick={() => void remove(target)}>
<Button size="small" disabled={!canRemove(target)} onClick={() => void remove(target)}>
Delete…
</OpButton>
</Button>
</div>
<SectionBanner>
@@ -1584,22 +1543,21 @@ export function ComposeProjectDashboard({
conn,
node: { kind: "compose", key: `compose:${project}`, project, containers },
};
const busy = useServices((s) => targetBusy(target, s));
const first = containers[0];
const runningCount = containers.filter(isRunning).length;
return (
<div className={styles.dashboard} tabIndex={0} onKeyDown={copySelectionOnKeyDown}>
<div className={styles.dashboardActions}>
<OpButton busy={busy === "start"} disabled={!canStart(target)} onClick={() => void start(target)}>
<Button size="small" disabled={!canStart(target)} onClick={() => void start(target)}>
Start
</OpButton>
<OpButton busy={busy === "stop"} disabled={!canStop(target)} onClick={() => void stop(target)}>
</Button>
<Button size="small" disabled={!canStop(target)} onClick={() => void stop(target)}>
Stop
</OpButton>
<OpButton busy={busy === "restart"} disabled={!canRestart(target)} onClick={() => void restart(target)}>
</Button>
<Button size="small" disabled={!canRestart(target)} onClick={() => void restart(target)}>
Restart
</OpButton>
</Button>
<Button size="small" disabled={!canRemove(target)} onClick={() => void remove(target)}>
Compose Down
</Button>
Loaded 100 of 146 files, more files were not shown because too many files have changed in this diff. Show more