diff --git a/crates/ide-agent/src/acp/discover.rs b/crates/ide-agent/src/acp/discover.rs index 7335b8679d..0926e31c04 100644 --- a/crates/ide-agent/src/acp/discover.rs +++ b/crates/ide-agent/src/acp/discover.rs @@ -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()); diff --git a/crates/ide-agent/src/lib.rs b/crates/ide-agent/src/lib.rs index 06e0a92e6c..79d081f691 100644 --- a/crates/ide-agent/src/lib.rs +++ b/crates/ide-agent/src/lib.rs @@ -132,6 +132,7 @@ pub type McpExecutableFn = dyn Fn() -> Option + Send + Sync; #[derive(Clone, Debug, PartialEq, Eq, Hash)] struct CopilotBinaryKey { command: String, + github_account: Option, modified: Option, len: Option, } @@ -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 { 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) { diff --git a/crates/ide-agent/src/native/copilot/mod.rs b/crates/ide-agent/src/native/copilot/mod.rs index 1421972b35..bdea39d8d1 100644 --- a/crates/ide-agent/src/native/copilot/mod.rs +++ b/crates/ide-agent/src/native/copilot/mod.rs @@ -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( diff --git a/crates/ide-agent/src/native/copilot/models.rs b/crates/ide-agent/src/native/copilot/models.rs index 95154a2adf..d6d0ace9f1 100644 --- a/crates/ide-agent/src/native/copilot/models.rs +++ b/crates/ide-agent/src/native/copilot/models.rs @@ -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 { 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) -> Vec 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) -> Option { let id = str_of(m, "id")?.to_owned(); if m.get("model_picker_enabled").and_then(Value::as_bool) == Some(false) diff --git a/crates/ide-agent/src/native/copilot/tests.rs b/crates/ide-agent/src/native/copilot/tests.rs index a4de2ca99e..bc50f0ff7c 100644 --- a/crates/ide-agent/src/native/copilot/tests.rs +++ b/crates/ide-agent/src/native/copilot/tests.rs @@ -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::>(), ["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::>(), ["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())); diff --git a/crates/ide-agent/src/provider.rs b/crates/ide-agent/src/provider.rs index 8db7094993..a8f4370d49 100644 --- a/crates/ide-agent/src/provider.rs +++ b/crates/ide-agent/src/provider.rs @@ -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 { + 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 { + 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 { + 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, ) -> 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(); diff --git a/crates/ide-agent/src/registry.rs b/crates/ide-agent/src/registry.rs index ed81488518..212ebc8fc6 100644 --- a/crates/ide-agent/src/registry.rs +++ b/crates/ide-agent/src/registry.rs @@ -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, diff --git a/crates/ide-agent/src/tests.rs b/crates/ide-agent/src/tests.rs index 7308f39f17..95d65b4359 100644 --- a/crates/ide-agent/src/tests.rs +++ b/crates/ide-agent/src/tests.rs @@ -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(); diff --git a/docs/en/guide/debugging.mdx b/docs/en/guide/debugging.mdx index 1bb96f1fd8..371c73fdbf 100644 --- a/docs/en/guide/debugging.mdx +++ b/docs/en/guide/debugging.mdx @@ -123,7 +123,7 @@ These commands are in the **Run** menu and on the Debug tool window toolbar. While the program is suspended: - The **Variables** view shows the variables of the selected frame. Right-click a value for **Set Value…** (`F2`), **Copy Value**, **Copy Name**, **Jump to Source** (`F4`) and **Add to Watches**. -- **Watches** appear at the top of the Variables view and are re-evaluated on every stop and frame change. Add one with **Add to Watches**; remove it with **Remove Watch**. +- **Watches** appear at the top of the Variables view and are re-evaluated on every stop and frame change. Add one with **Add to Watches**; remove it with **Remove Watch**, or all of them with **Remove All Watches**. - Hovering a variable in the editor shows its value. `⌥`-click (`Alt`-click) or **Quick Evaluate Expression** (`⌘⌥F8` / `Ctrl+Alt+F8`) evaluates the expression under the mouse or the selection. - Values of local variables are shown inline after the lines that use them. - **Evaluate Expression…** (`⌥F8` / `Alt+F8`) opens a dialog that evaluates any expression in the selected frame, keeps a history, and can add the expression to watches. diff --git a/docs/en/guide/run.mdx b/docs/en/guide/run.mdx index 4633737789..f214cb3893 100644 --- a/docs/en/guide/run.mdx +++ b/docs/en/guide/run.mdx @@ -160,7 +160,7 @@ A **Compound** configuration starts several configurations at once. Run it to st Each launch opens a tab in the **Run** tool window (bottom). The toolbar has **Rerun**, **Debug**, **Rerun Failed Tests** (for test runs), **Update Application**, **Find…**, **Scroll to End**, **Soft-Wrap**, **Clear All** and **Edit Configurations…**. - File paths and stack trace frames in the output are links. -- Repeated lines can be folded; configure the patterns in **Settings › Build, Execution, Deployment › Console**, along with the buffer size and the console encoding. +- Repeated lines can be folded; configure the patterns in **Settings › Build, Execution, Deployment › Console**, along with the buffer size and the console encoding. **Fold Lines Like This** in the console's context menu opens that page with the selected text (or the clicked line) added as a pattern. - Log lines can take the colour of their level (`ERROR`, `WARN`, `INFO`, `DEBUG`, `TRACE`); colours the program prints itself are kept. Turn it on and pick the colours in **Settings › Build, Execution, Deployment › Console**. - For test runs the tab shows a test tree next to the output. See [Testing](/en/guide/testing). diff --git a/docs/zh/guide/debugging.mdx b/docs/zh/guide/debugging.mdx index bc1566e2fb..cdae5193b5 100644 --- a/docs/zh/guide/debugging.mdx +++ b/docs/zh/guide/debugging.mdx @@ -125,7 +125,7 @@ C 和 C++ 的配置也可以改用 GDB 14 及以上版本(`gdb -i dap`): 程序挂起时: - **变量** 视图显示选中帧的变量。右键点击某个值,可以 **设置值…**(`F2`)、**复制值**、**复制名称**、**跳转到源代码**(`F4`)和 **添加到监视**。 -- 监视表达式显示在变量视图顶部,每次停下或切换帧时重新计算。用 **添加到监视** 添加,用 **移除监视** 删除。 +- 监视表达式显示在变量视图顶部,每次停下或切换帧时重新计算。用 **添加到监视** 添加,用 **移除监视** 删除,用 **移除所有监视** 一次全部删除。 - 在编辑器里悬停变量会显示它的值。`⌥` 点击(`Alt` 点击)或 **快速计算表达式**(`⌘⌥F8` / `Ctrl+Alt+F8`)计算鼠标下的表达式或选中的内容。 - 局部变量的值会内联显示在使用它们的行尾。 - **计算表达式…**(`⌥F8` / `Alt+F8`)打开对话框,在选中帧里计算任意表达式,带历史记录,也能把表达式加入监视。 diff --git a/docs/zh/guide/run.mdx b/docs/zh/guide/run.mdx index 5f4ede0c66..123742294e 100644 --- a/docs/zh/guide/run.mdx +++ b/docs/zh/guide/run.mdx @@ -156,7 +156,7 @@ Maven 模块在 **自动** 和 **构建(Make)** 时由 jdtls(ECJ)构建 每次启动都会在底部的 **运行** 工具窗口里开一个标签页。工具栏有 **重新运行**、**调试**、**重新运行失败的测试**(测试运行时)、**更新应用**、**查找…**、**滚动到末尾**、**软换行**、**全部清除** 和 **编辑配置…**。 - 输出里的文件路径和堆栈帧都可以点击跳转。 -- 重复的行可以折叠。折叠规则、缓冲区大小和控制台编码在 **设置 › 构建、执行、部署 › 控制台** 中配置。 +- 重复的行可以折叠。折叠规则、缓冲区大小和控制台编码在 **设置 › 构建、执行、部署 › 控制台** 中配置。控制台右键菜单中的 **折叠与此类似的行** 会打开该页面,并把选中的文本(或右键所在的行)添加为折叠规则。 - 日志行可按级别着色(`ERROR`、`WARN`、`INFO`、`DEBUG`、`TRACE`);程序自行输出的颜色保持不变。默认关闭,可在 **设置 › 构建、执行、部署 › 控制台** 开启并修改颜色。 - 测试运行时,标签页会在输出旁显示测试树,参见[测试](/zh/guide/testing)。 diff --git a/e2e/branchCompareLayout.spec.ts b/e2e/branchCompareLayout.spec.ts new file mode 100644 index 0000000000..9137af23ba --- /dev/null +++ b/e2e/branchCompareLayout.spec.ts @@ -0,0 +1,71 @@ +import { expect, ipcCalls, stubDesktop, test } from "./fixtures"; + +test("Branch comparison keeps both commit ranges and the diff action visible", async ({ workbench: page }) => { + const branch = "feature/settlement-reconciliation-and-international-ledger-reporting"; + const current = "feature/review-quarterly-settlement-audit"; + const incomingSubject = "Keep regional settlement references stable during the report export"; + const outgoingSubject = "Preserve the audit trail for settlement retries"; + await page.setViewportSize({ width: 1120, height: 760 }); + await stubDesktop(page); + await page.evaluate( + async ({ branch, current, incomingSubject, outgoingSubject }) => { + const root = "/dev/acme-api"; + const branchInfo = { + head: current, + headCommit: "b".repeat(40), + upstream: null, + ahead: 0, + behind: 0, + operation: null, + }; + const entry = (letter: string, summary: string) => ({ + id: letter.repeat(40), + shortId: letter.repeat(8), + parents: ["a".repeat(40)], + refs: [], + summary, + message: summary + "\n\nUpdate the audit report context.", + author: "Sam Rivera", + email: "sam@example.invalid", + timeMs: 1795100000000, + }); + const h = window.__ipc.handlers; + h.vcs_roots = () => [{ root, ...branchInfo }]; + h.vcs_branch_info = () => branchInfo; + h.vcs_status = () => []; + h.vcs_log = ({ query }) => + (query as { range: string }).range === `HEAD..${branch}` + ? [entry("c", incomingSubject)] + : [entry("b", outgoingSubject)]; + h.window_open_comparison = () => null; + const store = "/src/features/vcs/store.ts"; + const { useVcs } = await import(/* @vite-ignore */ store); + useVcs.setState({ available: true, root, repo: root, roots: [root], branch: branchInfo }); + const path = "/src/features/vcs/CompareBranches.tsx"; + (await import(/* @vite-ignore */ path)).showCompareBranches(branch); + }, + { branch, current, incomingSubject, outgoingSubject }, + ); + const dialog = page.getByRole("dialog", { name: new RegExp(`Compare ${current}`) }); + await expect(dialog.getByRole("listbox")).toHaveCount(2); + const incoming = dialog.getByRole("listbox", { name: `In ${branch}, not in ${current}` }); + const outgoing = dialog.getByRole("listbox", { name: `In ${current}, not in ${branch}` }); + await expect(incoming.getByText(incomingSubject, { exact: true })).toBeVisible(); + await expect(outgoing.getByText(outgoingSubject, { exact: true })).toBeVisible(); + const divider = dialog.getByRole("separator", { name: "Resize branch comparison panes" }); + await expect(divider).toHaveAttribute("aria-orientation", "horizontal"); + const start = (await divider.boundingBox())!.y; + await divider.focus(); + await page.keyboard.press("ArrowDown"); + await expect.poll(async () => (await divider.boundingBox())!.y).toBeGreaterThan(start + 1); + + await page.setViewportSize({ width: 440, height: 660 }); + const heading = dialog.getByRole("heading", { name: new RegExp(`In ${branch}`) }); + await expect.poll(() => heading.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1); + await expect(incoming.getByRole("option")).toBeVisible(); + await expect(outgoing.getByRole("option")).toBeVisible(); + await dialog.getByRole("button", { name: "Show Diff", exact: true }).click(); + await expect + .poll(() => ipcCalls(page, "window_open_comparison")) + .toMatchObject([{ comparison: { from: { rev: branch }, to: { rev: "HEAD" }, repo: "/dev/acme-api" } }]); +}); diff --git a/e2e/colorSchemeLayout.spec.ts b/e2e/colorSchemeLayout.spec.ts new file mode 100644 index 0000000000..4fb8cc1604 --- /dev/null +++ b/e2e/colorSchemeLayout.spec.ts @@ -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); +}); diff --git a/e2e/editorFontLayout.spec.ts b/e2e/editorFontLayout.spec.ts new file mode 100644 index 0000000000..95cb9e44b5 --- /dev/null +++ b/e2e/editorFontLayout.spec.ts @@ -0,0 +1,42 @@ +import { expect, test } from "./fixtures"; + +test("Editor Font keeps the preview in view while editing and resizing the controls", async ({ workbench: page }) => { + await page.setViewportSize({ width: 1200, height: 760 }); + await page.keyboard.press("Meta+,"); + const settings = page.getByRole("dialog", { name: "Settings", exact: true }); + const search = settings.getByRole("textbox", { name: "Search settings" }); + await search.fill("Show only monospaced fonts"); + await settings.getByRole("treeitem", { name: "Font", exact: true, level: 2 }).click(); + await search.clear(); + + const divider = settings.getByRole("separator", { name: "Resize font preview" }); + const options = settings.getByRole("region", { name: "Font options", exact: true }); + const preview = settings.getByRole("textbox", { name: "Font preview", exact: true }); + const font = options.getByRole("combobox", { name: "Font", exact: true }); + await expect(divider).toHaveAttribute("aria-orientation", "vertical"); + expect((await font.boundingBox())!.x).toBeLessThan((await preview.boundingBox())!.x); + await expect.poll(() => preview.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1); + + await preview.fill("function main() { return 42; }"); + await options.getByRole("textbox", { name: "Size", exact: true }).fill("18"); + await options.getByRole("textbox", { name: "Line height", exact: true }).fill("25"); + await expect(preview).toHaveCSS("font-size", "18px"); + await expect(preview).toHaveCSS("line-height", "25px"); + + await page.setViewportSize({ width: 520, height: 620 }); + await expect(divider).toHaveAttribute("aria-orientation", "horizontal"); + expect((await font.boundingBox())!.y).toBeLessThan((await preview.boundingBox())!.y); + await expect(preview).toHaveValue("function main() { return 42; }"); + const y = (await divider.boundingBox())!.y; + await divider.press("ArrowDown"); + await expect.poll(async () => (await divider.boundingBox())!.y).toBeGreaterThan(y + 1); + + await search.fill("Fallback font"); + const fallback = options.getByRole("combobox", { name: "Fallback font", exact: true }); + await fallback.scrollIntoViewIfNeeded(); + await expect(fallback).toBeInViewport(); + await fallback.fill("Consolas"); + await expect(preview).toHaveCSS("font-family", /Consolas/); + await expect(preview).toBeInViewport(); + await expect.poll(() => options.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1); +}); diff --git a/e2e/welcomeProjectsLayout.spec.ts b/e2e/welcomeProjectsLayout.spec.ts new file mode 100644 index 0000000000..786da33290 --- /dev/null +++ b/e2e/welcomeProjectsLayout.spec.ts @@ -0,0 +1,42 @@ +import { expect, test } from "./fixtures"; + +test("Welcome keeps project search and actions on one row at a narrow width", async ({ workbench: page }) => { + await page.setViewportSize({ width: 1080, height: 700 }); + await page.evaluate(async () => { + const projectPath = "/src/platform/project.ts"; + const { useProject } = await import(/* @vite-ignore */ projectPath); + useProject.setState({ project: null, lightEdit: false }); + }); + + const projects = page.getByRole("region", { name: "Projects", exact: true }); + const search = projects.getByRole("textbox", { name: "Search projects" }); + const list = projects.getByRole("listbox", { name: "Recent projects" }); + const more = projects.getByRole("button", { name: "More Actions", exact: true }); + const open = projects.getByRole("button", { name: "Open", exact: true }); + await expect(list.getByRole("option")).toHaveCount(4); + await expect(more).toBeVisible(); + await expect(open).toHaveText("Open"); + + await page.setViewportSize({ width: 440, height: 620 }); + const boxes = await Promise.all([search.boundingBox(), open.boundingBox(), more.boundingBox()]); + expect(boxes[0]!.width).toBeGreaterThan(95); + for (const box of boxes.slice(1)) { + expect(Math.abs(box!.y + box!.height / 2 - (boxes[0]!.y + boxes[0]!.height / 2))).toBeLessThan(2); + expect(box!.x + box!.width).toBeLessThanOrEqual(440); + } + await expect(open.getByText("Open", { exact: true })).toBeHidden(); + await expect.poll(() => projects.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1); + + await search.fill("tokio"); + await expect(list.getByRole("option")).toHaveCount(1); + await expect(list.getByRole("option")).toContainText("tokio"); + await more.press("Enter"); + const menu = page.getByRole("menu", { name: "More Actions" }); + for (const label of ["New File", "Open File", "Remote Development"]) { + await expect(menu.getByRole("menuitem", { name: new RegExp(label) })).toBeVisible(); + } + await page.keyboard.press("Escape"); + await expect(menu).toBeHidden(); + await expect(more).toBeFocused(); + await expect(search).toHaveValue("tokio"); +}); diff --git a/src/editor/core/cm/languages.test.ts b/src/editor/core/cm/languages.test.ts index cf50cf1d6d..73cfabca92 100644 --- a/src/editor/core/cm/languages.test.ts +++ b/src/editor/core/cm/languages.test.ts @@ -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)!); diff --git a/src/editor/core/cm/languages.ts b/src/editor/core/cm/languages.ts index c81820ae58..cf7808fc81 100644 --- a/src/editor/core/cm/languages.ts +++ b/src/editor/core/cm/languages.ts @@ -420,6 +420,9 @@ export const JAVA_TAGS: Parameters[0] = { this: t.keyword, }; +// @lezer/go leaves `default` uncoloured, unlike `case` and `switch`. +const GO_TAGS: Parameters[0] = { default: t.controlKeyword }; + /** Highlighting the stock grammars lack or colour unlike IntelliJ. */ const EXTRA_TAGS: Record[0]> = { JavaScript: JS_TAGS, @@ -437,6 +440,7 @@ const EXTRA_TAGS: Record[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, diff --git a/src/features/agents/AgentList.tsx b/src/features/agents/AgentList.tsx index 965342d378..b0a0831559 100644 --- a/src/features/agents/AgentList.tsx +++ b/src/features/agents/AgentList.tsx @@ -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) => + 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(null); // An edit can have been staged by a previous page instance. Its Apply callback @@ -849,6 +866,27 @@ function ProviderSettings({
+ {agent.id === "copilot" && ( + GitHub account} + htmlFor={`agent-github-account-${agent.id}`} + hint={ + + Leave empty to use the active GitHub CLI account. OpenIDEA resolves the token at launch and never + stores it. + + } + > + account.set(e.target.value)} + /> + + )} Command}> {launch} diff --git a/src/features/agents/ConfigPickers.tsx b/src/features/agents/ConfigPickers.tsx index f6d5144527..58ff1cba6e 100644 --- a/src/features/agents/ConfigPickers.tsx +++ b/src/features/agents/ConfigPickers.tsx @@ -284,7 +284,7 @@ function ModelPicker({ const pinnedModels = useAgents((s) => s.pinnedModels); const anchor = useRef(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")); diff --git a/src/features/agents/agentRegistry.test.tsx b/src/features/agents/agentRegistry.test.tsx index 975782be43..6f09154f71 100644 --- a/src/features/agents/agentRegistry.test.tsx +++ b/src/features/agents/agentRegistry.test.tsx @@ -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: () => , }); render(); - 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 = [ diff --git a/src/features/agents/modelRefresh.test.tsx b/src/features/agents/modelRefresh.test.tsx index abc61b9a0c..2ae959f8f1 100644 --- a/src/features/agents/modelRefresh.test.tsx +++ b/src/features/agents/modelRefresh.test.tsx @@ -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(); + 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(); diff --git a/src/features/agents/session/SessionComposer.tsx b/src/features/agents/session/SessionComposer.tsx index 8401cfdcdf..3a72085b78 100644 --- a/src/features/agents/session/SessionComposer.tsx +++ b/src/features/agents/session/SessionComposer.tsx @@ -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(null); diff --git a/src/features/agents/store.ts b/src/features/agents/store.ts index 457a11d984..b1504b6bec 100644 --- a/src/features/agents/store.ts +++ b/src/features/agents/store.ts @@ -421,7 +421,7 @@ export async function refreshModels( export async function refreshTaskModels(id: string, force = true): Promise { 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); diff --git a/src/features/debugger/__tests__/toolWindow.test.tsx b/src/features/debugger/__tests__/toolWindow.test.tsx index cf291552be..99abdee4d7 100644 --- a/src/features/debugger/__tests__/toolWindow.test.tsx +++ b/src/features/debugger/__tests__/toolWindow.test.tsx @@ -396,6 +396,32 @@ describe("variables the adapter computes after the stop", () => { } }); + it("offers Remove All Watches on a watch's context menu", async () => { + useDebug.setState({ watches: ["count + 1", "label.upper()"] }); + const menu = (text: string) => { + fireEvent.contextMenu(screen.getByText(text).closest("[role=treeitem]")!); + const items = useContextMenuStore.getState().menu?.items ?? []; + act(() => hideContextMenu()); + return items.flatMap((i) => ("label" in i && i.label ? [i] : [])); + }; + try { + setup(); + await screen.findByText("label.upper()"); + await screen.findByText("'hi'"); + expect(menu("label").map((i) => i.label)).not.toContain("Remove All Watches"); + const items = menu("count + 1"); + expect(items.map((i) => i.label)).toContain("Remove Watch"); + const removeAll = items.find((i) => i.label === "Remove All Watches"); + expect(removeAll).toBeTruthy(); + act(() => (removeAll as { run: () => void }).run()); + expect(useDebug.getState().watches).toEqual([]); + await waitFor(() => expect(screen.queryByText("label.upper()")).toBeNull()); + expect(screen.getByText("'hi'")).toBeTruthy(); + } finally { + useDebug.setState({ watches: [] }); + } + }); + it("reloads after Set Value", async () => { setup(); await screen.findByText("Collecting data…"); diff --git a/src/features/debugger/__tests__/watchStorage.test.ts b/src/features/debugger/__tests__/watchStorage.test.ts index 48386436fa..ce477b9432 100644 --- a/src/features/debugger/__tests__/watchStorage.test.ts +++ b/src/features/debugger/__tests__/watchStorage.test.ts @@ -1,5 +1,5 @@ import { beforeEach, describe, expect, it } from "vitest"; -import { addWatch, loadWatches, useDebug } from "../state"; +import { addWatch, loadWatches, removeAllWatches, useDebug } from "../state"; const SHARED = "openidea.debugger.watches"; const of = (root: string) => `${SHARED}:${root}`; @@ -41,6 +41,23 @@ describe("watch storage", () => { expect(watches()).toEqual([]); }); + it("Remove All Watches empties the project's stored list", () => { + localStorage.setItem(SHARED, '["legacy"]'); + loadWatches("/a"); + addWatch("x"); + addWatch("y"); + loadWatches("/b"); + addWatch("z"); + loadWatches("/a"); + removeAllWatches(); + expect(watches()).toEqual([]); + expect(localStorage.getItem(of("/a"))).toBe("[]"); + loadWatches("/a"); + expect(watches()).toEqual([]); + loadWatches("/b"); + expect(watches()).toEqual(["legacy", "z"]); + }); + it("without a project nothing is stored", () => { loadWatches(null); addWatch("z"); diff --git a/src/features/debugger/state.ts b/src/features/debugger/state.ts index 9014a529f6..6c20e4f84e 100644 --- a/src/features/debugger/state.ts +++ b/src/features/debugger/state.ts @@ -1221,6 +1221,11 @@ export function removeWatch(expression: string) { persistWatches(); } +export function removeAllWatches() { + useDebug.setState({ watches: [] }); + persistWatches(); +} + /** Watches used to be one list for every project; it is only read now, as a project's first list. */ const SHARED_WATCH_KEY = "openidea.debugger.watches"; const watchKey = (root: string) => `${SHARED_WATCH_KEY}:${root}`; diff --git a/src/features/debugger/ui/VariablesView.tsx b/src/features/debugger/ui/VariablesView.tsx index 214e69a92f..82ae6a1fde 100644 --- a/src/features/debugger/ui/VariablesView.tsx +++ b/src/features/debugger/ui/VariablesView.tsx @@ -9,7 +9,15 @@ import { activeEditor } from "@/editor/api"; import { notifications } from "@/workbench/contributions"; import { addFieldWatchpoint } from "../breakpoints/special"; import { methodAt } from "../breakpoints/symbols"; -import { activeSession, addWatch, removeWatch, revealFrame, sessionSupports, setVariableValue } from "../state"; +import { + activeSession, + addWatch, + removeAllWatches, + removeWatch, + revealFrame, + sessionSupports, + setVariableValue, +} from "../state"; import { blurDebugView, focusDebugView } from "./focusedView"; import { classifyValue, oneLine, shownValue, sortVariables } from "../values"; import { valueText } from "../valueText"; @@ -300,7 +308,11 @@ export function VariablesView({ { label: "Set Value…", icon: "edit", shortcut: "F2", run: () => startEdit(node) }, { kind: "separator" }, ); - if (node.kind === "watch") items.push({ label: "Remove Watch", icon: "minus", run: () => removeWatch(node.name) }); + if (node.kind === "watch") + items.push( + { label: "Remove Watch", icon: "minus", run: () => removeWatch(node.name) }, + { label: "Remove All Watches", run: removeAllWatches }, + ); if (node.kind !== "scope") { items.push({ label: "Copy Value", icon: "copy", run: () => void copyValue(node) }); items.push({ label: "Copy Name", run: () => void writeClipboardText(node.name) }); diff --git a/src/features/http-client/HttpClientView.tsx b/src/features/http-client/HttpClientView.tsx index 7e811e46b1..e6a97a99f8 100644 --- a/src/features/http-client/HttpClientView.tsx +++ b/src/features/http-client/HttpClientView.tsx @@ -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(); diff --git a/src/features/http-client/responseFind.test.tsx b/src/features/http-client/responseFind.test.tsx index fc45a32e1e..d22111182c 100644 --- a/src/features/http-client/responseFind.test.tsx +++ b/src/features/http-client/responseFind.test.tsx @@ -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(); const body = screen.getByLabelText("Response body"); fireEvent.keyDown(body, { key: "f", metaKey: true, ctrlKey: true }); diff --git a/src/features/http-client/spring/endpoints.ts b/src/features/http-client/spring/endpoints.ts index 22dbb32f87..72fe1e8150 100644 --- a/src/features/http-client/spring/endpoints.ts +++ b/src/features/http-client/spring/endpoints.ts @@ -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) => diff --git a/src/features/http-client/spring/spring.test.ts b/src/features/http-client/spring/spring.test.ts index ac0cbb9742..9fdc006600 100644 --- a/src/features/http-client/spring/spring.test.ts +++ b/src/features/http-client/spring/spring.test.ts @@ -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([]); diff --git a/src/features/http-client/store.test.ts b/src/features/http-client/store.test.ts index aaedff5998..e4153357cb 100644 --- a/src/features/http-client/store.test.ts +++ b/src/features/http-client/store.test.ts @@ -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>) => void; + const first = new Promise>>((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")]); +}); diff --git a/src/features/http-client/store.ts b/src/features/http-client/store.ts index 57576bba00..38b456e5f2 100644 --- a/src/features/http-client/store.ts +++ b/src/features/http-client/store.ts @@ -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 { @@ -41,8 +44,8 @@ interface HttpClientState { environments: Record; /** History entries, newest first (this session's runs included). */ history: HttpHistoryEntry[]; - /** Loaded exchanges by entry id. */ - exchanges: Record; + /** Loaded exchanges, most recently viewed first. */ + exchanges: HttpExchange[]; selected: string | null; running: Running | null; } @@ -51,7 +54,7 @@ export const useHttpClient = create(() => ({ 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 { @@ -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 }); } diff --git a/src/features/run/ConsoleView.tsx b/src/features/run/ConsoleView.tsx index 7aeb93e5d2..bbd53475a0 100644 --- a/src/features/run/ConsoleView.tsx +++ b/src/features/run/ConsoleView.tsx @@ -29,6 +29,7 @@ import { useConsoleSelection } from "./useConsoleSelection"; import { hostBinding, formatBinding, hasPrimaryModifier, registerKeyClaim } from "@/platform/keymap"; import { WidestColumns } from "@/platform/consoleColumns"; import { tx } from "@/platform/i18n"; +import { executeAction } from "@/platform/actions"; import { ConsoleFindBar } from "@/ui/ConsoleFindBar"; import { DEFAULT_FIND_OPTIONS, findInLines, type FindOptions } from "@/ui/consoleFind"; @@ -115,6 +116,15 @@ export interface Fold { */ export type DisplayRow = { kind: "line"; index: number; fold?: Fold } | { kind: "fold"; fold: Fold }; +/** + * IDEA's Fold Lines Like This: the selection when it stays on one line, else the clicked line; + * trimmed, and `null` when that leaves nothing to fold on. + */ +export function foldLineText(selection: string, line: string | null): string | null { + const text = (selection || (line ?? "")).trim(); + return text && !/[\r\n]/.test(text) ? text : null; +} + /** * Folds runs of consecutive output lines (one or more) that contain one of * `patterns`; runs whose first line id is in `expanded` stay open. @@ -421,9 +431,18 @@ export function ConsoleView({ /** The selected text; after Select All the whole buffer, including rows that are not mounted. */ const selectedOutput = () => (allSelected() ? model.text() : (window.getSelection()?.toString() ?? "")); + /** The output line a context menu opened on; folds and the input row have none. */ + const lineAt = (target: EventTarget) => { + const index = (target as Element).closest?.("[data-index]")?.getAttribute("data-index"); + const row = index == null ? undefined : rows[Number(index)]; + const line = row?.kind === "line" ? lines[row.index] : undefined; + return line && line.kind !== "system" ? line.text : null; + }; + const onContextMenu = (e: MouseEvent) => { e.preventDefault(); const selection = selectedOutput(); + const foldText = foldLineText(selection, lineAt(e.target)); showContextMenu(e, [ { label: "Copy", @@ -441,6 +460,12 @@ export function ConsoleView({ run: openFind, }, { kind: "separator" }, + { + label: "Fold Lines Like This", + disabled: !foldText, + // Opens Settings › Console with the text added to the fold patterns, for OK / Cancel there. + run: () => void executeAction("file.settings", `build.console#${foldText}`), + }, { label: "Clear All", icon: "trash", disabled: !onClear, run: () => onClear?.() }, ...(input ? [{ kind: "separator" } as const, { label: "Send EOF", shortcut: "⌃D", run: () => input.onEof() }] diff --git a/src/features/run/consoleFoldLines.test.tsx b/src/features/run/consoleFoldLines.test.tsx new file mode 100644 index 0000000000..8c1323d733 --- /dev/null +++ b/src/features/run/consoleFoldLines.test.tsx @@ -0,0 +1,129 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { act, fireEvent, render, within } from "@testing-library/react"; +import { useProject } from "@/platform/project"; +import { hideContextMenu, useContextMenuStore } from "@/ui"; +import { ConsoleModel } from "./console"; +import { ConsoleView, foldLineText } from "./ConsoleView"; + +const actions = vi.hoisted(() => ({ executeAction: vi.fn(async () => {}) })); +vi.mock("@/platform/actions", async (orig) => ({ ...(await orig()), executeAction: actions.executeAction })); + +vi.mock("@tanstack/react-virtual", () => ({ + useVirtualizer: ({ count }: { count: number }) => ({ + getTotalSize: () => count * 20, + getVirtualItems: () => Array.from({ length: count }, (_, index) => ({ index, start: index * 20, key: index })), + scrollToIndex: () => {}, + measureElement: () => {}, + measure: () => {}, + }), +})); + +beforeEach(() => { + actions.executeAction.mockClear(); + useProject.setState({ settings: null }); + window.getSelection()?.removeAllRanges(); +}); + +afterEach(() => act(hideContextMenu)); + +function setup(chunks: { kind: "stdout" | "stderr" | "system"; text: string }[]) { + const model = new ConsoleModel(); + for (const c of chunks) model.append(c); + model.flush(); + const { container } = render( + {}} cwd="/" />, + ); + return within(container).getByRole("log"); +} + +function foldItem(target: Element) { + fireEvent.contextMenu(target); + const items = useContextMenuStore.getState().menu?.items ?? []; + return items.find((i) => "label" in i && i.label === "Fold Lines Like This") as + | { disabled?: boolean; run?: () => void } + | undefined; +} + +function select(node: Node, start: number, end: number) { + const range = document.createRange(); + range.setStart(node, start); + range.setEnd(node, end); + window.getSelection()!.removeAllRanges(); + window.getSelection()!.addRange(range); +} + +describe("foldLineText", () => { + it("takes a one-line selection, else the clicked line, trimmed", () => { + expect(foldLineText(" at org.junit.Assert ", "ignored")).toBe("at org.junit.Assert"); + expect(foldLineText("", "\tat java.base/Thread.run(Thread.java:1583) ")).toBe( + "at java.base/Thread.run(Thread.java:1583)", + ); + // A whole row picked by a triple click ends in its line break. + expect(foldLineText("DEBUG pool\n", null)).toBe("DEBUG pool"); + }); + + it("has nothing for a selection across lines, a blank selection or a blank line", () => { + expect(foldLineText("first\nsecond", "first")).toBeNull(); + expect(foldLineText("first\r\nsecond", "first")).toBeNull(); + expect(foldLineText(" ", "a line")).toBeNull(); + expect(foldLineText("", " ")).toBeNull(); + expect(foldLineText("", null)).toBeNull(); + }); +}); + +describe("Fold Lines Like This", () => { + it("opens Settings › Console with the clicked line to add as a fold pattern", () => { + const log = setup([ + { + kind: "stdout", + text: "start\n at org.springframework.test.context.TestContextManager.prepare(TestContextManager.java:248)\n", + }, + ]); + const row = log.querySelectorAll("[data-index]")[1]!; + const item = foldItem(row.firstElementChild ?? row)!; + expect(item.disabled).toBeFalsy(); + item.run!(); + expect(actions.executeAction).toHaveBeenCalledWith( + "file.settings", + "build.console#at org.springframework.test.context.TestContextManager.prepare(TestContextManager.java:248)", + ); + }); + + it("uses the selected part of a line rather than the whole line", () => { + const log = setup([{ kind: "stdout", text: "12:00 DEBUG pool: idle\n" }]); + const row = log.querySelector("[data-index]")!; + const text = document.createTreeWalker(row, NodeFilter.SHOW_TEXT).nextNode()!; + select(text, 6, 11); + foldItem(row)!.run!(); + expect(actions.executeAction).toHaveBeenCalledWith("file.settings", "build.console#DEBUG"); + }); + + it("is disabled for a selection over several lines", () => { + const log = setup([{ kind: "stdout", text: "one\ntwo\n" }]); + const rows = log.querySelectorAll("[data-index]"); + const range = document.createRange(); + range.setStart(rows[0]!, 0); + range.setEnd(rows[1]!, rows[1]!.childNodes.length); + window.getSelection()!.removeAllRanges(); + window.getSelection()!.addRange(range); + expect(foldItem(rows[0]!)!.disabled).toBe(true); + }); + + it("is disabled on a blank line, the IDE's own messages and a folded run", () => { + useProject.setState({ settings: { console: { foldPatterns: ["at org."] } } as never }); + const log = setup([ + { kind: "stdout", text: "\n" }, + { kind: "system", text: "Process finished with exit code 0\n" }, + ]); + const rows = log.querySelectorAll("[data-index]"); + expect(foldItem(rows[0]!)!.disabled).toBe(true); + expect(foldItem(rows[1]!)!.disabled).toBe(true); + act(hideContextMenu); + + const folded = setup([{ kind: "stdout", text: "at org.a\nat org.b\n" }]); + const fold = folded.querySelector("[data-index]")!; + expect(fold.textContent).toContain("internal lines"); + expect(foldItem(fold)!.disabled).toBe(true); + expect(actions.executeAction).not.toHaveBeenCalled(); + }); +}); diff --git a/src/features/settings/__tests__/consoleFoldPatterns.test.tsx b/src/features/settings/__tests__/consoleFoldPatterns.test.tsx new file mode 100644 index 0000000000..df5cd4cdca --- /dev/null +++ b/src/features/settings/__tests__/consoleFoldPatterns.test.tsx @@ -0,0 +1,107 @@ +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { act, fireEvent, render, screen, within } from "@testing-library/react"; +import { type Settings } from "@/platform/ipc"; + +const settingsSet = vi.fn(); +const settingsGet = vi.fn(); +const settingsGetGlobal = vi.fn(); + +vi.mock("@/platform/ipc", async (importOriginal) => { + const real = await importOriginal(); + return { + ...real, + isTauri: () => true, + commands: { + ...real.commands, + settingsSet: (...a: unknown[]) => settingsSet(...a), + settingsGet: () => settingsGet(), + settingsGetGlobal: () => settingsGetGlobal(), + }, + }; +}); + +import { executeAction } from "@/platform/actions"; +import { useProject } from "@/platform/project"; +import { DEFAULT_SETTINGS, setAt } from "../model/schema"; +import { useSettingsDialog } from "../model/staging"; +import { SettingsDialog } from "../dialog/SettingsDialog"; +import { activate } from ".."; + +let current: Settings; +let dispose: () => void = () => {}; + +beforeEach(() => { + current = setAt(structuredClone(DEFAULT_SETTINGS) as Settings, "console.foldPatterns", ["at org.junit."]); + settingsSet.mockReset().mockImplementation(async (_scope: string, key: string, json: string) => { + current = setAt(current, key, JSON.parse(json)); + return { status: "ok", data: current }; + }); + settingsGet.mockReset().mockImplementation(async () => current); + settingsGetGlobal.mockReset().mockImplementation(async () => current); + useProject.setState({ settings: current, project: null }); + dispose = activate(); +}); + +afterEach(() => { + act(() => useSettingsDialog.setState({ open: false })); + dispose(); +}); + +/** Settings › Console as the console's Fold Lines Like This opens it. */ +async function openWith(text: string) { + render(); + await act(async () => { + await executeAction("file.settings", `build.console#${text}`); + }); + const dialog = screen.getByRole("dialog", { name: "Settings" }); + const list = await within(dialog).findByRole("listbox", { name: "Fold console lines that contain" }); + return { + dialog, + patterns: () => + within(list) + .getAllByRole("option") + .map((o) => o.textContent), + }; +} + +it("adds the console's line to the fold patterns, written on OK", async () => { + const { dialog, patterns } = await openWith("at com.example.Retry#call"); + expect(patterns()).toEqual(["at org.junit.", "at com.example.Retry#call"]); + expect(settingsSet).not.toHaveBeenCalled(); + await act(async () => fireEvent.click(within(dialog).getByRole("button", { name: "OK" }))); + expect(settingsSet).toHaveBeenCalledWith( + "global", + "console.foldPatterns", + JSON.stringify(["at org.junit.", "at com.example.Retry#call"]), + ); +}); + +it("writes nothing when the dialog is cancelled", async () => { + const { dialog } = await openWith("DEBUG"); + await act(async () => fireEvent.click(within(dialog).getByRole("button", { name: "Cancel" }))); + expect(settingsSet).not.toHaveBeenCalled(); +}); + +it("does not add a pattern the list already has", async () => { + const { dialog, patterns } = await openWith("at org.junit."); + expect(patterns()).toEqual(["at org.junit."]); + await act(async () => fireEvent.click(within(dialog).getByRole("button", { name: "OK" }))); + expect(settingsSet).not.toHaveBeenCalled(); +}); + +it("adds to the global list, not the project's own, while the global settings load", async () => { + const global = current; + settingsGetGlobal.mockImplementation(async () => global); + useProject.setState({ + settings: setAt(global, "console.foldPatterns", ["at com.acme.internal."]), + project: { root: "/p", name: "p" } as never, + }); + const { dialog, patterns } = await openWith("DEBUG"); + expect(patterns()).toEqual(["at org.junit.", "DEBUG"]); + await act(async () => fireEvent.click(within(dialog).getByRole("button", { name: "OK" }))); + expect(settingsSet).toHaveBeenCalledWith( + "global", + "console.foldPatterns", + JSON.stringify(["at org.junit.", "DEBUG"]), + ); +}); diff --git a/src/features/settings/pages/editor/ColorSchemeBody.tsx b/src/features/settings/pages/editor/ColorSchemeBody.tsx index 46ed4b7fc1..bcb21f5f3a 100644 --- a/src/features/settings/pages/editor/ColorSchemeBody.tsx +++ b/src/features/settings/pages/editor/ColorSchemeBody.tsx @@ -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("editor.colorScheme", "global"); const [overrides, setOverrides] = useSetting("editor.colorOverrides", "global"); @@ -1580,7 +1600,7 @@ export function ColorSchemePage({ scopes, landing }: { scopes: readonly string[] [], ); return ( -
+
{ @@ -187,27 +199,60 @@ function Preview() { ); } -export const FONT_PAGE = editorPage({ +const FONT_SECTIONS: EditorSection[] = [ + { + items: [ + { t: "custom", label: "Font", keywords: ["font family", "Show only monospaced fonts"], component: FontRow }, + { t: "custom", label: "Size", keywords: ["Line height"], component: SizeRow }, + { t: "check", key: "editor.ligatures", label: "Enable ligatures" }, + ], + }, + { + title: "Typography Settings", + items: [ + { t: "custom", label: "Main font weight", keywords: ["Bold font weight"], component: WeightRows }, + { t: "custom", label: "Fallback font", component: FallbackRow }, + ], + }, +]; + +function FontPage() { + const page = useRef(null); + const [stacked, setStacked] = useState(true); + useLayoutEffect(() => { + const el = page.current; + if (!el) return; + const measure = () => setStacked(el.clientWidth < 620); + measure(); + if (typeof ResizeObserver === "undefined") return; + const observer = new ResizeObserver(measure); + observer.observe(el); + return () => observer.disconnect(); + }, []); + return ( +
+ + +
+ +
+
+ + + + +
+
+ ); +} + +export const FONT_PAGE: PageSpec = { id: "editor.font", title: "Font", + group: "Editor", order: 22, projectScope: true, keywords: ["typeface", "monospace", "ligatures", "font size", "line spacing", "font weight", "bold"], - sections: [ - { - items: [ - { t: "custom", label: "Font", keywords: ["font family", "Show only monospaced fonts"], component: FontRow }, - { t: "custom", label: "Size", keywords: ["Line height"], component: SizeRow }, - { t: "check", key: "editor.ligatures", label: "Enable ligatures" }, - ], - }, - { - title: "Typography Settings", - items: [ - { t: "custom", label: "Main font weight", keywords: ["Bold font weight"], component: WeightRows }, - { t: "custom", label: "Fallback font", component: FallbackRow }, - ], - }, - ], - footer: Preview, -}); + component: FontPage, + dynamicLabels: () => sectionLabels(FONT_SECTIONS), +}; diff --git a/src/features/settings/pages/execution.tsx b/src/features/settings/pages/execution.tsx index e817c63898..2819b366b9 100644 --- a/src/features/settings/pages/execution.tsx +++ b/src/features/settings/pages/execution.tsx @@ -3,10 +3,15 @@ * Stepping), Python Debugger and Run/Debug. Consumed by the run and debugger * features (and `ide-run` for encoding / termination timeout). */ +import { useEffect } from "react"; import { WORKFLOW_LIMITS } from "@/platform/workflowSettings"; +import { useSettingsPageFocus } from "@/workbench/contributions"; +import { isTauri } from "@/platform/ipc"; +import { useProject } from "@/platform/project"; import type { SelectOption } from "@/ui"; import { ColorSwatches, FormGroup, GlobListEditor, NumberInput, Row, Toggle } from "../components/Form"; -import { useSetting } from "../components/context"; +import { usePageContext, useSetting } from "../components/context"; +import { useSettingsDialog } from "../model/staging"; import { lazyPage } from "./lazyPage"; import type { PageSpec } from "./spec"; import { Indented, ToggleNumber } from "./workflowControls"; @@ -53,6 +58,18 @@ function BufferRow() { function FoldPatterns() { const [patterns, set] = useSetting("console.foldPatterns"); + // Opened as `build.console#` by the console's Fold Lines Like This: add it as a pattern. + const { focus, consume } = useSettingsPageFocus(); + // With a project open, the Global list arrives after the dialog opens (until then it is the project's). + const { scope } = usePageContext(); + const globalPending = useSettingsDialog((s) => s.globalBase === s.base); + const hasProject = useProject((s) => !!s.project); + const waiting = scope === "global" && globalPending && hasProject && isTauri(); + useEffect(() => { + if (!focus || waiting) return; + consume(); + if (!patterns.includes(focus)) set([...patterns, focus]); + }, [focus, consume, waiting, patterns, set]); return ( void; }) { - const rowHeight = useRowHeight(22); + const rowHeight = useRowHeight(rangeLabel ? 42 : 22); return ( -
+
{error ? (
{error} @@ -92,7 +95,7 @@ function CommitList({ items={commits} getKey={(c) => c.id} rowHeight={rowHeight} - aria-label="Commits" + aria-label={rangeLabel ?? "Commits"} className={styles.grow} empty={ @@ -103,27 +106,53 @@ function CommitList({ onClose(); void executeAction("vcs.showCommit", c); }} - renderItem={(c) => ( - - {c.shortId} - - {c.summary} + renderItem={(c) => + rangeLabel ? ( +
+ + {c.summary} + +
+ {c.shortId} + {c.author} + {formatTime(c.timeMs)} +
+
+ ) : ( + + {c.shortId} + + {c.summary} + + {c.author} + {formatTime(c.timeMs)} - {c.author} - {formatTime(c.timeMs)} -
- )} + ) + } /> )}
); } +function CompareRange({ label, commits, onClose }: { label: string; commits: Commit[] | null; onClose: () => void }) { + return ( + +
+
+

{label}

+ {commits && {commits.length}} +
+ +
+
+ ); +} + function CompareDialog({ branch, current, onClose }: { branch: string; current: string; onClose: () => void }) { const [repo] = useState(currentRepo); const [data, setData] = useState<{ incoming: Commit[]; outgoing: Commit[] } | null>(null); const [error, setError] = useState(null); - const [tab, setTab] = useState("incoming"); useEffect(() => { let alive = true; Promise.all([commitsBetween("HEAD", branch, repo), commitsBetween(branch, "HEAD", repo)]) @@ -134,17 +163,17 @@ function CompareDialog({ branch, current, onClose }: { branch: string; current: return () => { alive = false; }; - }, [branch]); - const list = data ? (tab === "incoming" ? data.incoming : data.outgoing) : []; + }, [branch, repo]); return ( { onClose(); // Whole-project diff: every file that differs between the branches. - showCompareRevisions(branch, "HEAD", branch, current); + showCompareRevisions(branch, "HEAD", branch, current, repo); }, }, { label: "Close", role: "cancel" }, ]} > - - + {error ? ( +
+ {error} +
+ ) : ( + + + + + + )}
); } diff --git a/src/features/vcs/__tests__/branchOps.test.ts b/src/features/vcs/__tests__/branchOps.test.ts index 6966b2a5a0..44f9286be5 100644 --- a/src/features/vcs/__tests__/branchOps.test.ts +++ b/src/features/vcs/__tests__/branchOps.test.ts @@ -1,4 +1,4 @@ -import { beforeEach, expect, it, vi } from "vitest"; +import { afterEach, beforeEach, expect, it, vi } from "vitest"; import type { Branch, BranchInfo, ProjectInfo, Worktree } from "@/bindings"; const mocks = vi.hoisted(() => ({ prompt: vi.fn(), @@ -13,6 +13,7 @@ const mocks = vi.hoisted(() => ({ ask: vi.fn(), checkout: vi.fn(), executeAction: vi.fn(), + windowOpenRemote: vi.fn(), })); vi.mock("../dialogs", async (original) => ({ ...(await original()), @@ -41,12 +42,14 @@ vi.mock("@/platform/ipc", async (original) => { vcsBranches: mocks.branches, vcsRenameBranch: mocks.rename, vcsCheckout: mocks.checkout, + windowOpenRemote: mocks.windowOpenRemote, }, }; }); import { checkoutBranch, deleteBranch, deleteBranches, newBranch, newBranchInRepos, renameBranch } from "../branchOps"; import { useVcs } from "../store"; import { useProject } from "@/platform/project"; +import { useRemote } from "@/platform/remote"; const branch = (head: string | null): BranchInfo => ({ head, @@ -386,3 +389,40 @@ it("refreshes tracking branches in the deletion repository without replacing the notification.actions.find((a: { label: string }) => a.label === "Restore").run(); await vi.waitFor(() => expect(mocks.restoreBranch).toHaveBeenCalledWith("/p/back", expect.anything())); }); + +afterEach(() => useRemote.setState({ session: null })); + +it.each(["focused", "failed"])("opens a checked-out SSH branch without retrying checkout: %s", async (outcome) => { + const target = { kind: "ssh", config: "connected-host" } as const; + const path = "/p/front feature"; + useRemote.setState({ session: { target, root: "/p/front", host: "demo-linux", os: "linux", commands: [] } }); + mocks.checkout.mockReset().mockResolvedValue(ok({ kind: "checkedOutInWorktree", branch: "feature/wt", path })); + mocks.ask.mockReset().mockResolvedValue({ button: "open" }); + mocks.windowOpenRemote + .mockReset() + .mockResolvedValue( + outcome === "focused" + ? ok({ kind: "focused", label: "existing-window" }) + : { status: "error", error: { kind: "unavailable", message: "SSH unavailable", detail: null } }, + ); + mocks.executeAction.mockClear(); + mocks.notify.mockClear(); + await checkoutBranch("feature/wt"); + expect(mocks.windowOpenRemote).toHaveBeenCalledExactlyOnceWith(target, path, true); + expect(mocks.checkout).toHaveBeenCalledTimes(1); + expect(mocks.executeAction).not.toHaveBeenCalledWith("file.openProjectPath", expect.anything()); + if (outcome === "failed") { + expect(mocks.notify).toHaveBeenCalledWith(expect.objectContaining({ level: "error", body: "SSH unavailable" })); + } +}); + +it("keeps the local open action when another worktree holds the branch", async () => { + const path = "C:/src/project-worktree"; + useRemote.setState({ session: null }); + mocks.checkout.mockResolvedValue(ok({ kind: "checkedOutInWorktree", branch: "feature/wt", path })); + mocks.ask.mockResolvedValue({ button: "open" }); + await checkoutBranch("feature/wt"); + expect(mocks.executeAction).toHaveBeenCalledExactlyOnceWith("file.openProjectPath", path); + expect(mocks.windowOpenRemote).not.toHaveBeenCalled(); + expect(mocks.checkout).toHaveBeenCalledTimes(1); +}); diff --git a/src/features/vcs/__tests__/worktreesPanel.test.tsx b/src/features/vcs/__tests__/worktreesPanel.test.tsx index 4e7610f0dd..1285c57823 100644 --- a/src/features/vcs/__tests__/worktreesPanel.test.tsx +++ b/src/features/vcs/__tests__/worktreesPanel.test.tsx @@ -1,18 +1,25 @@ -import { beforeEach, expect, it, vi } from "vitest"; +import { afterEach, beforeEach, expect, it, vi } from "vitest"; import { act, fireEvent, render, screen, waitFor } from "@testing-library/react"; -const { list, move, remove, open, confirm } = vi.hoisted(() => ({ +const { list, move, remove, open, confirm, windowOpenRemote } = vi.hoisted(() => ({ list: vi.fn(), move: vi.fn(), remove: vi.fn(), open: vi.fn(), confirm: vi.fn(), + windowOpenRemote: vi.fn(), })); vi.mock("@/platform/ipc", async (original) => { const real = await original(); return { ...real, - commands: { ...real.commands, vcsWorktrees: list, vcsMoveWorktree: move, vcsRemoveWorktree: remove }, + commands: { + ...real.commands, + vcsWorktrees: list, + vcsMoveWorktree: move, + vcsRemoveWorktree: remove, + windowOpenRemote, + }, }; }); vi.mock("@/platform/dialog", () => ({ open })); @@ -24,11 +31,15 @@ vi.mock("../dialogs", async (original) => ({ import { WorktreesPanel } from "../gitMenuDialogs"; import { useVcs } from "../store"; import { useProject } from "@/platform/project"; +import { useRemote } from "@/platform/remote"; +import { registerAction } from "@/platform/actions"; const worktrees = [ { path: "/work/app", branch: "main", head: "12345678", main: true, locked: false, prunable: false }, { path: "/work/app-feature", branch: "feature", head: "12345678", main: false, locked: false, prunable: false }, ]; +const ssh = { kind: "ssh", config: "test-linux" } as const; +const wsl = { kind: "wsl", distro: "Ubuntu" } as const; const ok = (data: T) => ({ status: "ok" as const, data }); const fail = (message: string) => ({ status: "error", error: { kind: "invalidInput", message, detail: null } }); @@ -130,3 +141,41 @@ it("keeps the error and selected worktree after force removal fails", async () = expect(await screen.findByRole("alert")).toHaveTextContent(failure); expect(screen.getByRole("treeitem", { name: /feature/ })).toHaveAttribute("aria-selected", "true"); }); + +afterEach(() => useRemote.setState({ session: null })); + +it.each([ + ["toolbar", ssh], + ["double click", ssh], + ["toolbar", wsl], +] as const)("opens a remote worktree via %s with the current target", async (entry, target) => { + useRemote.setState({ + session: { target, root: "/work/app-feature", host: "demo-linux", os: "linux", commands: [] }, + }); + windowOpenRemote.mockReset().mockResolvedValue(ok({ kind: "opened", label: "git-main" })); + render(); + const row = await screen.findByRole("treeitem", { name: /main/ }); + fireEvent.mouseDown(row); + if (entry === "toolbar") fireEvent.click(screen.getByRole("button", { name: "Open in New Window" })); + else fireEvent.doubleClick(row); + await waitFor(() => expect(windowOpenRemote).toHaveBeenCalledExactlyOnceWith(target, "/work/app", true)); + expect(useProject.getState().project?.root).toBe("/work/app-feature"); +}); + +it.each(["toolbar", "double click"])("preserves the local project open via %s", async (entry) => { + useRemote.setState({ session: null }); + windowOpenRemote.mockReset(); + const run = vi.fn(); + const dispose = registerAction({ id: "file.openProjectPath", title: "Open Project Path", run }); + try { + render(); + const row = await screen.findByRole("treeitem", { name: /main/ }); + fireEvent.mouseDown(row); + if (entry === "toolbar") fireEvent.click(screen.getByRole("button", { name: "Open in New Window" })); + else fireEvent.doubleClick(row); + await waitFor(() => expect(run).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ arg: "/work/app" }))); + expect(windowOpenRemote).not.toHaveBeenCalled(); + } finally { + dispose(); + } +}); diff --git a/src/features/vcs/branchOps.ts b/src/features/vcs/branchOps.ts index 93401a2399..c6a1e0a054 100644 --- a/src/features/vcs/branchOps.ts +++ b/src/features/vcs/branchOps.ts @@ -5,6 +5,7 @@ import type { Branch, BranchInfo, BranchUpdateStatus, CheckoutOptions, Worktree import { executeAction } from "@/platform/actions"; import { call, commands } from "@/platform/ipc"; import { notifications } from "@/workbench/contributions"; +import { openWorktree } from "./openWorktree"; import { ask } from "@/workbench/messages"; import { branchNamePrefixes, isFavoriteBranch, pushRecent, shortRemoteName } from "./branches"; import { showCommitRange } from "./CompareBranches"; @@ -154,7 +155,7 @@ async function performCheckout( options = { ...options, ignoreOtherWorktrees: true }; continue; } - if (r.button === "open") await executeAction("file.openProjectPath", path); + if (r.button === "open") await openWorktree(path); return false; } } diff --git a/src/features/vcs/gitMenuDialogs.tsx b/src/features/vcs/gitMenuDialogs.tsx index 68c30b4450..589e0752d6 100644 --- a/src/features/vcs/gitMenuDialogs.tsx +++ b/src/features/vcs/gitMenuDialogs.tsx @@ -2,9 +2,9 @@ import { useEffect, useMemo, useRef, useState } from "react"; import clsx from "clsx"; import type { Branch, BranchInfo, MergeOptions, Remote, Worktree } from "@/bindings"; -import { executeAction } from "@/platform/actions"; import { call, commands } from "@/platform/ipc"; import { notifications } from "@/workbench/contributions"; +import { openWorktree } from "./openWorktree"; import { Button, Checkbox, @@ -890,7 +890,7 @@ export function WorktreesPanel({ className, listClassName }: { className?: strin title="Open in New Window" size="small" disabled={!current} - onClick={() => current && void executeAction("file.openProjectPath", current.path)} + onClick={() => current && void openWorktree(current.path)} />
@@ -912,7 +912,7 @@ export function WorktreesPanel({ className, listClassName }: { className?: strin selected={selectedKeys} multiSelect={false} onSelectionChange={(selection) => setSelected([...selection][0] ?? null)} - onActivate={(n) => n.worktree && void executeAction("file.openProjectPath", n.worktree.path)} + onActivate={(n) => n.worktree && void openWorktree(n.worktree.path)} className={listClassName ?? styles.worktreeListDialog} aria-label="Worktrees" /> diff --git a/src/features/vcs/openWorktree.ts b/src/features/vcs/openWorktree.ts new file mode 100644 index 0000000000..c456c4a0a4 --- /dev/null +++ b/src/features/vcs/openWorktree.ts @@ -0,0 +1,29 @@ +import { executeAction } from "@/platform/actions"; +import { t } from "@/platform/i18n"; +import { call, commands, isCancelled } from "@/platform/ipc"; +import { useRemote } from "@/platform/remote"; +import { notifications } from "@/workbench/contributions"; + +/** + * Opens worktree `path` in a new window. In an SSH or WSL session the path is on that + * machine, so the window connects there instead of opening it as a local folder. + */ +export async function openWorktree(path: string): Promise { + const target = useRemote.getState().session?.target; + if (target?.kind !== "ssh" && target?.kind !== "wsl") { + await executeAction("file.openProjectPath", path); + return; + } + try { + await call(commands.windowOpenRemote(target, path, true)); + } catch (error) { + if (isCancelled(error)) return; + notifications().notify({ + level: "error", + group: "vcs", + userInitiated: true, + title: t("app.window.openFailed", { name: path }), + body: error instanceof Error ? error.message : String(error), + }); + } +} diff --git a/src/features/viewers/markdown/render.test.ts b/src/features/viewers/markdown/render.test.ts index 20cc5efc0a..a6bb1daf3a 100644 --- a/src/features/viewers/markdown/render.test.ts +++ b/src/features/viewers/markdown/render.test.ts @@ -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 `` swallows the rest of the file, so it is rendered as a whole. for (const [readme, reuses] of [ diff --git a/src/features/welcome/ProjectsPage.tsx b/src/features/welcome/ProjectsPage.tsx index 31733c825d..2cd209a082 100644 --- a/src/features/welcome/ProjectsPage.tsx +++ b/src/features/welcome/ProjectsPage.tsx @@ -12,6 +12,8 @@ import { Icon, IconButton, Kbd, + Menu, + type MenuItem, SearchField, Spinner, isPopupOpen, @@ -27,40 +29,63 @@ import { tx } from "@/platform/i18n"; function HeaderButtons() { const canClone = useActions((s) => s.actions.has("vcs.clone")); - const canRemote = useActions((s) => s.actions.has("remote.connect")); const opening = useProject((s) => s.opening); const canCreate = useActions((s) => s.actions.has("file.newProject")); const openKey = shortcutLabel("file.openProject"); + const [moreOpen, setMoreOpen] = useState(false); + const more = useRef<HTMLButtonElement>(null); + const primary = [ + { id: "file.newProject", label: "New Project", icon: "plus", available: canCreate, disabled: opening }, + { + id: "file.openProject", + label: "Open", + icon: "folder-open", + title: openKey ? tx`Open (${openKey})` : undefined, + available: true, + disabled: opening, + }, + { id: "vcs.clone", label: "Clone Repository", icon: "branch", available: canClone }, + ]; + const secondary: MenuItem[] = [ + { kind: "action", action: "file.newUntitled", label: "New File", disabled: opening }, + { kind: "action", action: "file.openFile", label: "Open File", disabled: opening }, + { kind: "action", action: "remote.connect", label: "Remote Development", disabled: opening }, + ]; return ( - <div className={styles.headerButtons}> - <Button disabled={opening} onClick={() => void executeAction("file.newUntitled")}> - <T>New File</T> - </Button> - {canCreate && ( - <Button disabled={opening} onClick={() => void executeAction("file.newProject")}> - <T>New Project</T> - </Button> - )} - <Button - disabled={opening} - onClick={() => void executeAction("file.openProject")} - title={openKey ? tx`Open (${openKey})` : "Open"} - > - <T>Open</T> - </Button> - <Button disabled={opening} onClick={() => void executeAction("file.openFile")}> - <T>Open File</T> - </Button> - {canClone && ( - <Button onClick={() => void executeAction("vcs.clone")}> - <T>Clone Repository</T> - </Button> - )} - {canRemote && ( - <Button disabled={opening} onClick={() => void executeAction("remote.connect")}> - <T>Remote Development</T> - </Button> + <div className={styles.headerButtons} role="group" aria-label={tx("Project actions")}> + {primary.map( + ({ id, label, title, icon, available, disabled }) => + available && ( + <Button + key={id} + size="small" + icon={icon} + className={styles.headerAction} + title={title ?? label} + aria-label={tx(label)} + disabled={disabled} + onClick={() => void executeAction(id)} + > + <span className={styles.headerActionLabel}>{tx(label)}</span> + </Button> + ), )} + <IconButton + ref={more} + icon="more" + title="More Actions" + aria-haspopup="menu" + aria-expanded={moreOpen} + onClick={() => setMoreOpen((open) => !open)} + /> + <Menu + open={moreOpen} + onClose={() => setMoreOpen(false)} + anchor={more} + items={secondary} + placement="bottom-end" + aria-label="More Actions" + /> </div> ); } diff --git a/src/features/welcome/Welcome.module.css b/src/features/welcome/Welcome.module.css index 5859612054..faca55d70e 100644 --- a/src/features/welcome/Welcome.module.css +++ b/src/features/welcome/Welcome.module.css @@ -129,6 +129,7 @@ /* ---- Projects page ---------------------------------------------------- */ .projects { + container: welcome-projects / inline-size; flex: 1; min-height: 0; display: flex; @@ -138,30 +139,51 @@ flex: none; display: flex; align-items: center; - flex-wrap: wrap; - gap: var(--space-3); - min-height: 76px; - margin-left: 14px; - padding: 12px 14px 12px 6px; + gap: var(--space-2); + margin: 0 var(--space-3); + padding: var(--space-3) var(--space-1); box-shadow: inset 0 -1px 0 var(--border); } .search { - flex: 1 1 160px; + flex: 1; min-width: 0; } -/* Wraps in a narrow window, so no button is clipped. */ .headerButtons { - flex: 0 1 auto; - min-width: 0; + flex: none; display: flex; - flex-wrap: wrap; - gap: var(--space-2); + align-items: center; + gap: var(--space-1); +} +.headerAction { + max-width: 146px; +} +.headerActionLabel { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; +} +@container welcome-projects (max-width: 600px) { + .headerAction { + width: var(--h-control); + padding: 0; + } + .headerActionLabel { + display: none; + } +} +@container welcome-projects (max-width: 218px) { + .header { + flex-wrap: wrap; + } + .search { + flex-basis: 100%; + } } .projectList { flex: 1; min-height: 0; overflow-y: auto; - padding: 14px 16px 14px 24px; + padding: var(--space-2) var(--space-3) var(--space-3); outline: none; } .noMatches { @@ -174,7 +196,7 @@ display: flex; align-items: flex-start; gap: var(--space-3); - padding: 8px 10px; + padding: var(--space-2); border-radius: var(--radius-popup); cursor: default; } @@ -186,8 +208,11 @@ .projectSelected:hover { background: color-mix(in srgb, var(--bg-list-selected) 70%, var(--bg-island)); } -.projectBadge { - margin-top: 1px; +.tile.projectBadge { + width: 32px; + height: 32px; + margin-top: var(--space-0-5); + font-size: var(--fs-ui); } /* A project group: one line, folds its projects. */ .group { @@ -199,6 +224,7 @@ flex: 1; min-width: 0; color: var(--fg-strong); + font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; @@ -214,7 +240,8 @@ min-width: 0; display: flex; flex-direction: column; - line-height: 20px; + gap: var(--space-0-5); + line-height: 18px; } .projectName { color: var(--fg-strong); @@ -224,6 +251,7 @@ } .projectPath { color: var(--fg-muted); + font-size: var(--fs-small); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; @@ -234,6 +262,7 @@ gap: var(--space-1-5); min-width: 0; color: var(--fg-muted); + font-size: var(--fs-small); --icon-color: var(--fg-muted); } .projectBranchName { diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index e20c35ef8a..1823464529 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -1,7 +1,12 @@ { "Inspection details": "Inspection details", "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", @@ -2706,5 +2711,10 @@ "Loading…": "Loading…", "<schema>": "<schema>", "Shelve Silently": "Shelve Silently", - "Unshelve Silently": "Unshelve Silently" + "Unshelve Silently": "Unshelve Silently", + "Fold Lines Like This": "Fold Lines Like This", + "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" } diff --git a/src/platform/locales/text/es.json b/src/platform/locales/text/es.json index 43d982ebf1..300ba6cfa0 100644 --- a/src/platform/locales/text/es.json +++ b/src/platform/locales/text/es.json @@ -679,7 +679,6 @@ "Detecting…": "Detectando…", "Diff": "Diferencias", "Different tool window background": "Fondo diferente para las ventanas de herramientas", - "Direction": "Dirección", "Directory": "Directorio", "Staging State": "Estado de preparación (stage)", "Staged Changes": "Cambios preparados (staged)", diff --git a/src/platform/locales/text/fr.json b/src/platform/locales/text/fr.json index e036b0da4a..03a87d167d 100644 --- a/src/platform/locales/text/fr.json +++ b/src/platform/locales/text/fr.json @@ -620,7 +620,6 @@ "Detecting…": "Détection…", "Diff": "Diff", "Different tool window background": "Arrière-plan distinct pour les fenêtres d'outils", - "Direction": "Sens", "Directory": "Répertoire", "Directory (relative to project root)": "Répertoire (relatif à la racine du projet)", "Directory Mappings": "Associations de répertoires", diff --git a/src/platform/locales/text/ko.json b/src/platform/locales/text/ko.json index 6ea769967b..922fec95ca 100644 --- a/src/platform/locales/text/ko.json +++ b/src/platform/locales/text/ko.json @@ -715,7 +715,6 @@ "Detecting installations": "설치 항목 감지 중", "Detecting…": "감지 중…", "Different tool window background": "도구 창 배경을 다르게 표시", - "Direction": "방향", "Directory": "디렉터리", "Staging State": "스테이징 상태", "Staged Changes": "스테이징된 변경 사항", diff --git a/src/platform/locales/text/pl.json b/src/platform/locales/text/pl.json index 987f9fe1f7..e2f8cbce10 100644 --- a/src/platform/locales/text/pl.json +++ b/src/platform/locales/text/pl.json @@ -671,7 +671,6 @@ "Detecting…": "Wykrywanie…", "Diff": "Różnice (Diff)", "Different tool window background": "Inne tło okien narzędziowych", - "Direction": "Kierunek", "Directory": "Katalog", "Staging State": "Stan poczekalni (Staging)", "Staged Changes": "Zmiany w poczekalni (Staged)", diff --git a/src/platform/locales/text/pt.json b/src/platform/locales/text/pt.json index e3a2b804e6..f037ffa181 100644 --- a/src/platform/locales/text/pt.json +++ b/src/platform/locales/text/pt.json @@ -671,7 +671,6 @@ "Detecting…": "Detectando…", "Diff": "Diff", "Different tool window background": "Plano de fundo diferente para janelas de ferramentas", - "Direction": "Direção", "Directory": "Diretório", "Staging State": "Estado de staging", "Staged Changes": "Alterações no stage", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 22f76987c7..4bc38b273c 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -1,7 +1,12 @@ { "Inspection details": "检查详情", "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": "调整文件类型窗格大小", @@ -1273,7 +1278,6 @@ "Detecting…": "正在检测…", "Diff": "差异", "Different tool window background": "不同的工具窗口背景", - "Direction": "方向", "Directory": "目录", "Staging State": "暂存状态", "Staged Changes": "已暂存的更改", @@ -3350,6 +3354,7 @@ "Hold Shift to Debug, F4 to edit, Delete to remove": "按住 Shift 调试,F4 编辑,Delete 删除", "Hold Shift to Run, F4 to edit, Delete to remove": "按住 Shift 运行,F4 编辑,Delete 删除", "Send EOF": "发送 EOF", + "Fold Lines Like This": "折叠与此类似的行", "Collapse folded lines": "折叠行", "Close Tool Window Tab": "关闭工具窗口标签页", "No open files": "没有打开的文件", @@ -9073,5 +9078,9 @@ "Resize shelf panes": "调整搁置记录和文件窗格大小", "Database and schema": "数据库和 schema", "Shelve Silently": "静默搁置", - "Unshelve Silently": "静默取消搁置" + "Unshelve Silently": "静默取消搁置", + "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 用户名" }