дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-28 21:42:27 +02:00
Порівняти коміти
18
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
7dee96dc64 | ||
|
|
9293b13737 | ||
|
|
d1f79d05b3 | ||
|
|
176c43c908 | ||
|
|
20b6b0aed5 | ||
|
|
101a0862e4 | ||
|
|
b48f0b6071 | ||
|
|
a9b16c3e06 | ||
|
|
abd55f88b5 | ||
|
|
dac4db0994 | ||
|
|
b0d0ea868b | ||
|
|
d86ff872af | ||
|
|
dbef3cdc96 | ||
|
|
c483c3b76f | ||
|
|
da79a73def | ||
|
|
2cc54b35f6 | ||
|
|
097221c1b3 | ||
|
|
1bb4ffe6b2 |
No files matched your search
@@ -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());
|
||||
|
||||
@@ -132,6 +132,7 @@ 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>,
|
||||
}
|
||||
@@ -193,6 +194,7 @@ 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),
|
||||
}
|
||||
@@ -1126,6 +1128,16 @@ 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;
|
||||
@@ -1146,17 +1158,19 @@ impl AgentManager {
|
||||
task.emit_task();
|
||||
return Ok(());
|
||||
}
|
||||
let target = s
|
||||
.task
|
||||
.config
|
||||
.iter()
|
||||
.find(|o| o.id == option)
|
||||
.ok_or_else(|| IdeError::not_found("no such setting"))?
|
||||
.clone();
|
||||
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")),
|
||||
};
|
||||
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 !target.values.iter().any(|v| v.value == value) {
|
||||
if recovered_model {
|
||||
(target, None)
|
||||
} else 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)));
|
||||
}
|
||||
@@ -2799,9 +2813,12 @@ 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(&launch_cwd))
|
||||
.await
|
||||
.map_err(|e| SessionOpenError { message: e.to_string(), allow_acp_fallback: false })?;
|
||||
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 })?;
|
||||
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) {
|
||||
|
||||
@@ -144,7 +144,8 @@ 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.to_string(), allow_acp_fallback: false })?
|
||||
.map_err(|e| DiscoverError { message: e, allow_acp_fallback: false })?;
|
||||
let cwd = dunce::canonicalize(&cwd).unwrap_or(cwd);
|
||||
let args = headless_args(&launch.args);
|
||||
let peer = Peer::spawn_framed(
|
||||
|
||||
@@ -312,7 +312,7 @@ impl Settings {
|
||||
}
|
||||
|
||||
/// Parses `models.list` + optional `models.listTokenPriceUnits` into catalog entries,
|
||||
/// prepending `"auto"` when not already in the list.
|
||||
/// prepending `"auto"` when direct models are present or Copilot advertises an enabled Auto tier.
|
||||
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() {
|
||||
if !raw.iter().any(|m| str_of(m, "id") == Some("auto")) && (!raw.is_empty() || auto_model_available(list)) {
|
||||
out.push(ModelEntry {
|
||||
id: "auto".into(),
|
||||
name: "Auto".into(),
|
||||
@@ -344,6 +344,18 @@ 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,6 +110,72 @@ 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()));
|
||||
|
||||
@@ -9,6 +9,8 @@ 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)]
|
||||
@@ -138,15 +140,31 @@ 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_with_copilot_env(cwd, strip)
|
||||
self.resolve_for_launch_base(cwd, strip)
|
||||
}
|
||||
|
||||
pub(crate) fn resolve_for_launch_with_copilot_env(mut self, cwd: &Path, strip_ambient_tokens: bool) -> Self {
|
||||
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 {
|
||||
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 =
|
||||
@@ -164,6 +182,50 @@ 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)
|
||||
}
|
||||
@@ -339,6 +401,31 @@ 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)
|
||||
}
|
||||
|
||||
@@ -955,6 +1042,46 @@ 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();
|
||||
|
||||
@@ -537,6 +537,14 @@ 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,
|
||||
|
||||
@@ -2333,6 +2333,56 @@ 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();
|
||||
|
||||
@@ -749,6 +749,14 @@ 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",
|
||||
|
||||
@@ -458,6 +458,44 @@ 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()),
|
||||
|
||||
@@ -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.rows(p.ping_sql(), 1).await {
|
||||
tracing::debug!("keep-alive: {}", e.message);
|
||||
if let Err(e) = p.ping().await {
|
||||
tracing::info!("keep-alive: {}", e.message);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -847,12 +847,12 @@ impl DbManager {
|
||||
}
|
||||
|
||||
pub fn is_connected(&self, id: &str) -> bool {
|
||||
self.pools.lock().contains_key(id)
|
||||
self.pools.lock().get(id).is_some_and(|p| !p.is_closed())
|
||||
}
|
||||
|
||||
/// Connected targets (data source ids, `<id>:<database>`).
|
||||
pub fn connected(&self) -> Vec<String> {
|
||||
self.pools.lock().keys().cloned().collect()
|
||||
self.pools.lock().iter().filter(|(_, p)| !p.is_closed()).map(|(id, _)| id.clone()).collect()
|
||||
}
|
||||
|
||||
/// The pool of target `id`, connecting first if needed.
|
||||
@@ -862,8 +862,13 @@ impl DbManager {
|
||||
if self.tunnels.lock().get(source_id).is_some_and(|t| t.is_closed()) {
|
||||
self.disconnect_source(source_id).await;
|
||||
}
|
||||
if let Some(p) = self.pools.lock().get(id) {
|
||||
return Ok(p.clone());
|
||||
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;
|
||||
}
|
||||
let source = self.source(id)?;
|
||||
let password = self.password(&source).await;
|
||||
@@ -917,7 +922,7 @@ impl DbManager {
|
||||
|
||||
/// Disconnects every database of data source `id`.
|
||||
pub async fn disconnect_source(&self, id: &str) {
|
||||
let targets: Vec<String> = self.connected().into_iter().filter(|t| split_target(t).0 == id).collect();
|
||||
let targets: Vec<String> = self.pools.lock().keys().filter(|t| split_target(t).0 == id).cloned().collect();
|
||||
for t in targets {
|
||||
self.disconnect(&t).await;
|
||||
}
|
||||
|
||||
@@ -213,3 +213,36 @@ 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(())
|
||||
}
|
||||
@@ -7,9 +7,10 @@
|
||||
|
||||
use crate::{
|
||||
COMPOSE_DIR, COMPOSE_FILES, COMPOSE_PROJECT, COMPOSE_SERVICE, ContainerOp, DockerAvailability, DockerContainer,
|
||||
DockerEndpoint, DockerImage, DockerNetwork, DockerObject, DockerSnapshot, DockerVolume, split_csv,
|
||||
DockerEndpoint, DockerImage, DockerImageLayer, DockerLogLine, DockerNetwork, DockerObject, DockerProcessList,
|
||||
DockerSnapshot, DockerVolume, split_csv,
|
||||
};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use serde::Deserialize;
|
||||
use std::collections::BTreeMap;
|
||||
use std::io::{Read, Write};
|
||||
@@ -193,9 +194,15 @@ fn request(addr: &Address, method: &str, path: &str, timeout: Duration) -> IdeRe
|
||||
read_response(&mut conn)
|
||||
}
|
||||
|
||||
/// 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> {
|
||||
/// 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> {
|
||||
let mut head: Vec<u8> = Vec::new();
|
||||
let mut byte = [0u8; 1];
|
||||
loop {
|
||||
@@ -228,16 +235,27 @@ fn read_response(stream: &mut impl Read) -> IdeResult<Response> {
|
||||
length = value.parse().ok();
|
||||
}
|
||||
}
|
||||
let body = if chunked {
|
||||
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 {
|
||||
read_chunked(stream)?
|
||||
} else if let Some(n) = length {
|
||||
} else if let Some(n) = head.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).
|
||||
@@ -482,6 +500,292 @@ 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={}×tamps={}",
|
||||
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());
|
||||
@@ -817,6 +1121,75 @@ 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() };
|
||||
|
||||
@@ -287,6 +287,11 @@ 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))
|
||||
}
|
||||
@@ -294,6 +299,11 @@ 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))
|
||||
}
|
||||
@@ -316,6 +326,11 @@ 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 {
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
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);
|
||||
});
|
||||
@@ -0,0 +1,75 @@
|
||||
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");
|
||||
});
|
||||
@@ -64,3 +64,15 @@ 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();
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
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();
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
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");
|
||||
});
|
||||
@@ -0,0 +1,65 @@
|
||||
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");
|
||||
});
|
||||
Бінарний файл не відображається.
@@ -243,6 +243,20 @@ 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()) {
|
||||
|
||||
@@ -14,6 +14,7 @@ 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;
|
||||
|
||||
@@ -36,6 +37,8 @@ public class SelfTest {
|
||||
case "getMetaData" -> meta;
|
||||
case "close" -> null;
|
||||
case "createStatement" -> statement();
|
||||
case "isClosed" -> false;
|
||||
case "isValid" -> !dropped;
|
||||
default -> throw new SQLFeatureNotSupportedException();
|
||||
});
|
||||
}
|
||||
@@ -53,6 +56,7 @@ 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;
|
||||
}
|
||||
@@ -122,6 +126,12 @@ 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");
|
||||
} finally {
|
||||
child.destroyForcibly().waitFor();
|
||||
}
|
||||
|
||||
@@ -394,6 +394,11 @@ 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)!);
|
||||
|
||||
@@ -420,6 +420,9 @@ 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,
|
||||
@@ -437,6 +440,7 @@ 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,
|
||||
|
||||
@@ -276,14 +276,23 @@ export const openideaTheme = EditorView.theme({
|
||||
},
|
||||
".cm-openidea-laneDeleted": {
|
||||
position: "absolute",
|
||||
left: "0",
|
||||
top: "-3px",
|
||||
left: "-4px",
|
||||
top: "-6px",
|
||||
width: "12px",
|
||||
height: "12px",
|
||||
cursor: "pointer",
|
||||
zIndex: "1",
|
||||
},
|
||||
".cm-openidea-laneDeleted::after": {
|
||||
content: '""',
|
||||
position: "absolute",
|
||||
left: "4px",
|
||||
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,15 +11,37 @@
|
||||
.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: 2;
|
||||
min-height: 84px;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.label {
|
||||
@@ -27,7 +49,9 @@
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
font-family: var(--font-mono);
|
||||
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);
|
||||
}
|
||||
|
||||
.detail {
|
||||
@@ -36,8 +60,12 @@
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
|
||||
.previewPanel {
|
||||
padding-top: var(--space-2);
|
||||
}
|
||||
|
||||
.preview {
|
||||
flex: 3;
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
border: 1px solid var(--border-strong);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useEffect, useLayoutEffect, useRef, useState, type KeyboardEvent } from "react";
|
||||
import { useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type KeyboardEvent } from "react";
|
||||
import { create } from "zustand";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { EditorView, highlightSpecialChars, lineNumbers } from "@codemirror/view";
|
||||
import { EditorView, highlightSpecialChars } from "@codemirror/view";
|
||||
import { language, syntaxHighlighting } from "@codemirror/language";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { isImeKey } from "@/platform/ime";
|
||||
@@ -9,11 +9,14 @@ 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,
|
||||
@@ -22,9 +25,11 @@ 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";
|
||||
|
||||
@@ -82,6 +87,11 @@ 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()))
|
||||
@@ -156,7 +166,7 @@ function PasteHistoryDialog({ view, paste, onClose }: Request & { onClose: () =>
|
||||
title="Choose Content to Paste"
|
||||
onClose={onClose}
|
||||
className={styles.dialog}
|
||||
width={680}
|
||||
width={560}
|
||||
resizable="both"
|
||||
minWidth={360}
|
||||
minHeight={320}
|
||||
@@ -169,48 +179,63 @@ 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)}
|
||||
>
|
||||
<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} />
|
||||
<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>
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
@@ -228,11 +253,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(),
|
||||
],
|
||||
}),
|
||||
|
||||
@@ -35,6 +35,10 @@ 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;
|
||||
@@ -819,13 +823,26 @@ function ProviderSettings({
|
||||
onChanged?.();
|
||||
return command === agent.defaultProgram ? "" : (command ?? "");
|
||||
});
|
||||
const envBase = formatEnv(agent.env);
|
||||
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 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(parsed);
|
||||
return formatEnv(launchEnv(parsed));
|
||||
});
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
// An edit can have been staged by a previous page instance. Its Apply callback
|
||||
@@ -849,6 +866,27 @@ 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}
|
||||
|
||||
@@ -284,7 +284,7 @@ function ModelPicker({
|
||||
const pinnedModels = useAgents((s) => s.pinnedModels);
|
||||
const anchor = useRef<HTMLButtonElement>(null);
|
||||
const selectedModel = selected(model, modelValue);
|
||||
const unavailable = modelRefresh?.draft && modelValue !== null && !selectedModel;
|
||||
const unavailable = !!modelRefresh && modelValue !== null && !selectedModel;
|
||||
const modelName = unavailable
|
||||
? tx`${modelValue} (unavailable)`
|
||||
: (selectedModel?.name ?? (modelRefresh ? modelValue : null) ?? tx("Default"));
|
||||
|
||||
@@ -469,7 +469,7 @@ describe("Built-in executable overrides", () => {
|
||||
dispose();
|
||||
});
|
||||
|
||||
const openCommands = async (commands: FakeCommands, onChanged = vi.fn()) => {
|
||||
const openCommands = async (commands: FakeCommands, onChanged = vi.fn(), name = "Claude Code") => {
|
||||
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: "Claude Code" });
|
||||
return screen.findByRole("region", { name });
|
||||
};
|
||||
const apply = () => screen.getByRole("button", { name: "Apply" });
|
||||
const field = () => screen.getByRole("textbox", { name: "Executable" });
|
||||
@@ -564,6 +564,38 @@ 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 = [
|
||||
|
||||
@@ -251,6 +251,44 @@ 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 />);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { AgentChange, AgentCommit, AgentEntry, AgentTask } from "@/bindings";
|
||||
import type { AgentChange, AgentCommit, AgentConfigOption, AgentEntry, AgentTask } from "@/bindings";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { tx, useTx } from "@/platform/i18n";
|
||||
import { useProject } from "@/platform/project";
|
||||
@@ -161,18 +161,37 @@ export function SessionComposer({
|
||||
const catalog = useAgents((s) => s.modelCatalogs.get(task.provider));
|
||||
const requestingModels = useAgents((s) => s.modelRequests.has(task.provider));
|
||||
const model = task.config.find((o) => o.category === "model");
|
||||
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 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 pickerConfig = useMemo(() => {
|
||||
if (!model || !candidateModels?.length) return task.config;
|
||||
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;
|
||||
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, model, candidateModels]);
|
||||
}, [task.config, task.model, model, catalogModel, canRefreshModels]);
|
||||
const [sending, setSending] = useState(false);
|
||||
const configChange = useRef<{ loadingModel: boolean } | null>(null);
|
||||
const [configuring, setConfiguring] = useState<typeof configChange.current>(null);
|
||||
|
||||
@@ -421,7 +421,7 @@ export async function refreshModels(
|
||||
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.config.some((o) => o.category === "model")) return;
|
||||
if (!task || task.status === "archived" || (!task.model && !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, null, null);
|
||||
|
||||
@@ -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(["dev", "ci"]);
|
||||
expect(labels(children(roots[0]!))).toEqual(["ci", "dev"]);
|
||||
const top = children(roots[1]!);
|
||||
expect(labels(top)).toEqual(["Lifecycle", "Plugins", "core", "Demo App"]);
|
||||
expect(labels(children(top[0]!))).toEqual([
|
||||
@@ -148,6 +148,22 @@ 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);
|
||||
|
||||
@@ -187,6 +187,11 @@ 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;
|
||||
|
||||
@@ -1020,14 +1020,16 @@ 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}
|
||||
|
||||
@@ -1072,6 +1072,18 @@ 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[],
|
||||
@@ -1087,6 +1099,8 @@ 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.getByText(", main.py:12")).toBeTruthy();
|
||||
expect(screen.getByRole("option", { selected: true })).toHaveTextContent("main:12, main.py");
|
||||
expect(screen.getByPlaceholderText("Evaluate expression (↩) or add a watch (⇧⌘↩)")).toBeTruthy();
|
||||
expect(await screen.findByText("{int}")).toBeTruthy();
|
||||
expect(screen.getByText("'hi'")).toBeTruthy();
|
||||
|
||||
@@ -102,11 +102,20 @@
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
padding: 4px 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);
|
||||
}
|
||||
|
||||
.threadSelect {
|
||||
margin: 0 8px 4px;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.frameList {
|
||||
@@ -116,7 +125,7 @@
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
outline: none;
|
||||
padding: 0 4px;
|
||||
padding: var(--space-1) var(--space-1) 0;
|
||||
}
|
||||
|
||||
.frame {
|
||||
@@ -150,24 +159,36 @@
|
||||
flex: none;
|
||||
}
|
||||
|
||||
.frameName {
|
||||
.frameText,
|
||||
.frameLabel {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
min-width: 0;
|
||||
}
|
||||
.frameText {
|
||||
flex: 1;
|
||||
}
|
||||
.frameLine {
|
||||
flex: none;
|
||||
}
|
||||
.frameName,
|
||||
.frameFile {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.frameFile {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
/* ", File.java:12" hugs the name, cancelling the row gap. */
|
||||
margin-left: -6px;
|
||||
flex: 0 1000 auto;
|
||||
min-width: min(12ch, 32%);
|
||||
color: var(--fg-subtle);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
|
||||
.hiddenFrames {
|
||||
display: block;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
color: var(--fg-subtle);
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/** Debug tool window: toolbar, Threads & Variables (frames + variables), Console. */
|
||||
import { writeClipboardText } from "@/platform/clipboard";
|
||||
import { useEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";
|
||||
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";
|
||||
import clsx from "clsx";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { basename, useProject } from "@/platform/project";
|
||||
@@ -22,6 +22,7 @@ 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";
|
||||
@@ -347,10 +348,15 @@ 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;
|
||||
@@ -365,19 +371,24 @@ function FramesPane({ session }: { session: DebugSession }) {
|
||||
return (
|
||||
<div className={styles.frames}>
|
||||
{session.threads.length > 0 && (
|
||||
<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 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>
|
||||
)}
|
||||
<div
|
||||
ref={list}
|
||||
className={styles.frameList}
|
||||
role="listbox"
|
||||
aria-label={tx("Frames")}
|
||||
@@ -415,9 +426,11 @@ 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,
|
||||
@@ -459,13 +472,15 @@ function FramesPane({ session }: { session: DebugSession }) {
|
||||
}}
|
||||
>
|
||||
<Icon name="method" size={16} className={styles.frameIcon} />
|
||||
<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 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>
|
||||
)}
|
||||
{item.frame.path && <span className={styles.frameFile}>, {basename(item.frame.path)}</span>}
|
||||
</span>
|
||||
</button>
|
||||
),
|
||||
)}
|
||||
|
||||
@@ -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.selected ? s.exchanges[s.selected] : undefined));
|
||||
const exchange = useHttpClient((s) => s.exchanges.find((e) => e.entry.id === s.selected));
|
||||
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: { e1: exchange }, selected: "e1" });
|
||||
useHttpClient.setState({ history: [exchange.entry], exchanges: [exchange], selected: "e1" });
|
||||
render(<HttpClientView />);
|
||||
const body = screen.getByLabelText("Response body");
|
||||
fireEvent.keyDown(body, { key: "f", metaKey: true, ctrlKey: true });
|
||||
|
||||
@@ -237,6 +237,12 @@ 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;
|
||||
@@ -267,12 +273,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] = cond.split("=", 2);
|
||||
const [name, value] = condition(cond);
|
||||
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] = cond.split("=", 2);
|
||||
const [name, value] = condition(cond);
|
||||
if (name && !cond.includes("!") && value !== undefined) headers.push({ name: name.trim(), value: value.trim() });
|
||||
}
|
||||
const first = (key: string) =>
|
||||
|
||||
@@ -198,6 +198,32 @@ 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,10 +1,11 @@
|
||||
import { beforeEach, expect, it, vi } from "vitest";
|
||||
import type { HttpExchange, HttpRequestBlock } from "@/platform/ipc";
|
||||
import { runAll, runRequest, setEnvironment, useHttpClient } from "./store";
|
||||
import { runAll, runRequest, selectEntry, 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) => {
|
||||
@@ -95,3 +96,40 @@ 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")]);
|
||||
});
|
||||
@@ -14,6 +14,9 @@ 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> {
|
||||
@@ -41,8 +44,8 @@ interface HttpClientState {
|
||||
environments: Record<string, string[]>;
|
||||
/** History entries, newest first (this session's runs included). */
|
||||
history: HttpHistoryEntry[];
|
||||
/** Loaded exchanges by entry id. */
|
||||
exchanges: Record<string, HttpExchange>;
|
||||
/** Loaded exchanges, most recently viewed first. */
|
||||
exchanges: HttpExchange[];
|
||||
selected: string | null;
|
||||
running: Running | null;
|
||||
}
|
||||
@@ -51,7 +54,7 @@ export const useHttpClient = create<HttpClientState>(() => ({
|
||||
envByFile: readEnvChoices(),
|
||||
environments: {},
|
||||
history: [],
|
||||
exchanges: {},
|
||||
exchanges: [],
|
||||
selected: null,
|
||||
running: null,
|
||||
}));
|
||||
@@ -96,6 +99,10 @@ 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());
|
||||
@@ -106,12 +113,18 @@ 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) => ({ exchanges: { ...s.exchanges, [id]: ex } }));
|
||||
useHttpClient.setState((s) => (s.selected === id ? { exchanges: rememberExchange(ex, s.exchanges) } : s));
|
||||
} catch (e) {
|
||||
if (useHttpClient.getState().selected !== id) return;
|
||||
notifications().notify({
|
||||
level: "error",
|
||||
title: "Cannot open the response",
|
||||
@@ -122,7 +135,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[]> {
|
||||
@@ -159,8 +172,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)],
|
||||
exchanges: { ...s.exchanges, [ex.entry.id]: ex },
|
||||
history: [ex.entry, ...s.history.filter((h) => h.id !== ex.entry.id)].slice(0, HISTORY_LIMIT),
|
||||
exchanges: rememberExchange(ex, s.exchanges),
|
||||
selected: ex.entry.id,
|
||||
}));
|
||||
return true;
|
||||
@@ -235,5 +248,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 });
|
||||
}
|
||||
@@ -417,6 +417,9 @@ 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",
|
||||
),
|
||||
|
||||
@@ -102,6 +102,20 @@
|
||||
.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;
|
||||
@@ -267,6 +281,13 @@
|
||||
.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);
|
||||
}
|
||||
|
||||
@@ -325,9 +325,9 @@ function RecentFilesDialog() {
|
||||
open
|
||||
onClose={hideRecentPopup}
|
||||
restoreFocus={keepFocus}
|
||||
width={720}
|
||||
width={switcher ? 560 : 720}
|
||||
aria-label={title}
|
||||
className={styles.dialog}
|
||||
className={clsx(styles.dialog, switcher && styles.switcher)}
|
||||
>
|
||||
<header className={styles.header}>
|
||||
<span className={styles.title}>
|
||||
|
||||
@@ -1,25 +1,35 @@
|
||||
.tabs {
|
||||
margin-bottom: var(--space-3);
|
||||
}
|
||||
|
||||
.fileTypes {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(180px, 260px) minmax(0, 1fr);
|
||||
gap: var(--space-3);
|
||||
container: file-types / inline-size;
|
||||
height: clamp(382px, 67vh, 500px);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.split {
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.types {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-1-5);
|
||||
min-width: 0;
|
||||
height: 100%;
|
||||
padding-inline-end: var(--space-2);
|
||||
}
|
||||
|
||||
.filter {
|
||||
flex: none;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.typeList {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
max-height: 420px;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow: auto;
|
||||
padding: 2px 0;
|
||||
border-radius: var(--radius-small);
|
||||
@@ -27,11 +37,12 @@
|
||||
}
|
||||
|
||||
.type {
|
||||
flex: none;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
height: var(--h-row);
|
||||
padding: 0 8px;
|
||||
padding: 0 var(--space-2);
|
||||
border: none;
|
||||
background: none;
|
||||
color: var(--fg);
|
||||
@@ -65,6 +76,20 @@
|
||||
flex-direction: column;
|
||||
gap: var(--space-1);
|
||||
min-width: 0;
|
||||
height: 100%;
|
||||
overflow: auto;
|
||||
padding-inline-start: var(--space-3);
|
||||
}
|
||||
|
||||
.patterns > .patternRow {
|
||||
flex: none;
|
||||
margin-inline: 0;
|
||||
padding-inline: 0;
|
||||
}
|
||||
|
||||
.patterns [role="listbox"] {
|
||||
min-height: 72px;
|
||||
max-height: 128px;
|
||||
}
|
||||
|
||||
.note {
|
||||
@@ -74,10 +99,17 @@
|
||||
|
||||
.code {
|
||||
font-family: var(--font-mono);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.fileTypes {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
@container file-types (width < 530px) {
|
||||
.types {
|
||||
padding-inline-end: 0;
|
||||
padding-block-end: var(--space-2);
|
||||
}
|
||||
|
||||
.patterns {
|
||||
padding-inline-start: 0;
|
||||
padding-block-start: var(--space-2);
|
||||
}
|
||||
}
|
||||
@@ -4,9 +4,9 @@
|
||||
* user's) and hashbang patterns, stored in `files.fileTypes`. The backend
|
||||
* detects languages with them; open editors re-detect when they change.
|
||||
*/
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import clsx from "clsx";
|
||||
import { Icon, Input, T, fileIconName } from "@/ui";
|
||||
import { Icon, Input, SplitGroup, SplitHandle, SplitPanel, T, fileIconName } from "@/ui";
|
||||
import { commands, isTauri, type LanguageInfo_Serialize as LanguageInfo } from "@/platform/ipc";
|
||||
import {
|
||||
addPattern,
|
||||
@@ -52,6 +52,19 @@ export function applyPatternEdit(
|
||||
}
|
||||
|
||||
export function RecognizedFileTypes() {
|
||||
const desktop = isTauri();
|
||||
const container = useRef<HTMLDivElement>(null);
|
||||
const [stacked, setStacked] = useState(true);
|
||||
useLayoutEffect(() => {
|
||||
const element = container.current;
|
||||
if (!element) return;
|
||||
const measure = () => setStacked(element.clientWidth < 530);
|
||||
measure();
|
||||
if (typeof ResizeObserver === "undefined") return;
|
||||
const observer = new ResizeObserver(measure);
|
||||
observer.observe(element);
|
||||
return () => observer.disconnect();
|
||||
}, [desktop]);
|
||||
const langs = useLanguages();
|
||||
const [assoc, setAssoc] = useSetting<FileTypeAssociations>("files.fileTypes");
|
||||
const [filter, setFilter] = useState("");
|
||||
@@ -68,74 +81,87 @@ export function RecognizedFileTypes() {
|
||||
}, [langs, filter, assoc]);
|
||||
// Keep the last explicit choice for when it becomes visible again.
|
||||
const selected = shown.find((l) => l.id === selectedId) ?? shown[0] ?? null;
|
||||
if (!isTauri()) return null;
|
||||
if (!desktop) return null;
|
||||
const current = assoc ?? {};
|
||||
const patterns = selected ? effectivePatterns(selected, current).map((p) => p.pattern) : [];
|
||||
const hashbangs = selected ? (current[selected.id]?.hashbangs ?? []) : [];
|
||||
|
||||
return (
|
||||
<div className={styles.fileTypes}>
|
||||
<div className={styles.types}>
|
||||
<Input
|
||||
className={styles.filter}
|
||||
value={filter}
|
||||
placeholder="Filter file types"
|
||||
aria-label="Filter file types"
|
||||
onChange={(e) => setFilter(e.target.value)}
|
||||
/>
|
||||
<div className={styles.typeList} role="listbox" aria-label={tx("Recognized file types")}>
|
||||
{shown.map((l) => {
|
||||
const sample = sampleFileName(l);
|
||||
return (
|
||||
<button
|
||||
key={l.id}
|
||||
type="button"
|
||||
role="option"
|
||||
aria-selected={l.id === selected?.id}
|
||||
className={clsx(styles.type, l.id === selected?.id && styles.typeSelected)}
|
||||
onClick={() => setSelectedId(l.id)}
|
||||
<div className={styles.fileTypes} ref={container}>
|
||||
<SplitGroup orientation={stacked ? "vertical" : "horizontal"} className={styles.split}>
|
||||
<SplitPanel defaultSize="34%" minSize={stacked ? "106px" : "148px"}>
|
||||
<div className={styles.types}>
|
||||
<Input
|
||||
className={styles.filter}
|
||||
value={filter}
|
||||
placeholder="Filter file types"
|
||||
aria-label="Filter file types"
|
||||
onChange={(e) => setFilter(e.target.value)}
|
||||
/>
|
||||
<div className={styles.typeList} role="listbox" aria-label={tx("Recognized file types")}>
|
||||
{shown.map((l) => {
|
||||
const sample = sampleFileName(l);
|
||||
return (
|
||||
<button
|
||||
key={l.id}
|
||||
type="button"
|
||||
role="option"
|
||||
aria-selected={l.id === selected?.id}
|
||||
className={clsx(styles.type, l.id === selected?.id && styles.typeSelected)}
|
||||
onClick={() => setSelectedId(l.id)}
|
||||
>
|
||||
<Icon name={sample ? fileIconName(sample) : "file-text"} size={16} />
|
||||
<span className={styles.typeName}>{l.name}</span>
|
||||
{current[l.id] && (
|
||||
<span className={styles.modified}>
|
||||
<T>modified</T>
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</SplitPanel>
|
||||
<SplitHandle aria-label={tx("Resize file type panes")} />
|
||||
<SplitPanel defaultSize="66%" minSize={stacked ? "196px" : "190px"}>
|
||||
{selected && (
|
||||
<div className={styles.patterns} key={selected.id}>
|
||||
<Row
|
||||
className={styles.patternRow}
|
||||
label="File name patterns"
|
||||
stacked
|
||||
hint="* matches any characters, ? one (e.g. *.foo, Jenkinsfile)."
|
||||
>
|
||||
<Icon name={sample ? fileIconName(sample) : "file-text"} size={16} />
|
||||
<span className={styles.typeName}>{l.name}</span>
|
||||
{current[l.id] && (
|
||||
<span className={styles.modified}>
|
||||
<T>modified</T>
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
{selected && (
|
||||
<div className={styles.patterns} key={selected.id}>
|
||||
<Row label="File name patterns" stacked hint="* matches any characters, ? one (e.g. *.foo, Jenkinsfile).">
|
||||
<GlobListEditor
|
||||
value={patterns}
|
||||
onChange={(next) => setAssoc(applyPatternEdit(current, langs, selected, next))}
|
||||
placeholder="*.ext"
|
||||
aria-label={tx`File name patterns of ${selected.name}`}
|
||||
/>
|
||||
</Row>
|
||||
<Row
|
||||
label="Hashbang patterns"
|
||||
stacked
|
||||
hint="Interpreters run by a #! first line, e.g. node for #!/usr/bin/env node."
|
||||
>
|
||||
<GlobListEditor
|
||||
value={hashbangs}
|
||||
onChange={(next) => setAssoc(setHashbangs(current, selected.id, next))}
|
||||
placeholder="interpreter"
|
||||
aria-label={tx`Hashbang patterns of ${selected.name}`}
|
||||
/>
|
||||
</Row>
|
||||
{selected.firstLine && (
|
||||
<div className={styles.note}>
|
||||
<T>Also recognized by its first line:</T> <code className={styles.code}>{selected.firstLine}</code>
|
||||
<GlobListEditor
|
||||
value={patterns}
|
||||
onChange={(next) => setAssoc(applyPatternEdit(current, langs, selected, next))}
|
||||
placeholder="*.ext"
|
||||
aria-label={tx`File name patterns of ${selected.name}`}
|
||||
/>
|
||||
</Row>
|
||||
<Row
|
||||
className={styles.patternRow}
|
||||
label="Hashbang patterns"
|
||||
stacked
|
||||
hint="Interpreters run by a #! first line, e.g. node for #!/usr/bin/env node."
|
||||
>
|
||||
<GlobListEditor
|
||||
value={hashbangs}
|
||||
onChange={(next) => setAssoc(setHashbangs(current, selected.id, next))}
|
||||
placeholder="interpreter"
|
||||
aria-label={tx`Hashbang patterns of ${selected.name}`}
|
||||
/>
|
||||
</Row>
|
||||
{selected.firstLine && (
|
||||
<div className={styles.note}>
|
||||
<T>Also recognized by its first line:</T> <code className={styles.code}>{selected.firstLine}</code>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</SplitPanel>
|
||||
</SplitGroup>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,9 +1,14 @@
|
||||
/** Built-in settings pages (IDEA layout: Appearance & Behavior, Keymap, Editor). */
|
||||
import { useId, useState } from "react";
|
||||
import { Tabs } from "@/ui";
|
||||
import { GlobListEditor, Row } from "../components/Form";
|
||||
import { useSetting } from "../components/context";
|
||||
import { useSearchQuery, useSetting } from "../components/context";
|
||||
import { keymapSearchLabels } from "../keymap/model";
|
||||
import { labelMatches, queryTerms } from "../model/pages";
|
||||
import { lazyPage } from "./lazyPage";
|
||||
import type { PageSpec } from "./spec";
|
||||
import { OptionsPage } from "./OptionsPage";
|
||||
import { specLabels, type PageSpec, type SectionSpec } from "./spec";
|
||||
import styles from "./FileTypes.module.css";
|
||||
export const EDITOR_GROUP = "Editor";
|
||||
|
||||
const KeymapPage = lazyPage("keymap", () => import("../keymap/KeymapPage").then((m) => m.KeymapPage));
|
||||
@@ -38,22 +43,10 @@ function IgnoredNamesRow() {
|
||||
);
|
||||
}
|
||||
|
||||
export const BUILTIN_PAGES: PageSpec[] = [
|
||||
const FILE_TYPE_TABS: { id: string; label: string; sections: SectionSpec[] }[] = [
|
||||
{
|
||||
id: "keymap",
|
||||
title: "Keymap",
|
||||
order: 10,
|
||||
keywords: ["shortcut", "keyboard", "hotkey", "binding", "preset", "vs code", "intellij"],
|
||||
component: KeymapPage,
|
||||
dynamicLabels: keymapSearchLabels,
|
||||
},
|
||||
{
|
||||
id: "editor.files",
|
||||
title: "File Types",
|
||||
group: EDITOR_GROUP,
|
||||
order: 29,
|
||||
projectScope: true,
|
||||
keywords: ["ignore", "ignored", "excluded", "glob", "exclude patterns", "associate", "association", "extension"],
|
||||
id: "recognized",
|
||||
label: "Recognized File Types",
|
||||
sections: [
|
||||
{
|
||||
title: "Recognized File Types",
|
||||
@@ -77,6 +70,12 @@ export const BUILTIN_PAGES: PageSpec[] = [
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "ignored",
|
||||
label: "Ignored Files and Folders",
|
||||
sections: [
|
||||
{
|
||||
title: "Ignored Files and Folders",
|
||||
options: [
|
||||
@@ -87,3 +86,75 @@ export const BUILTIN_PAGES: PageSpec[] = [
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const FILE_TYPES: PageSpec = {
|
||||
id: "editor.files",
|
||||
title: "File Types",
|
||||
group: EDITOR_GROUP,
|
||||
order: 29,
|
||||
projectScope: true,
|
||||
keywords: ["ignore", "ignored", "excluded", "glob", "exclude patterns", "associate", "association", "extension"],
|
||||
sections: FILE_TYPE_TABS.flatMap((tab) => tab.sections),
|
||||
component: FileTypesPage,
|
||||
};
|
||||
|
||||
function FileTypesPage() {
|
||||
const prefix = useId();
|
||||
const query = useSearchQuery();
|
||||
const [selection, select] = useState({ id: "recognized", query: "" });
|
||||
let active = selection.id;
|
||||
if (query !== selection.query) {
|
||||
const terms = queryTerms(query);
|
||||
let best = 0;
|
||||
for (const tab of FILE_TYPE_TABS) {
|
||||
const labels = specLabels({ ...FILE_TYPES, keywords: [], sections: tab.sections });
|
||||
const score = terms.filter((term) => labels.some((label) => labelMatches(label, term))).length;
|
||||
if (score > best) {
|
||||
best = score;
|
||||
active = tab.id;
|
||||
}
|
||||
}
|
||||
}
|
||||
return (
|
||||
<>
|
||||
<Tabs
|
||||
aria-label="File Types"
|
||||
variant="compact"
|
||||
layout="wrap"
|
||||
className={styles.tabs}
|
||||
items={FILE_TYPE_TABS.map(({ id, label }) => ({ id, label }))}
|
||||
activeId={active}
|
||||
panelIdPrefix={prefix}
|
||||
onSelect={(id) => select({ id, query })}
|
||||
/>
|
||||
{FILE_TYPE_TABS.map(({ id, sections }) => (
|
||||
<div
|
||||
key={id}
|
||||
role="tabpanel"
|
||||
id={`${prefix}-panel-${id}`}
|
||||
aria-labelledby={`${prefix}-tab-${id}`}
|
||||
hidden={id !== active}
|
||||
>
|
||||
<OptionsPage
|
||||
spec={{
|
||||
...FILE_TYPES,
|
||||
sections: sections.map((section, i) => (i === 0 ? { ...section, title: undefined } : section)),
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export const BUILTIN_PAGES: PageSpec[] = [
|
||||
{
|
||||
id: "keymap",
|
||||
title: "Keymap",
|
||||
order: 10,
|
||||
keywords: ["shortcut", "keyboard", "hotkey", "binding", "preset", "vs code", "intellij"],
|
||||
component: KeymapPage,
|
||||
dynamicLabels: keymapSearchLabels,
|
||||
},
|
||||
FILE_TYPES,
|
||||
];
|
||||
@@ -5,8 +5,20 @@ import { SCHEME_SUBPAGES, languagePageId } from "./colorSchemeMeta";
|
||||
* italic / effects editor, and a live preview. Edits are staged in
|
||||
* `editor.colorOverrides[scheme][attribute]`; `editor/core` injects them.
|
||||
*/
|
||||
import { useEffect, useMemo, useRef, useState, type CSSProperties } from "react";
|
||||
import { Button, Checkbox, Icon, Input, Tree, type SelectOption, type TreeHandle, T } from "@/ui";
|
||||
import { useEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from "react";
|
||||
import {
|
||||
Button,
|
||||
Checkbox,
|
||||
Icon,
|
||||
Input,
|
||||
SplitGroup,
|
||||
SplitHandle,
|
||||
SplitPanel,
|
||||
Tree,
|
||||
type SelectOption,
|
||||
type TreeHandle,
|
||||
T,
|
||||
} from "@/ui";
|
||||
import { fontWeightVars, type CustomColorSchemes, type TextAttributesOverride } from "@/platform/editorSettings";
|
||||
import {
|
||||
ATTRIBUTES,
|
||||
@@ -1368,7 +1380,15 @@ function GitPreview({
|
||||
);
|
||||
}
|
||||
|
||||
export function ColorSchemePage({ scopes, landing }: { scopes: readonly string[]; landing?: boolean }) {
|
||||
export function ColorSchemePage({
|
||||
scopes,
|
||||
landing,
|
||||
children,
|
||||
}: {
|
||||
scopes: readonly string[];
|
||||
landing?: boolean;
|
||||
children?: ReactNode;
|
||||
}) {
|
||||
const translate = useTx();
|
||||
const [scheme, setScheme] = useSetting<string>("editor.colorScheme", "global");
|
||||
const [overrides, setOverrides] = useSetting<Overrides>("editor.colorOverrides", "global");
|
||||
@@ -1580,7 +1600,7 @@ export function ColorSchemePage({ scopes, landing }: { scopes: readonly string[]
|
||||
[],
|
||||
);
|
||||
return (
|
||||
<div className={styles.page}>
|
||||
<div className={landing ? styles.page : styles.schemePage}>
|
||||
<div className={styles.schemeRow}>
|
||||
<Row label="Scheme">
|
||||
<Select value={scheme} options={options} onChange={setScheme} aria-label="Scheme" />
|
||||
@@ -1631,84 +1651,88 @@ export function ColorSchemePage({ scopes, landing }: { scopes: readonly string[]
|
||||
))}
|
||||
</nav>
|
||||
) : (
|
||||
<>
|
||||
<div className={styles.schemeBody} style={baseVars}>
|
||||
<div className={styles.attrTree}>
|
||||
<Tree<Node>
|
||||
aria-label="Color scheme attributes"
|
||||
roots={roots}
|
||||
getKey={(n) => n.key}
|
||||
getLabel={(n) => translate(n.label)}
|
||||
getChildren={(n) => n.children}
|
||||
isExpandable={(n) => !!n.children?.length}
|
||||
expanded={expanded}
|
||||
onExpandedChange={setExpanded}
|
||||
handleRef={treeRef}
|
||||
multiSelect={false}
|
||||
selected={new Set([selected])}
|
||||
onSelectionChange={(_s, lead) => lead?.attr && setSelected(lead.attr.id)}
|
||||
renderNode={(n) => (
|
||||
<span
|
||||
className={`${styles.treeLabel} ${(n.attr ? mine?.[n.attr.id] : modifiedKeys.has(n.key)) ? styles.attrModified : ""}`}
|
||||
>
|
||||
{translate(n.label)}
|
||||
</span>
|
||||
)}
|
||||
speedSearch
|
||||
/>
|
||||
</div>
|
||||
{attr ? (
|
||||
<div className={styles.attrPanel}>
|
||||
<AttributeEditor
|
||||
key={`${id}/${attr.id}`}
|
||||
attr={attr}
|
||||
inherited={inherited}
|
||||
value={mine?.[attr.id]}
|
||||
onChange={(v) => update(attr.id, v)}
|
||||
<SplitGroup orientation="vertical" className={styles.schemeSplit}>
|
||||
<SplitPanel defaultSize="62%" minSize="154px">
|
||||
<div className={styles.schemeBody} style={baseVars}>
|
||||
<div className={styles.attrTree}>
|
||||
<Tree<Node>
|
||||
aria-label="Color scheme attributes"
|
||||
roots={roots}
|
||||
getKey={(n) => n.key}
|
||||
getLabel={(n) => translate(n.label)}
|
||||
getChildren={(n) => n.children}
|
||||
isExpandable={(n) => !!n.children?.length}
|
||||
expanded={expanded}
|
||||
onExpandedChange={setExpanded}
|
||||
handleRef={treeRef}
|
||||
multiSelect={false}
|
||||
selected={new Set([selected])}
|
||||
onSelectionChange={(_s, lead) => lead?.attr && setSelected(lead.attr.id)}
|
||||
renderNode={(n) => (
|
||||
<span
|
||||
className={`${styles.treeLabel} ${(n.attr ? mine?.[n.attr.id] : modifiedKeys.has(n.key)) ? styles.attrModified : ""}`}
|
||||
>
|
||||
{translate(n.label)}
|
||||
</span>
|
||||
)}
|
||||
speedSearch
|
||||
/>
|
||||
</div>
|
||||
<section className={styles.attrPanel} aria-label={tx("Color scheme options")}>
|
||||
{attr && (
|
||||
<AttributeEditor
|
||||
key={`${id}/${attr.id}`}
|
||||
attr={attr}
|
||||
inherited={inherited}
|
||||
value={mine?.[attr.id]}
|
||||
onChange={(v) => update(attr.id, v)}
|
||||
/>
|
||||
)}
|
||||
{children && <div className={styles.schemeExtraOptions}>{children}</div>}
|
||||
</section>
|
||||
</div>
|
||||
</SplitPanel>
|
||||
<SplitHandle aria-label={tx("Resize color scheme preview")} />
|
||||
<SplitPanel defaultSize="38%" minSize="88px">
|
||||
{scopes[0] === "Git" ? (
|
||||
<GitPreview vars={vars} ids={ids} reveal={reveal} />
|
||||
) : (
|
||||
<div />
|
||||
)}
|
||||
</div>
|
||||
{scopes[0] === "Git" ? (
|
||||
<GitPreview vars={vars} ids={ids} reveal={reveal} />
|
||||
) : (
|
||||
<pre className={styles.schemePreview} style={vars} aria-label={tx("Color scheme preview")}>
|
||||
{sample.code.map((line, i) => (
|
||||
<div key={i} className={`${styles.previewLine} ${i === sample.caret ? styles.previewCaretLine : ""}`}>
|
||||
<span className={styles.previewGutter}>{i + 1}</span>
|
||||
<code>
|
||||
{line.map(([text, attrId], j) => {
|
||||
const attr = attrId !== undefined ? A(attrId) : undefined;
|
||||
const inPage = attr !== undefined && ids.has(attrId!);
|
||||
return (
|
||||
<span
|
||||
key={j}
|
||||
style={tokenStyle(attr)}
|
||||
className={attr ? styles.clickable : undefined}
|
||||
onClick={
|
||||
attr
|
||||
? () => {
|
||||
if (inPage) reveal(attrId!);
|
||||
else {
|
||||
crossPageReveal = attrId!;
|
||||
selectPage(attrPageId(attr));
|
||||
<pre className={styles.schemePreview} style={vars} aria-label={tx("Color scheme preview")}>
|
||||
{sample.code.map((line, i) => (
|
||||
<div key={i} className={`${styles.previewLine} ${i === sample.caret ? styles.previewCaretLine : ""}`}>
|
||||
<span className={styles.previewGutter}>{i + 1}</span>
|
||||
<code>
|
||||
{line.map(([text, attrId], j) => {
|
||||
const attr = attrId !== undefined ? A(attrId) : undefined;
|
||||
const inPage = attr !== undefined && ids.has(attrId!);
|
||||
return (
|
||||
<span
|
||||
key={j}
|
||||
style={tokenStyle(attr)}
|
||||
className={attr ? styles.clickable : undefined}
|
||||
onClick={
|
||||
attr
|
||||
? () => {
|
||||
if (inPage) reveal(attrId!);
|
||||
else {
|
||||
crossPageReveal = attrId!;
|
||||
selectPage(attrPageId(attr));
|
||||
}
|
||||
}
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
{text}
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</code>
|
||||
</div>
|
||||
))}
|
||||
</pre>
|
||||
)}
|
||||
</>
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
{text}
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</code>
|
||||
</div>
|
||||
))}
|
||||
</pre>
|
||||
)}
|
||||
</SplitPanel>
|
||||
</SplitGroup>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -223,13 +223,38 @@
|
||||
}
|
||||
.schemeBody {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(180px, 1fr) minmax(220px, 260px);
|
||||
gap: 14px;
|
||||
min-height: 320px;
|
||||
grid-template-columns: minmax(0, 1fr) minmax(0, 280px);
|
||||
gap: var(--space-2);
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
padding-bottom: var(--space-2);
|
||||
}
|
||||
.schemePage {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
min-height: 340px;
|
||||
min-width: 0;
|
||||
}
|
||||
.schemeSplit {
|
||||
flex: 1;
|
||||
}
|
||||
.schemePage > :not(.schemeSplit) {
|
||||
flex: none;
|
||||
}
|
||||
.schemeExtraOptions {
|
||||
margin-top: var(--space-4);
|
||||
}
|
||||
@container settings-content (max-width: 610px) {
|
||||
.schemeBody {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
grid-template-rows: minmax(72px, 2fr) minmax(0, 3fr);
|
||||
}
|
||||
}
|
||||
.attrTree {
|
||||
max-height: 360px;
|
||||
overflow: auto;
|
||||
min-height: 0;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
border-radius: var(--radius-small);
|
||||
box-shadow: inset 0 0 0 1px var(--border-strong);
|
||||
padding: 2px 0;
|
||||
@@ -247,9 +272,9 @@
|
||||
box-shadow: inset 0 0 0 1px var(--border-strong);
|
||||
border-radius: var(--radius-small);
|
||||
padding: 10px;
|
||||
align-self: start;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
overflow: auto;
|
||||
max-height: 360px;
|
||||
}
|
||||
.attrEditor {
|
||||
display: flex;
|
||||
@@ -259,6 +284,7 @@
|
||||
.attrRow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-2);
|
||||
min-height: 28px;
|
||||
}
|
||||
@@ -274,7 +300,7 @@
|
||||
}
|
||||
.swatchInput {
|
||||
flex: 1 1 90px;
|
||||
min-width: 90px;
|
||||
min-width: min(90px, 100%);
|
||||
}
|
||||
.colorBox {
|
||||
position: relative;
|
||||
@@ -298,7 +324,9 @@
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
.schemePreview {
|
||||
margin: 14px 0 0;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
margin: var(--space-2) 0 0;
|
||||
padding: 8px 0;
|
||||
border-radius: var(--radius-small);
|
||||
box-shadow: inset 0 0 0 1px var(--border-strong);
|
||||
@@ -309,7 +337,6 @@
|
||||
font-size: var(--fs-code);
|
||||
line-height: var(--lh-code);
|
||||
overflow: auto;
|
||||
max-height: 260px;
|
||||
}
|
||||
.previewLine {
|
||||
display: flex;
|
||||
@@ -338,12 +365,13 @@
|
||||
/* Git preview mirrors the two real surfaces: the editor inline blame widget and
|
||||
the project tree root branch suffix. Only the Git page uses these. */
|
||||
.gitPreview {
|
||||
margin: 14px 0 0;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
margin: var(--space-2) 0 0;
|
||||
border-radius: var(--radius-small);
|
||||
box-shadow: inset 0 0 0 1px var(--border-strong);
|
||||
background: var(--bg-editor, var(--bg-island));
|
||||
overflow: auto;
|
||||
max-height: 260px;
|
||||
}
|
||||
.gitSection {
|
||||
padding: 8px 0;
|
||||
|
||||
@@ -2,24 +2,34 @@ import { ATTRIBUTES, SCHEMES } from "@/platform/colorScheme";
|
||||
import { lazyPage } from "../lazyPage";
|
||||
import type { PageSpec } from "../spec";
|
||||
import { LANGUAGES, SCHEME_SUBPAGES, languagePageId } from "./colorSchemeMeta";
|
||||
import { editorPage } from "./kit";
|
||||
import { editorPage, EditorSections, sectionLabels, type EditorSection } from "./kit";
|
||||
|
||||
const ALL_COLOR_SCHEME_PAGE_IDS = ["editor.colorScheme", ...SCHEME_SUBPAGES.map((p) => p.id)];
|
||||
const LazyColorSchemePage = lazyPage(ALL_COLOR_SCHEME_PAGE_IDS, () =>
|
||||
import("./ColorSchemeBody").then((m) => m.ColorSchemePage),
|
||||
);
|
||||
|
||||
/** The scope chooser, import/export buttons and preview are identical on every sub-page. */
|
||||
function colorSchemeSection(scopes: readonly string[]) {
|
||||
function colorSchemePage(
|
||||
spec: Pick<PageSpec, "id" | "title" | "order" | "keywords">,
|
||||
scope: string,
|
||||
extraSections: EditorSection[] = [],
|
||||
): PageSpec {
|
||||
const scopes = [scope];
|
||||
const labels = [
|
||||
"Scheme",
|
||||
...ATTRIBUTES.filter((a) => a.path[0] === scope).map((a) => a.name),
|
||||
...sectionLabels(extraSections),
|
||||
];
|
||||
return {
|
||||
items: [
|
||||
{
|
||||
t: "custom" as const,
|
||||
label: "Scheme",
|
||||
keywords: ATTRIBUTES.filter((a) => scopes.includes(a.path[0]!)).map((a) => a.name),
|
||||
component: () => <LazyColorSchemePage scopes={scopes} />,
|
||||
},
|
||||
],
|
||||
...spec,
|
||||
group: "Editor",
|
||||
projectScope: false,
|
||||
dynamicLabels: () => labels,
|
||||
component: () => (
|
||||
<LazyColorSchemePage scopes={scopes}>
|
||||
{extraSections.length > 0 && <EditorSections sections={extraSections} />}
|
||||
</LazyColorSchemePage>
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -55,22 +65,23 @@ const COLOR_SCHEME_PAGE = editorPage({
|
||||
/** JetBrains layout: scopes and languages live in the settings tree under Color Scheme, one page each. */
|
||||
export const COLOR_SCHEME_PAGES: PageSpec[] = [
|
||||
COLOR_SCHEME_PAGE,
|
||||
editorPage({
|
||||
id: "editor.colorScheme.general",
|
||||
title: "General",
|
||||
order: 1,
|
||||
projectScope: false,
|
||||
keywords: ATTRIBUTES.filter((a) => a.path[0] === "General").map((a) => a.name),
|
||||
sections: [colorSchemeSection(["General"])],
|
||||
}),
|
||||
editorPage({
|
||||
id: "editor.colorScheme.language-defaults",
|
||||
title: "Language Defaults",
|
||||
order: 2,
|
||||
projectScope: false,
|
||||
keywords: ["semantic highlighting", "rainbow"],
|
||||
sections: [
|
||||
colorSchemeSection(["Language Defaults"]),
|
||||
colorSchemePage(
|
||||
{
|
||||
id: "editor.colorScheme.general",
|
||||
title: "General",
|
||||
order: 1,
|
||||
},
|
||||
"General",
|
||||
),
|
||||
colorSchemePage(
|
||||
{
|
||||
id: "editor.colorScheme.language-defaults",
|
||||
title: "Language Defaults",
|
||||
order: 2,
|
||||
keywords: ["semantic highlighting", "rainbow"],
|
||||
},
|
||||
"Language Defaults",
|
||||
[
|
||||
{
|
||||
title: "Language Defaults",
|
||||
items: [
|
||||
@@ -101,39 +112,42 @@ export const COLOR_SCHEME_PAGES: PageSpec[] = [
|
||||
],
|
||||
},
|
||||
],
|
||||
}),
|
||||
editorPage({
|
||||
id: "editor.colorScheme.debugger",
|
||||
title: "Debugger",
|
||||
order: 3,
|
||||
projectScope: false,
|
||||
keywords: ["breakpoint", "inline values"],
|
||||
sections: [colorSchemeSection(["Debugger"])],
|
||||
}),
|
||||
editorPage({
|
||||
id: "editor.colorScheme.console-colors",
|
||||
title: "Console Colors",
|
||||
order: 4,
|
||||
projectScope: false,
|
||||
keywords: ["terminal", "ansi", "console", "background"],
|
||||
sections: [colorSchemeSection(["Console Colors"])],
|
||||
}),
|
||||
editorPage({
|
||||
id: "editor.colorScheme.git",
|
||||
title: "Git",
|
||||
order: 5,
|
||||
projectScope: false,
|
||||
keywords: ["git", "blame", "branch", "inline blame", "project view", "decoration"],
|
||||
sections: [colorSchemeSection(["Git"])],
|
||||
}),
|
||||
),
|
||||
colorSchemePage(
|
||||
{
|
||||
id: "editor.colorScheme.debugger",
|
||||
title: "Debugger",
|
||||
order: 3,
|
||||
keywords: ["breakpoint", "inline values"],
|
||||
},
|
||||
"Debugger",
|
||||
),
|
||||
colorSchemePage(
|
||||
{
|
||||
id: "editor.colorScheme.console-colors",
|
||||
title: "Console Colors",
|
||||
order: 4,
|
||||
keywords: ["terminal", "ansi", "console", "background"],
|
||||
},
|
||||
"Console Colors",
|
||||
),
|
||||
colorSchemePage(
|
||||
{
|
||||
id: "editor.colorScheme.git",
|
||||
title: "Git",
|
||||
order: 5,
|
||||
keywords: ["git", "blame", "branch", "inline blame", "project view", "decoration"],
|
||||
},
|
||||
"Git",
|
||||
),
|
||||
...LANGUAGES.map((language, i) =>
|
||||
editorPage({
|
||||
id: languagePageId(language),
|
||||
title: language,
|
||||
order: 6 + i,
|
||||
projectScope: false,
|
||||
keywords: ATTRIBUTES.filter((a) => a.path[0] === language).map((a) => a.name),
|
||||
sections: [colorSchemeSection([language])],
|
||||
}),
|
||||
colorSchemePage(
|
||||
{
|
||||
id: languagePageId(language),
|
||||
title: language,
|
||||
order: 6 + i,
|
||||
},
|
||||
language,
|
||||
),
|
||||
),
|
||||
];
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { EditorSelection, EditorState } from "@codemirror/state";
|
||||
import type { LineHunk } from "@/bindings";
|
||||
import { applyRollback, hunkAtLine, hunkKeys, hunksOverlapping, nextHunk, prevHunk, rollbackEdit } from "../hunks";
|
||||
@@ -132,6 +132,38 @@ describe("change lane clicks", () => {
|
||||
setHunkPopupHooks(null);
|
||||
parent.remove();
|
||||
});
|
||||
|
||||
it("opens a deletion from the hit area above its line", async () => {
|
||||
const { EditorView } = await import("@codemirror/view");
|
||||
const { changeLane } = await import("@/editor/core/cm/lanes");
|
||||
const { changeMarkers, setHunkPopupHooks } = await import("../gutter");
|
||||
const opened: string[] = [];
|
||||
setHunkPopupHooks({ open: (_v, hunk) => opened.push(hunk.kind), docChanged: () => {} });
|
||||
const parent = document.createElement("div");
|
||||
document.body.appendChild(parent);
|
||||
const view = new EditorView({
|
||||
parent,
|
||||
state: EditorState.create({
|
||||
doc: "a\nc\n",
|
||||
extensions: [changeLane, changeMarkers({ path: "/p/f.txt" } as Parameters<typeof changeMarkers>[0])],
|
||||
}),
|
||||
});
|
||||
view.dispatch({ effects: setHunksEffect.of([h("deleted", 1, 0, 1, 1, "b\n")]) });
|
||||
const lane = view.dom.querySelector<HTMLElement>(".cm-openidea-lane")!;
|
||||
vi.spyOn(lane, "getBoundingClientRect").mockReturnValue({ left: 100, right: 104, top: 0, bottom: 100 } as DOMRect);
|
||||
const marker = view.dom.querySelector<HTMLElement>(".cm-openidea-laneDeleted")!;
|
||||
vi.spyOn(marker, "getBoundingClientRect").mockReturnValue({ left: 96, top: 14, width: 12, height: 12 } as DOMRect);
|
||||
const previous = view.lineBlockAt(view.state.doc.line(1).from);
|
||||
const deleted = view.lineBlockAt(view.state.doc.line(2).from);
|
||||
vi.spyOn(view, "lineBlockAtHeight").mockImplementation((height) => (height < 20 ? previous : deleted));
|
||||
marker.dispatchEvent(
|
||||
new MouseEvent("mousedown", { bubbles: true, cancelable: true, button: 0, clientX: 96, clientY: 17 }),
|
||||
);
|
||||
expect(opened).toEqual(["deleted"]);
|
||||
view.destroy();
|
||||
setHunkPopupHooks(null);
|
||||
parent.remove();
|
||||
});
|
||||
});
|
||||
|
||||
describe("change markers in folds", () => {
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
import { useEffect, useId, useState } from "react";
|
||||
import type { FileStatus, Stash } from "@/bindings";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { Checkbox, Dialog, Icon, IconButton, Input, T, fileIconName } from "@/ui";
|
||||
import { Checkbox, Dialog, IconButton, Input, T } from "@/ui";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
import { addedThenDeleted, groupOf, remainingOverrides, renamedFromPath } from "./changes";
|
||||
import { runCommitChecks } from "./commitChecks";
|
||||
@@ -12,10 +12,11 @@ import { workflowSettings } from "@/platform/workflowSettings";
|
||||
import { notifyFileOperation } from "@/platform/fileOps";
|
||||
import { confirmDialog, openDialog } from "./dialogs";
|
||||
import { RepoPicker, useBranchInfo } from "./gitMenuDialogs";
|
||||
import { KIND_COLOR, baseName, dirName, effectiveKind, relTo, stripSlash } from "./model";
|
||||
import { baseName, effectiveKind, stripSlash } from "./model";
|
||||
import { logConsole, runOp, saveAll } from "./ops";
|
||||
import { ensureCommitIdentity } from "./commitIdentity";
|
||||
import { showCompareRevisions } from "./operations";
|
||||
import { FileChecklist } from "./shelf";
|
||||
import { currentRepo, loadStashes, refreshNow, useVcs } from "./store";
|
||||
import styles from "./common.module.css";
|
||||
import { tx } from "@/platform/i18n";
|
||||
@@ -216,7 +217,6 @@ export function showRollbackDialog(files: FileStatus[]) {
|
||||
}
|
||||
|
||||
function RollbackDialog({ files, onClose }: { files: FileStatus[]; onClose: () => void }) {
|
||||
const root = useVcs((s) => s.root) ?? "";
|
||||
const [selected, setSelected] = useState(() => new Set(files.map((f) => f.path)));
|
||||
const [deleteAdded, setDeleteAdded] = useState(false);
|
||||
const hasAdded = files.some((f) => f.staged === "added");
|
||||
@@ -256,32 +256,7 @@ function RollbackDialog({ files, onClose }: { files: FileStatus[]; onClose: () =
|
||||
? tx`${selected.size} of ${files.length} file will be reverted to their last committed state. Uncommitted changes are lost.`
|
||||
: tx`${selected.size} of ${files.length} files will be reverted to their last committed state. Uncommitted changes are lost.`}
|
||||
</div>
|
||||
<div className={styles.fileList} role="group" aria-label={tx("Files to roll back")}>
|
||||
{files.map((f) => {
|
||||
const kind = effectiveKind(f) ?? "modified";
|
||||
return (
|
||||
<div key={f.path} className={styles.fileRow}>
|
||||
<Checkbox
|
||||
aria-label={tx`Include ${baseName(f.path)}`}
|
||||
checked={selected.has(f.path)}
|
||||
onChange={(v) =>
|
||||
setSelected((s) => {
|
||||
const n = new Set(s);
|
||||
if (v) n.add(f.path);
|
||||
else n.delete(f.path);
|
||||
return n;
|
||||
})
|
||||
}
|
||||
/>
|
||||
<Icon name={fileIconName(baseName(f.path), f.path)} size={14} />
|
||||
<span className={styles.fileName} style={{ color: KIND_COLOR[kind] }}>
|
||||
{baseName(f.path)}
|
||||
</span>
|
||||
<span className={styles.fileDir}>{dirName(relTo(root, stripSlash(f.path)))}</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<FileChecklist files={files} selected={selected} onChange={setSelected} label="Files to roll back" />
|
||||
<div style={{ height: 12 }} />
|
||||
</Dialog>
|
||||
);
|
||||
|
||||
@@ -235,14 +235,19 @@ const laneTheme = EditorView.baseTheme({
|
||||
*/
|
||||
export function laneMouseDown(view: EditorView, event: MouseEvent, path: string): boolean {
|
||||
if (event.button !== 0 || event.shiftKey || event.metaKey || event.ctrlKey || event.altKey) return false;
|
||||
const deletedMarker = event.target instanceof Element ? event.target.closest(".cm-openidea-laneDeleted") : null;
|
||||
const lane = view.dom.querySelector(".cm-openidea-lane");
|
||||
if (!lane) return false;
|
||||
const rect = lane.getBoundingClientRect();
|
||||
if (event.clientX < rect.left - 1 || event.clientX > rect.right + 3) return false;
|
||||
if (event.clientY < rect.top || event.clientY > rect.bottom) return false;
|
||||
const block = view.lineBlockAtHeight(event.clientY - view.documentTop);
|
||||
if (!deletedMarker) {
|
||||
const rect = lane.getBoundingClientRect();
|
||||
if (event.clientX < rect.left - 1 || event.clientX > rect.right + 3) return false;
|
||||
if (event.clientY < rect.top || event.clientY > rect.bottom) return false;
|
||||
}
|
||||
const markerRect = deletedMarker?.getBoundingClientRect();
|
||||
const y = markerRect ? markerRect.top + markerRect.height / 2 + 1 : event.clientY;
|
||||
const block = view.lineBlockAtHeight(y - view.documentTop);
|
||||
const hunk = hunkAtPos(view.state, block.from);
|
||||
if (!hunk) return false;
|
||||
if (!hunk || (deletedMarker && hunk.kind !== "deleted")) return false;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
showHunkPopup(view, hunk, path);
|
||||
|
||||
@@ -332,7 +332,7 @@ describe("markdown preview re-rendering", () => {
|
||||
same(render, doc(blocks));
|
||||
});
|
||||
|
||||
it("renders a large document as a whole, sanitizing only what an edit changed", () => {
|
||||
it("renders a large document as a whole, sanitizing only what an edit changed", { timeout: 20_000 }, () => {
|
||||
const asWritten = readFileSync(resolve(import.meta.dirname, "../../../../plugins/README.md"), "utf8");
|
||||
// As written, a bare `<title>` swallows the rest of the file, so it is rendered as a whole.
|
||||
for (const [readme, reuses] of [
|
||||
|
||||
@@ -3,12 +3,16 @@
|
||||
"Resize inspection panes": "Resize inspection panes",
|
||||
"Resize branch comparison panes": "Resize branch comparison panes",
|
||||
"Resize inspection description": "Resize inspection description",
|
||||
"Color scheme options": "Color scheme options",
|
||||
"Resize color scheme preview": "Resize color scheme preview",
|
||||
"Font options": "Font options",
|
||||
"Resize font preview": "Resize font preview",
|
||||
"Table actions": "Table actions",
|
||||
"Table pages": "Table pages",
|
||||
"Resize file type panes": "Resize file type panes",
|
||||
"Problems actions": "Problems actions",
|
||||
"TODO actions": "TODO actions",
|
||||
"Resize paste preview": "Resize paste preview",
|
||||
"Same as the existing configuration '{existing}'": "Same as the existing configuration '{existing}'",
|
||||
"Windows file and folder names cannot end with a period or space": "Windows file and folder names cannot end with a period or space",
|
||||
"Use URL template": "Use URL template",
|
||||
@@ -2710,5 +2714,8 @@
|
||||
"Shelve Silently": "Shelve Silently",
|
||||
"Unshelve Silently": "Unshelve Silently",
|
||||
"Fold Lines Like This": "Fold Lines Like This",
|
||||
"Remove All Watches": "Remove All Watches"
|
||||
"Remove All Watches": "Remove All Watches",
|
||||
"GitHub account": "GitHub account",
|
||||
"Leave empty to use the active GitHub CLI account. OpenIDEA resolves the token at launch and never stores it.": "Leave empty to use the active GitHub CLI account. OpenIDEA resolves the token at launch and never stores it.",
|
||||
"github-username": "github-username"
|
||||
}
|
||||
@@ -3,10 +3,13 @@
|
||||
"Resize inspection panes": "调整检查窗格大小",
|
||||
"Resize branch comparison panes": "调整分支比较窗格大小",
|
||||
"Resize inspection description": "调整检查说明窗格大小",
|
||||
"Color scheme options": "配色方案选项",
|
||||
"Resize color scheme preview": "调整配色方案预览大小",
|
||||
"Font options": "字体选项",
|
||||
"Resize font preview": "调整字体预览大小",
|
||||
"Table actions": "表数据操作",
|
||||
"Table pages": "表数据分页",
|
||||
"Resize file type panes": "调整文件类型窗格大小",
|
||||
"Problems actions": "问题操作",
|
||||
"Windows file and folder names cannot end with a period or space": "Windows 文件和文件夹名称不能以句点或空格结尾",
|
||||
"Use URL template": "使用 URL 模板",
|
||||
@@ -2960,6 +2963,7 @@
|
||||
"Tests failed: {detail}": "测试失败:{detail}",
|
||||
"TODO comment": "TODO 注释",
|
||||
"TODO actions": "TODO 操作",
|
||||
"Resize paste preview": "调整粘贴预览大小",
|
||||
"TODO filters": "TODO 筛选器",
|
||||
"TODO items": "TODO 项",
|
||||
"TODO items unavailable": "TODO 项不可用",
|
||||
@@ -9076,5 +9080,8 @@
|
||||
"Database and schema": "数据库和 schema",
|
||||
"Shelve Silently": "静默搁置",
|
||||
"Unshelve Silently": "静默取消搁置",
|
||||
"Remove All Watches": "移除所有监视"
|
||||
"Remove All Watches": "移除所有监视",
|
||||
"GitHub account": "GitHub 账号",
|
||||
"Leave empty to use the active GitHub CLI account. OpenIDEA resolves the token at launch and never stores it.": "留空则使用 GitHub CLI 当前登录的账号。OpenIDEA 在启动时获取令牌,不会保存它。",
|
||||
"github-username": "GitHub 用户名"
|
||||
}
|
||||
Reference in new issue
Заблокувати користувача