Compare commits

...
Author SHA1 Message Date
l0ng-ai 4762babfdd Merge remote-tracking branch 'origin/main' into ux/debug-stack-layout 2026-11-20 11:13:23 +08:00
l0ng-ai abd55f88b5 fix(search): make the editor switcher fit the workbench (#4660)
The editor switcher fits the workbench. Verified with e2e switcherLayout, search vitest and typecheck.
2026-11-20 11:13:20 +08:00
l0ng-ai dac4db0994 fix(settings): separate file type associations from ignore rules (#4657)
File Types settings separate file type associations from ignore rules. Verified with e2e fileTypesLayout, settings/locales vitest and typecheck.
2026-11-20 11:13:08 +08:00
l0ng-ai 4fa1e9cbbe Merge remote-tracking branch 'origin/main' into ux/debug-stack-layout 2026-11-20 11:11:23 +08:00
Deng Liuanddengliu b0d0ea868b feat(agents): configure GitHub Copilot authentication account (#4663)
Copilot launched with whichever GitHub CLI account was active outside the IDE. GitHub Copilot's settings get a GitHub account field: at launch the IDE asks gh for that account's token and passes it as COPILOT_GITHUB_TOKEN, without storing it; the account (not a credential) is kept with the agent's settings and scopes the catalog cache. Also adds the field's text to the en/zh catalog. Verified with cargo test -p ide-agent, clippy, agents and locale vitest, typecheck, and the field in Settings › Agents › Coding Agents.

Co-authored-by: dengliu <[email protected]>
2026-11-20 11:11:05 +08:00
l0ng-ai f41d2f8bf0 fix(debugger): keep call stack locations visible in narrow docks 2026-11-20 11:08:12 +08:00
Deng Liuanddengliu d86ff872af fix(agents): recover model controls for fallback sessions (#4662)
A session whose agent fell back to a configuration without a model option kept a stale model label and offered no way to pick another model. The composer rebuilds the model control from the provider's catalog and set_config accepts a model from that catalog, switching through the same path as other discovered models. Verified with cargo test -p ide-agent, clippy, agents vitest and typecheck.

Co-authored-by: dengliu <[email protected]>
2026-11-20 11:07:37 +08:00
Deng Liuanddengliu dbef3cdc96 fix(agents): support Auto-only Copilot catalogs (#4661)
Copilot can return an enabled Auto tier with an empty direct-model list; the catalog parser treated that as an empty catalog and forced the fallback transport. An enabled Auto tier now yields the auto model. Verified with cargo test -p ide-agent copilot and clippy.

Co-authored-by: dengliu <[email protected]>
2026-11-20 11:06:32 +08:00
C3B6 c483c3b76f perf(http-client): limit cached response details to four (#4659)
The HTTP Client kept every exchange's full request and response in memory for the whole session, even after its row left the backend's 100-entry history. The history list is capped at 100 like the backend, and only the four most recently viewed exchanges keep their details; older rows reload theirs from the saved history (which stores the full exchange) when selected. Verified with http-client vitest and typecheck.

Co-authored-by: 0xC3B6 <[email protected]>
2026-11-20 11:05:24 +08:00
HEOJUNFO da79a73def fix(http-client): keep the whole value of a Spring params/headers condition (#4666)
Spring params/headers conditions were split with split("=", 2), which drops everything after a second '='; only the first '=' divides name and value now, as in Spring. Verified with http-client vitest.

Co-authored-by: HEOJUNFO <[email protected]>
2026-11-20 11:04:44 +08:00
akshathayadav378-boopandakshathayadav378-boop 2cc54b35f6 test(markdown): allow large render test to finish (#4664)
The large Markdown re-render test renders plugins/README.md repeatedly and can exceed Vitest's default 5 s timeout under full-suite load; it gets a 20 s timeout like other heavy tests.

Co-authored-by: akshathayadav378-boop <[email protected]>
2026-11-20 11:04:36 +08:00
zhzhsxandzhzhsx 097221c1b3 fix(editor): colour Go's default like the other keywords (#4654)
@lezer/go tags every keyword except default, and gopls sends no keyword semantic tokens, so default in a Go switch/select rendered as plain text. Go now gets an extra style tag for default. Verified with editor cm vitest and typecheck.

Co-authored-by: zhzhsx <[email protected]>
2026-11-20 10:25:05 +08:00
l0ng-ai 1bb4ffe6b2 Keep the color scheme preview visible while editing (#4653)
The color scheme preview stays visible while editing scheme options. Verified with e2e colorSchemeLayout/editorFontLayout, settings and platform vitest and typecheck; main merged in (locale conflict resolved).
2026-11-20 10:22:05 +08:00
l0ng-ai 51e525336b Keep Welcome project search and actions in one row (#4652)
Welcome project search and actions stay in one row. Verified with e2e welcomeProjectsLayout, full vitest and typecheck.
2026-11-20 10:21:06 +08:00
l0ng-ai 1b47bc2c14 Keep the editor font preview visible while changing settings (#4649)
The editor font preview stays visible while changing font settings. Verified with e2e editorFontLayout, full vitest and typecheck.
2026-11-20 10:20:59 +08:00
l0ng-ai aa1326496b Show both commit ranges in Git branch comparisons (#4642)
Git branch comparison shows both commit ranges side by side in resizable panes. Verified with e2e branchCompareLayout, full vitest and typecheck.
2026-11-20 10:20:51 +08:00
leenandleen2175 7850429174 fix(vcs): open existing worktrees over SSH (#4465)
Opening a linked worktree from an SSH or WSL project treated the remote directory as a local path. The Worktrees toolbar, row double-click and the checkout prompt's Open now go through openWorktree, which reuses the session's remote target and opens a remote window; local projects are unchanged. Verified with vcs and remote-dev vitest and typecheck on macOS (local path); the SSH flow was verified by the author in the native Linux app.

Co-authored-by: leen2175 <[email protected]>
2026-11-20 10:17:09 +08:00
Mansur Akhmadiandmansur-akhmadi 3dd5c75fa0 feat(debugger): Remove All Watches in the Variables view's context menu (#4647)
A watch row's context menu in the Variables view gets Remove All Watches next to Remove Watch; it empties the project's stored watch list. Verified with debugger and locale vitest and typecheck; main merged in (locale conflict resolved).

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-20 10:15:56 +08:00
Mansur Akhmadiandmansur-akhmadi 36ecb53159 feat(run): Fold Lines Like This in the Run console's context menu (#4635)
The Run console's context menu gets Fold Lines Like This: it opens Settings › Build, Execution, Deployment › Console with the selected single-line text, or the right-clicked line, added to the fold patterns. Verified with full vitest, typecheck, and in the app (pattern added, Cancel leaves settings unchanged).

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-20 10:15:00 +08:00
006405ca11 fix(remote): restore WSL projects onto a live connection (#4103)
* fix(remote): restore WSL projects onto a live connection

A reopened WSL window kept sending commands to a remote host it was no
longer connected to. Remember the remote location, and do not drop a
connection that a later open or a superseded attempt still needs.

Co-authored-by: Cursor <[email protected]>

* Use ? for the last remote location prefix (clippy::question_mark)

* fix(remote): save window session after connecting

---------

Co-authored-by: 胡长贵 <[email protected]>
Co-authored-by: Cursor <[email protected]>
Co-authored-by: l0ng-ai <[email protected]>
2026-11-20 10:12:35 +08:00
Mollo-i 40b95650cf fix(maven): custom project.* properties and bare built-in shorthands resolve to their definition (#4651)
Every project.* name was treated as a Maven built-in, so custom properties such as project.port never navigated, and the bare built-in shorthand (@artifactId@) did not either. Non-coordinate project.* names now fall through to the <properties> lookup along the parent chain, and the bare shorthand resolves to the pom's own coordinate unless a custom property of that name exists. Verified with cargo test -p ide-build (maven tests pass; the one failing Go workspace test is unrelated to this change and fails from the local go toolchain) and clippy.

Co-authored-by: Greenker <[email protected]>
2026-11-20 10:08:09 +08:00
zhzhsxandzhzhsx 0a571c0b4d fix(libraries): keep a Go module inside the project editable (#4639)
go list -m reports a replace target's own folder as the module's Dir, so a local replacement inside the project was registered as a read-only library root. Modules whose source sits inside the opened project (outside vendor/) are no longer library roots. Also passes the project root in the zig_groups test added on main. Verified with cargo test -p ide-sdk (new go_modules test passes; three go command tests fail the same way without this change, from the local go shim) and clippy.

Co-authored-by: zhzhsx <[email protected]>
2026-11-20 10:06:44 +08:00
l0ng-ai b1f88bf79c Separate shelves from the files they contain (#4640)
Shelf tool window separates the list of shelves from the files of the selected shelf in resizable panes. Verified with e2e shelfLayout, full vitest and typecheck.
2026-11-20 09:21:25 +08:00
82 changed files with 3121 additions and 597 deletions

No files matched your search

+1 -1
View File
@@ -51,7 +51,7 @@ async fn run_once(
move || launch.resolve_for_launch_with_copilot_env(&root, strip_ambient)
})
.await
.map_err(|e| e.to_string())?;
.map_err(|e| e.to_string())??;
let cwd = dunce::canonicalize(&root).unwrap_or(root);
let updates = Arc::new(DiscoveryUpdates { provider: spec.id.clone(), ..Default::default() });
let client = Dialect::wrap(updates.clone());
+28 -11
View File
@@ -132,6 +132,7 @@ pub type McpExecutableFn = dyn Fn() -> Option<PathBuf> + Send + Sync;
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
struct CopilotBinaryKey {
command: String,
github_account: Option<String>,
modified: Option<std::time::SystemTime>,
len: Option<u64>,
}
@@ -193,6 +194,7 @@ impl Shared {
let metadata = std::fs::metadata(&executable).ok();
CopilotBinaryKey {
command: executable.to_string_lossy().into_owned(),
github_account: provider::copilot_github_account(&spec.env),
modified: metadata.as_ref().and_then(|m| m.modified().ok()),
len: metadata.as_ref().map(std::fs::Metadata::len),
}
@@ -1126,6 +1128,16 @@ impl AgentManager {
/// Changes a session setting (model, mode…): right away when the agent runs, else when it next starts.
pub async fn set_config(&self, id: &str, option: &str, value: String) -> IdeResult<()> {
let task = self.task(id)?;
let provider = task.state.lock().task.provider.clone();
let discovered = self
.shared
.paths
.catalogs
.cached(&self.shared, &provider)
.config
.iter()
.find(|o| o.id == option && o.category.as_deref() == Some("model"))
.cloned();
let (target, change) = {
let mut s = task.state.lock();
let busy = s.busy;
@@ -1146,17 +1158,19 @@ impl AgentManager {
task.emit_task();
return Ok(());
}
let target = s
.task
.config
.iter()
.find(|o| o.id == option)
.ok_or_else(|| IdeError::not_found("no such setting"))?
.clone();
let session_target = s.task.config.iter().find(|o| o.id == option).cloned();
let recovered_model = session_target.is_none();
let target = match session_target {
Some(target) => target,
None if discovered.is_some() => discovered.unwrap(),
None => return Err(IdeError::not_found("no such setting")),
};
if s.pending_model.is_some() && config::is_per_model_option(&target) {
return Err(IdeError::invalid("This setting is not available on the selected model"));
}
if !target.values.iter().any(|v| v.value == value) {
if recovered_model {
(target, None)
} else if !target.values.iter().any(|v| v.value == value) {
if target.category.as_deref() != Some("model") {
return Err(IdeError::invalid(format!("{} has no value {value}", target.name)));
}
@@ -2799,9 +2813,12 @@ impl Task {
pending_model: Option<&PendingModel>,
) -> Result<Live, SessionOpenError> {
let launch_cwd = cwd.to_path_buf();
let mut spec = tokio::task::spawn_blocking(move || spec.resolve_for_launch(&launch_cwd))
.await
.map_err(|e| SessionOpenError { message: e.to_string(), allow_acp_fallback: false })?;
let mut spec = tokio::task::spawn_blocking(move || {
spec.resolve_for_launch_with_copilot_env(&launch_cwd, provider::prefer_stored_copilot_auth())
})
.await
.map_err(|e| SessionOpenError { message: e.to_string(), allow_acp_fallback: false })?
.map_err(|e| SessionOpenError { message: e, allow_acp_fallback: false })?;
if spec.driver == provider::Driver::Acp && provider::is_copilot_provider(provider_id) {
let mcp_overrides = self.state.lock().task.mcp_overrides.clone();
for name in self.shared.mcp_servers_off_for_session(provider_id, &mcp_overrides) {
+2 -1
View File
@@ -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(
+14 -2
View File
@@ -312,7 +312,7 @@ impl Settings {
}
/// Parses `models.list` + optional `models.listTokenPriceUnits` into catalog entries,
/// prepending `"auto"` when not already in the list.
/// prepending `"auto"` when direct models are present or Copilot advertises an enabled Auto tier.
pub(super) fn parse_catalog(list: &Value, price_units: Option<&Value>) -> Vec<ModelEntry> {
let units = parse_price_units(price_units);
let raw = list
@@ -322,7 +322,7 @@ pub(super) fn parse_catalog(list: &Value, price_units: Option<&Value>) -> Vec<Mo
.map(Vec::as_slice)
.unwrap_or_default();
let mut out = Vec::new();
if !raw.iter().any(|m| str_of(m, "id") == Some("auto")) && !raw.is_empty() {
if !raw.iter().any(|m| str_of(m, "id") == Some("auto")) && (!raw.is_empty() || auto_model_available(list)) {
out.push(ModelEntry {
id: "auto".into(),
name: "Auto".into(),
@@ -344,6 +344,18 @@ pub(super) fn parse_catalog(list: &Value, price_units: Option<&Value>) -> Vec<Mo
out
}
fn auto_model_available(list: &Value) -> bool {
let Some(auto) = list.get("auto") else { return false };
if auto.get("enabled").or_else(|| auto.pointer("/status/enabled")).and_then(Value::as_bool) == Some(false) {
return false;
}
let Some(tiers) = auto.get("tiers").and_then(Value::as_array) else { return auto.is_object() };
tiers.is_empty()
|| tiers.iter().any(|tier| {
tier.get("enabled").or_else(|| tier.pointer("/status/enabled")).and_then(Value::as_bool) != Some(false)
})
}
fn parse_model(m: &Value, units: &HashMap<String, PriceUnit>) -> Option<ModelEntry> {
let id = str_of(m, "id")?.to_owned();
if m.get("model_picker_enabled").and_then(Value::as_bool) == Some(false)
@@ -110,6 +110,72 @@ fn sample_price_units() -> Value {
})
}
#[test]
fn parses_an_enabled_auto_only_catalog() {
let list = json!({
"models": [],
"auto": {
"defaultTier": "balance",
"tiers": [
{
"id": "balance",
"displayName": "Standard",
"type": "auto",
"fusionTier": "standard",
"status": { "enabled": true, "pickerVisible": true }
},
{
"id": "hydrafusion",
"displayName": "High",
"type": "fusion",
"fusionTier": "high",
"status": {
"enabled": false,
"pickerVisible": true,
"reason": "user_not_eligible"
}
},
{
"id": "fast",
"displayName": "Fast",
"type": "auto",
"status": { "enabled": true, "pickerVisible": false }
}
],
"providerId": "copilot"
},
"imageModels": []
});
let catalog = models::parse_catalog(&list, None);
assert_eq!(catalog.iter().map(|m| m.id.as_str()).collect::<Vec<_>>(), ["auto"]);
assert_eq!(Settings::new(&catalog, &UserDefaults::default()).model, "auto");
let options =
config::parse_options(&models::config_options(&catalog, &Settings::new(&catalog, &UserDefaults::default())));
let model = options.iter().find(|option| option.id == MODEL).unwrap();
assert_eq!(model.current.as_deref(), Some("auto"));
assert_eq!(model.values.iter().map(|value| value.value.as_str()).collect::<Vec<_>>(), ["auto"]);
}
#[test]
fn rejects_an_auto_only_catalog_when_every_tier_is_disabled() {
let list = json!({
"models": [],
"auto": {
"defaultTier": "balance",
"tiers": [
{
"id": "balance",
"status": { "enabled": false, "pickerVisible": true }
}
]
}
});
assert!(models::parse_catalog(&list, None).is_empty());
}
#[test]
fn parses_tiered_context_windows_pricing_and_uses_copilots_own_defaults() {
let catalog = models::parse_catalog(&sample_models_list(), Some(&sample_price_units()));
+129 -2
View File
@@ -9,6 +9,8 @@ use serde_json::Value;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
pub(crate) const COPILOT_GITHUB_ACCOUNT_ENV: &str = "OPENIDEA_COPILOT_GITHUB_ACCOUNT";
/// The protocol an agent speaks. Native ones run behind an in-process ACP endpoint
/// (`native`), so tasks see every agent as ACP and read features from its capabilities.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
@@ -138,15 +140,31 @@ impl ProviderSpec {
/// Resolve once before connecting, so authentication guidance names that same install.
pub(crate) fn resolve_for_launch(self, cwd: &Path) -> Self {
let strip = prefer_stored_copilot_auth();
self.resolve_for_launch_with_copilot_env(cwd, strip)
self.resolve_for_launch_base(cwd, strip)
}
pub(crate) fn resolve_for_launch_with_copilot_env(mut self, cwd: &Path, strip_ambient_tokens: bool) -> Self {
pub(crate) fn resolve_for_launch_with_copilot_env(
self,
cwd: &Path,
strip_ambient_tokens: bool,
) -> Result<Self, String> {
let account = is_copilot_provider(&self.id).then(|| copilot_github_account(&self.env)).flatten();
let mut resolved = self.resolve_for_launch_base(cwd, strip_ambient_tokens || account.is_some());
if let Some(account) = account {
let token = github_token_for_account(&account)?;
resolved.env.retain(|(name, _)| !AMBIENT_COPILOT_AUTH_VARS.contains(&name.as_str()));
resolved.env.push(("COPILOT_GITHUB_TOKEN".into(), token));
}
Ok(resolved)
}
fn resolve_for_launch_base(mut self, cwd: &Path, strip_ambient_tokens: bool) -> Self {
if self.driver != Driver::Acp {
self.command = crate::native::newest_install(&self.command);
}
if is_copilot_provider(&self.id) {
self.env = sanitized_copilot_env(&self.env, strip_ambient_tokens);
self.env.retain(|(name, _)| name != COPILOT_GITHUB_ACCOUNT_ENV);
}
let program = ide_jsonrpc::resolve_spawn_program(&self.command, &self.env);
self.command =
@@ -164,6 +182,50 @@ pub(crate) fn is_copilot_provider(id: &str) -> bool {
id == "copilot" || id.starts_with("copilot-")
}
pub(crate) fn copilot_github_account(env: &[(String, String)]) -> Option<String> {
env.iter()
.rev()
.find(|(name, _)| name == COPILOT_GITHUB_ACCOUNT_ENV)
.map(|(_, value)| value.trim())
.filter(|value| !value.is_empty())
.map(str::to_owned)
}
fn github_token_for_account(account: &str) -> Result<String, String> {
let path = ide_core::process::shell_env()
.find(|(name, _)| name == "PATH")
.map(|(_, value)| value)
.or_else(|| ide_core::process::host_var_os("PATH"));
let program = path
.as_deref()
.and_then(|path| ide_core::process::find_executable("gh", path))
.ok_or_else(|| "GitHub CLI (`gh`) is required to select a Copilot GitHub account".to_owned())?;
let mut command = std::process::Command::new(program);
command.args(["auth", "token", "--hostname", "github.com", "--user", account]).envs(ide_core::process::shell_env());
for name in AMBIENT_COPILOT_AUTH_VARS {
command.env_remove(name);
}
let output = command
.output()
.map_err(|error| format!("Couldn't read GitHub authentication for account {account}: {error}"))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
let detail = stderr.trim();
return Err(if detail.is_empty() {
format!("GitHub CLI has no authenticated account named {account}")
} else {
format!("Couldn't use GitHub account {account}: {detail}")
});
}
let token = String::from_utf8(output.stdout)
.map_err(|_| format!("GitHub CLI returned a non-text token for account {account}"))?;
let token = token.trim();
if token.is_empty() {
return Err(format!("GitHub CLI returned no token for account {account}"));
}
Ok(token.to_owned())
}
pub(crate) fn prefer_stored_copilot_auth() -> bool {
PREFER_STORED_COPILOT_AUTH.load(std::sync::atomic::Ordering::Acquire)
}
@@ -339,6 +401,31 @@ pub(crate) fn set_builtin_env(
id: &str,
env: BTreeMap<String, String>,
) -> IdeResult<()> {
if id == "copilot" {
let file = custom_dir.join("copilot.toml");
if file.try_exists()?
&& let mut agent = CustomAgent::read_with(&file, id, secrets).map_err(IdeError::invalid)?
&& agent.registry.is_some()
{
let existing = agent.env.clone();
let mut existing_launch_env = existing.clone();
let mut next_launch_env = env.clone();
existing_launch_env.remove(COPILOT_GITHUB_ACCOUNT_ENV);
next_launch_env.remove(COPILOT_GITHUB_ACCOUNT_ENV);
if existing_launch_env != next_launch_env {
return Err(IdeError::invalid(format!("{id} is installed from the ACP Registry")));
}
match env.get(COPILOT_GITHUB_ACCOUNT_ENV).filter(|value| !value.trim().is_empty()) {
Some(account) => {
agent.env.insert(COPILOT_GITHUB_ACCOUNT_ENV.into(), account.trim().into());
}
None => {
agent.env.remove(COPILOT_GITHUB_ACCOUNT_ENV);
}
}
return agent.write(&file).map_err(Into::into);
}
}
update_builtin(custom_dir, secrets, id, |agent, _| agent.env = env)
}
@@ -955,6 +1042,46 @@ mod tests {
set_builtin_env(dir.path(), None, "not-a-builtin", env).unwrap_err();
}
#[test]
fn registry_copilot_allows_only_the_github_account_override() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("copilot.toml");
CustomAgent {
name: Some("GitHub Copilot".into()),
driver: Driver::Acp,
command: "/tools/copilot".into(),
args: vec!["--acp".into()],
env: BTreeMap::from([("REGISTRY_SETTING".into(), "kept".into())]),
registry: Some(RegistryRef { id: "copilot".into(), version: "1.0.0".into() }),
}
.write(&file)
.unwrap();
set_builtin_env(
dir.path(),
None,
"copilot",
BTreeMap::from([
("REGISTRY_SETTING".into(), "kept".into()),
(COPILOT_GITHUB_ACCOUNT_ENV.into(), "dengliu_microsoft".into()),
]),
)
.unwrap();
let spec = load(Some(dir.path()), None).into_iter().find(|spec| spec.id == "copilot").unwrap();
assert_eq!(copilot_github_account(&spec.env).as_deref(), Some("dengliu_microsoft"));
set_builtin_env(dir.path(), None, "copilot", BTreeMap::from([("REGISTRY_SETTING".into(), "changed".into())]))
.unwrap_err();
}
#[test]
fn launch_metadata_never_passes_the_github_account_control_to_copilot() {
let mut spec = builtin_spec("copilot").unwrap();
spec.env.push((COPILOT_GITHUB_ACCOUNT_ENV.into(), "dengliu_microsoft".into()));
let resolved = spec.resolve_for_launch(Path::new("."));
assert!(resolved.env.iter().all(|(name, _)| name != COPILOT_GITHUB_ACCOUNT_ENV));
}
#[test]
fn acp_adapters_of_native_agents_are_unlisted_until_customized() {
let dir = tempfile::tempdir().unwrap();
+8
View File
@@ -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,
+50
View File
@@ -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();
+88 -11
View File
@@ -2020,11 +2020,25 @@ fn property_target(text: &str, path: &Path, name: &str, local_repo: Option<PathB
label: name.clone(),
});
}
// Built-in coordinates: the POM's own element, else the first ancestor declaring one.
if let Some(key) = name.strip_prefix("project.") {
if !matches!(key, "groupId" | "artifactId" | "version" | "packaging" | "name") {
return None; // `project.basedir`, `project.build.directory`… have no element.
// Built-in coordinates (`project.artifactId`, and the bare `@artifactId@`
// shorthand resource filtering resolves the same way): the POM's own element,
// else the first ancestor declaring one. Any other name under `project.` is a
// custom property (`project.port`, `project.servlet.path`), which the
// `<properties>` lookup below resolves.
let built_in = match name.strip_prefix("project.") {
Some(key) if matches!(key, "groupId" | "artifactId" | "version" | "packaging" | "name") => Some(key),
// `project.basedir`, `project.build.directory`… have no element of their own.
Some(_) => None,
None if matches!(name.as_str(), "groupId" | "artifactId" | "version" | "packaging" | "name") => {
// The bare shorthand of a built-in; a custom property of that name wins.
if let Some(found) = properties_target(&chain, &name, &resolver) {
return Some(found);
}
Some(name.as_str())
}
None => None,
};
if let Some(key) = built_in {
for (p, text) in &chain {
let Some(root) = xml::parse(text).filter(|e| e.name == "project") else { continue };
let Some(e) = root.child(key).filter(|e| !e.text.trim().is_empty()) else { continue };
@@ -2037,30 +2051,34 @@ fn property_target(text: &str, path: &Path, name: &str, local_repo: Option<PathB
}
return None;
}
// A property of `<properties>`: the first POM of the chain (child-first) that
// declares it, at project level or in an active profile.
for (p, text) in &chain {
properties_target(&chain, &name, &resolver)
}
/// A property of `<properties>`: the first POM of the chain (child-first) that
/// declares it, at project level or in an active profile.
fn properties_target(chain: &[(PathBuf, String)], name: &str, resolver: &Resolver) -> Option<PomGoto> {
for (p, text) in chain {
let Some(root) = xml::parse(text).filter(|e| e.name == "project") else { continue };
let active: Vec<String> = parse_pom(text)
.map(|pom| resolver.active(&pom.profiles).map(|pr| pr.id.clone()).collect())
.unwrap_or_default();
// Project level first, then the first active profile declaring the property.
let e = root.child("properties").and_then(|props| props.child(&name)).or_else(|| {
let e = root.child("properties").and_then(|props| props.child(name)).or_else(|| {
root.list("profiles", "profile")
.into_iter()
.find(|profile| {
active.contains(&profile.child("id").map(|id| id.text.trim().to_owned()).unwrap_or_default())
&& profile.child("properties").and_then(|props| props.child(&name)).is_some()
&& profile.child("properties").and_then(|props| props.child(name)).is_some()
})?
.child("properties")?
.child(&name)
.child(name)
});
if let Some(e) = e {
return Some(PomGoto {
path: p.clone(),
range: range_of(text, e),
kind: PomGotoKind::Property,
label: name.clone(),
label: name.to_owned(),
});
}
}
@@ -3086,6 +3104,65 @@ mod tests {
assert_eq!(goto.range, Range::new(pos_at(&text, from), pos_at(&text, to)));
}
#[test]
fn a_custom_project_property_is_found_like_a_plain_one() {
let text = format!(
r#"{CHILD_HEADER}<properties>
<project.port>8001</project.port>
</properties>
<dependencies>
<dependency>
<groupId>com.example</groupId>
<artifactId>lib</artifactId>
<version>${{project.port}}</version>
</dependency>
</dependencies>
</project>"#
);
let path = Path::new("/tmp/pom.xml");
let goto = goto_declaration(&text, path, at(&text, "${project.port}"), None).unwrap();
assert_eq!(goto.kind, PomGotoKind::Property);
assert_eq!(goto.label, "project.port");
assert_eq!(goto.path, path);
let from = text.find("<project.port>").unwrap();
let to = text.find("</project.port>").unwrap() + "</project.port>".len();
assert_eq!(goto.range, Range::new(pos_at(&text, from), pos_at(&text, to)));
// `${project.basedir}` has no element and no custom property: still nothing.
let basedir = text.replace("${project.port}", "${project.basedir}");
assert_eq!(goto_declaration(&basedir, path, at(&basedir, "${project.basedir}"), None), None);
}
#[test]
fn the_bare_builtin_shorthand_resolves_to_the_coordinate_and_a_custom_property_wins() {
let text = format!(
r#"{CHILD_HEADER}<artifactId>app</artifactId>
<dependencies>
<dependency>
<groupId>com.example</groupId>
<artifactId>lib</artifactId>
</dependency>
</dependencies>
<properties>
<groupId>custom</groupId>
</properties>
<description>${{artifactId}}-${{groupId}} docs</description>
</project>"#
);
let path = Path::new("/tmp/pom.xml");
// `@artifactId@` in a filtered resource resolves to the own coordinate.
let goto = goto_declaration(&text, path, at(&text, "${artifactId}"), None).unwrap();
assert_eq!(goto.label, "artifactId");
let from = text.find("<artifactId>app").unwrap();
assert_eq!(goto.range.start, pos_at(&text, from));
// A custom property of the bare name wins over the shorthand. The click
// sits inside the reference: the second one's `$` is behind the first's
// closing `}`, which `property_ref_at` does not take for the `$` itself.
let goto = goto_declaration(&text, path, at(&text, "groupId} docs"), None).unwrap();
assert_eq!(goto.label, "groupId");
let from = text.find("<groupId>custom").unwrap();
assert_eq!(goto.range.start, pos_at(&text, from));
}
#[test]
fn an_inherited_property_reference_finds_its_definition_in_the_parent_pom() {
let tmp = tempfile::tempdir().unwrap();
+25 -12
View File
@@ -84,7 +84,7 @@ pub fn project_libraries_stream(
cancel: &CancellationToken,
on_groups: &(dyn Fn(Vec<LibraryGroup>) + Sync),
) -> Vec<LibraryGroup> {
type Detect = fn(&Path, &Settings, &CancellationToken) -> Vec<LibraryGroup>;
type Detect = fn(&Path, &Path, &Settings, &CancellationToken) -> Vec<LibraryGroup>;
let detectors: [Detect; 6] = [python_groups, jdk_groups, node_groups, go_groups, ruby_groups, zig_groups];
let roots = library_project_roots(root, cancel);
let settings = module_settings(root, settings);
@@ -99,7 +99,7 @@ pub fn project_libraries_stream(
if cancel.is_cancelled() {
break;
}
let batch = d(dir, settings, cancel);
let batch = d(dir, root, settings, cancel);
if !cancel.is_cancelled() && !batch.is_empty() {
on_groups(batch.clone());
groups.extend(batch);
@@ -384,7 +384,7 @@ fn tool(bin: Option<PathBuf>, name: &str) -> Option<PathBuf> {
// ------------------------------------------------------------------ python
fn python_groups(root: &Path, s: &Settings, cancel: &CancellationToken) -> Vec<LibraryGroup> {
fn python_groups(root: &Path, _project: &Path, s: &Settings, cancel: &CancellationToken) -> Vec<LibraryGroup> {
let Some(python) = crate::apply::python_interpreter(root, s) else { return Vec::new() };
let mut files = vec![python.clone()];
files.extend(crate::venv_of(&python).map(|v| v.join("pyvenv.cfg")));
@@ -436,7 +436,7 @@ pub(crate) fn named_roots(roots: Vec<(String, PathBuf)>) -> Vec<LibraryRoot> {
// ------------------------------------------------------------------ ruby
fn ruby_groups(root: &Path, s: &Settings, cancel: &CancellationToken) -> Vec<LibraryGroup> {
fn ruby_groups(root: &Path, _project: &Path, s: &Settings, cancel: &CancellationToken) -> Vec<LibraryGroup> {
let Some(files) = manifests(root, RUBY_MANIFESTS) else { return Vec::new() };
if !root.join("Gemfile").is_file() && !root.join(".ruby-version").is_file() {
return Vec::new();
@@ -454,7 +454,7 @@ fn ruby_groups(root: &Path, s: &Settings, cancel: &CancellationToken) -> Vec<Lib
// ------------------------------------------------------------------ jdk
fn jdk_groups(root: &Path, s: &Settings, cancel: &CancellationToken) -> Vec<LibraryGroup> {
fn jdk_groups(root: &Path, _project: &Path, s: &Settings, cancel: &CancellationToken) -> Vec<LibraryGroup> {
// Java modules without a build manifest carry `.classpath` / `.project` /
// `.idea` instead; a configured JDK or declared source roots mark one too.
let files = match manifests(root, JAVA_MANIFESTS) {
@@ -731,7 +731,7 @@ pub(crate) fn gradle_jar(home: &Path, d: &BuildDependency) -> Option<PathBuf> {
// ------------------------------------------------------------------ node
fn node_groups(root: &Path, s: &Settings, _cancel: &CancellationToken) -> Vec<LibraryGroup> {
fn node_groups(root: &Path, _project: &Path, s: &Settings, _cancel: &CancellationToken) -> Vec<LibraryGroup> {
if !root.join("package.json").is_file() {
return Vec::new();
}
@@ -907,7 +907,7 @@ pub(crate) fn parse_cargo_metadata(json: &str) -> Option<Vec<(String, PathBuf)>>
// ------------------------------------------------------------------ go
fn go_groups(root: &Path, s: &Settings, cancel: &CancellationToken) -> Vec<LibraryGroup> {
fn go_groups(root: &Path, project: &Path, s: &Settings, cancel: &CancellationToken) -> Vec<LibraryGroup> {
let Some(mut files) = manifests(root, GO_MANIFESTS) else { return Vec::new() };
if !root.join("go.mod").is_file() && !root.join("go.work").is_file() {
return Vec::new();
@@ -958,7 +958,7 @@ fn go_groups(root: &Path, s: &Settings, cancel: &CancellationToken) -> Vec<Libra
} else if let Some(text) =
query_in_cancellable(&go, &["list", "-m", "-e", "-json", "all"], root, &env, GRAPH_TIMEOUT, cancel)
{
out.extend(group("Go Modules", "goModules", named_roots(parse_go_modules(&text))));
out.extend(group("Go Modules", "goModules", named_roots(parse_go_modules(&text, project))));
}
out
})
@@ -978,8 +978,19 @@ fn vendor_roots(vendor: &Path, text: &str) -> Vec<(String, PathBuf)> {
.collect()
}
/// `(path@version, dir)` of the downloaded non-main modules in `go list -m -json` output.
pub(crate) fn parse_go_modules(text: &str) -> Vec<(String, PathBuf)> {
/// True when `path` is source the user owns: inside `project` and not a `vendor` copy.
fn is_project_source(project: &Path, path: &Path) -> bool {
let project = project.canonicalize().unwrap_or_else(|_| project.to_path_buf());
let path = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
let Ok(relative) = path.strip_prefix(&project) else { return false };
!relative.components().any(|component| component.as_os_str() == "vendor")
}
/// `(path@version, dir)` of the modules that are libraries: everything whose source is
/// outside the opened project. Source inside it is the user's own code — the target of a
/// `replace`, say — and stays editable; a `vendor` copy is the exception, checked in and
/// kept read-only.
pub(crate) fn parse_go_modules(text: &str, project: &Path) -> Vec<(String, PathBuf)> {
#[derive(Deserialize)]
#[serde(rename_all = "PascalCase")]
struct Module {
@@ -993,6 +1004,8 @@ pub(crate) fn parse_go_modules(text: &str) -> Vec<(String, PathBuf)> {
.into_iter::<Module>()
.map_while(Result::ok)
.filter(|m| !m.main)
// A module whose source sits in the project is the user's own code, not a library.
.filter(|m| m.dir.as_deref().is_none_or(|dir| !is_project_source(project, dir)))
.filter_map(|m| {
let name = match &m.version {
Some(v) => format!("{}@{v}", m.path),
@@ -1005,7 +1018,7 @@ pub(crate) fn parse_go_modules(text: &str) -> Vec<(String, PathBuf)> {
// ------------------------------------------------------------------ zig
fn zig_groups(root: &Path, s: &Settings, cancel: &CancellationToken) -> Vec<LibraryGroup> {
fn zig_groups(root: &Path, _project: &Path, s: &Settings, cancel: &CancellationToken) -> Vec<LibraryGroup> {
let Some(files) = manifests(root, ZIG_MANIFESTS) else { return Vec::new() };
let Some(zig) = tool(crate::apply::zig_bin(root, s), "zig") else { return Vec::new() };
cached_cancellable(root, "zig", zig.display().to_string(), &files, cancel, || {
@@ -1574,7 +1587,7 @@ mod zig_tests {
std::fs::set_permissions(&zig, std::fs::Permissions::from_mode(0o755)).unwrap();
let mut settings = Settings::default();
settings.languages.zig.zig = "tools".into();
let groups = zig_groups(root, &settings, &CancellationToken::new());
let groups = zig_groups(root, root, &settings, &CancellationToken::new());
let summary: Vec<(&str, &str, Vec<&str>)> = groups
.iter()
.map(|g| (g.name.as_str(), g.kind.as_str(), g.roots.iter().map(|r| r.name.as_str()).collect()))
+30 -1
View File
@@ -1875,7 +1875,7 @@ fn go_modules_skip_the_main_module_and_missing_downloads() {
{"Path":"golang.org/x/text","Version":"v0.14.0","Dir":"/gopath/pkg/mod/golang.org/x/[email protected]"}
{"Path":"example.com/missing","Version":"v1.0.0","Error":{"Err":"module lookup disabled"}}"#;
assert_eq!(
crate::libraries::parse_go_modules(out),
crate::libraries::parse_go_modules(out, std::path::Path::new("/p")),
[(
"golang.org/x/[email protected]".to_owned(),
std::path::PathBuf::from("/gopath/pkg/mod/golang.org/x/[email protected]")
@@ -1883,6 +1883,35 @@ fn go_modules_skip_the_main_module_and_missing_downloads() {
);
}
#[test]
fn go_modules_skip_module_sources_inside_the_project() {
let out = r#"{"Path":"example.com/app","Main":true,"Dir":"/p/app"}
{"Path":"example.com/local","Version":"v0.0.0","Dir":"/p/local"}
{"Path":"example.com/vendored","Version":"v0.0.0","Dir":"/p/vendor/vendored"}
{"Path":"example.com/outside","Version":"v1.0.0","Dir":"/other/outside"}
{"Path":"golang.org/x/text","Version":"v0.14.0","Dir":"/gopath/pkg/mod/golang.org/x/[email protected]"}"#;
assert_eq!(
crate::libraries::parse_go_modules(out, std::path::Path::new("/p")),
[
("example.com/[email protected]".to_owned(), std::path::PathBuf::from("/p/vendor/vendored")),
("example.com/[email protected]".to_owned(), std::path::PathBuf::from("/other/outside")),
(
"golang.org/x/[email protected]".to_owned(),
std::path::PathBuf::from("/gopath/pkg/mod/golang.org/x/[email protected]")
),
]
);
// Opened from a root that does not contain it: the same folder is a library again.
assert!(
crate::libraries::parse_go_modules(
r#"{"Path":"example.com/local","Version":"v0.0.0","Dir":"/p/local"}"#,
std::path::Path::new("/p/app")
)
.iter()
.any(|(name, _)| name == "example.com/[email protected]")
);
}
#[test]
fn build_zig_zon_dependencies_are_parsed() {
let zon = r#"// the manifest is a Zig struct literal
+1 -1
View File
@@ -123,7 +123,7 @@ These commands are in the **Run** menu and on the Debug tool window toolbar.
While the program is suspended:
- The **Variables** view shows the variables of the selected frame. Right-click a value for **Set Value…** (`F2`), **Copy Value**, **Copy Name**, **Jump to Source** (`F4`) and **Add to Watches**.
- **Watches** appear at the top of the Variables view and are re-evaluated on every stop and frame change. Add one with **Add to Watches**; remove it with **Remove Watch**.
- **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.
+1 -1
View File
@@ -160,7 +160,7 @@ A **Compound** configuration starts several configurations at once. Run it to st
Each launch opens a tab in the **Run** tool window (bottom). The toolbar has **Rerun**, **Debug**, **Rerun Failed Tests** (for test runs), **Update Application**, **Find…**, **Scroll to End**, **Soft-Wrap**, **Clear All** and **Edit Configurations…**.
- File paths and stack trace frames in the output are links.
- Repeated lines can be folded; configure the patterns in **Settings › Build, Execution, Deployment › Console**, along with the buffer size and the console encoding.
- 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).
+1 -1
View File
@@ -125,7 +125,7 @@ C 和 C++ 的配置也可以改用 GDB 14 及以上版本(`gdb -i dap`):
程序挂起时:
- **变量** 视图显示选中帧的变量。右键点击某个值,可以 **设置值…**(`F2`)、**复制值**、**复制名称**、**跳转到源代码**(`F4`)和 **添加到监视**。
- 监视表达式显示在变量视图顶部,每次停下或切换帧时重新计算。用 **添加到监视** 添加,用 **移除监视** 删除。
- 监视表达式显示在变量视图顶部,每次停下或切换帧时重新计算。用 **添加到监视** 添加,用 **移除监视** 删除,用 **移除所有监视** 一次全部删除。
- 在编辑器里悬停变量会显示它的值。`⌥` 点击(`Alt` 点击)或 **快速计算表达式**(`⌘⌥F8` / `Ctrl+Alt+F8`)计算鼠标下的表达式或选中的内容。
- 局部变量的值会内联显示在使用它们的行尾。
- **计算表达式…**(`⌥F8` / `Alt+F8`)打开对话框,在选中帧里计算任意表达式,带历史记录,也能把表达式加入监视。
+1 -1
View File
@@ -156,7 +156,7 @@ Maven 模块在 **自动** 和 **构建(Make)** 时由 jdtls(ECJ)构建
每次启动都会在底部的 **运行** 工具窗口里开一个标签页。工具栏有 **重新运行**、**调试**、**重新运行失败的测试**(测试运行时)、**更新应用**、**查找…**、**滚动到末尾**、**软换行**、**全部清除** 和 **编辑配置…**。
- 输出里的文件路径和堆栈帧都可以点击跳转。
- 重复的行可以折叠。折叠规则、缓冲区大小和控制台编码在 **设置 › 构建、执行、部署 › 控制台** 中配置。
- 重复的行可以折叠。折叠规则、缓冲区大小和控制台编码在 **设置 › 构建、执行、部署 › 控制台** 中配置。控制台右键菜单中的 **折叠与此类似的行** 会打开该页面,并把选中的文本(或右键所在的行)添加为折叠规则。
- 日志行可按级别着色(`ERROR`、`WARN`、`INFO`、`DEBUG`、`TRACE`);程序自行输出的颜色保持不变。默认关闭,可在 **设置 › 构建、执行、部署 › 控制台** 开启并修改颜色。
- 测试运行时,标签页会在输出旁显示测试树,参见[测试](/zh/guide/testing)。
+71
View File
@@ -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: "[email protected]",
timeMs: 1795100000000,
});
const h = window.__ipc.handlers;
h.vcs_roots = () => [{ root, ...branchInfo }];
h.vcs_branch_info = () => branchInfo;
h.vcs_status = () => [];
h.vcs_log = ({ query }) =>
(query as { range: string }).range === `HEAD..${branch}`
? [entry("c", incomingSubject)]
: [entry("b", outgoingSubject)];
h.window_open_comparison = () => null;
const store = "/src/features/vcs/store.ts";
const { useVcs } = await import(/* @vite-ignore */ store);
useVcs.setState({ available: true, root, repo: root, roots: [root], branch: branchInfo });
const path = "/src/features/vcs/CompareBranches.tsx";
(await import(/* @vite-ignore */ path)).showCompareBranches(branch);
},
{ branch, current, incomingSubject, outgoingSubject },
);
const dialog = page.getByRole("dialog", { name: new RegExp(`Compare ${current}`) });
await expect(dialog.getByRole("listbox")).toHaveCount(2);
const incoming = dialog.getByRole("listbox", { name: `In ${branch}, not in ${current}` });
const outgoing = dialog.getByRole("listbox", { name: `In ${current}, not in ${branch}` });
await expect(incoming.getByText(incomingSubject, { exact: true })).toBeVisible();
await expect(outgoing.getByText(outgoingSubject, { exact: true })).toBeVisible();
const divider = dialog.getByRole("separator", { name: "Resize branch comparison panes" });
await expect(divider).toHaveAttribute("aria-orientation", "horizontal");
const start = (await divider.boundingBox())!.y;
await divider.focus();
await page.keyboard.press("ArrowDown");
await expect.poll(async () => (await divider.boundingBox())!.y).toBeGreaterThan(start + 1);
await page.setViewportSize({ width: 440, height: 660 });
const heading = dialog.getByRole("heading", { name: new RegExp(`In ${branch}`) });
await expect.poll(() => heading.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await expect(incoming.getByRole("option")).toBeVisible();
await expect(outgoing.getByRole("option")).toBeVisible();
await dialog.getByRole("button", { name: "Show Diff", exact: true }).click();
await expect
.poll(() => ipcCalls(page, "window_open_comparison"))
.toMatchObject([{ comparison: { from: { rev: branch }, to: { rev: "HEAD" }, repo: "/dev/acme-api" } }]);
});
+40
View File
@@ -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);
});
+75
View File
@@ -0,0 +1,75 @@
import { expect, stubDesktop, test } from "./fixtures";
const functionName = "calculateRegionalSettlementFromExternalOrderBeforeReconciliation";
const sourcePath = "/dev/acme-api/build.gradle.kts";
test("keeps frame sources and the keyboard selection visible in a narrow debug dock", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1120, height: 540 });
await stubDesktop(page);
await page.evaluate(
async ({ functionName, sourcePath }) => {
const debugModule = "/src/features/debugger/state.ts";
const layoutModule = "/src/workbench/toolwindows/store.ts";
const servicesModule = "/src/workbench/contributions.ts";
const { adoptSession } = await import(/* @vite-ignore */ debugModule);
const { moveToolWindow, setToolWindowSize } = await import(/* @vite-ignore */ layoutModule);
const { toolWindowService } = await import(/* @vite-ignore */ servicesModule);
const workerFrame = {
id: 51,
name: "processOrder",
path: sourcePath,
line: 5,
column: 0,
presentationHint: null,
};
window.__ipc.handlers.debug_scopes = () => [];
window.__ipc.handlers.debug_stack_trace = () => [workerFrame];
adoptSession(91, {
name: "Reconciliation",
adapter: "debugpy",
status: "paused",
stoppedThread: 1,
selectedThread: 1,
threads: [
{ id: 1, name: "MainThread" },
{ id: 2, name: "Order worker" },
],
selectedFrame: 1,
frames: Array.from({ length: 32 }, (_, index) => ({
id: index + 1,
name: index === 0 ? functionName : index === 1 ? "runBatch" : `reconcile(${index})`,
path: sourcePath,
line: index === 0 ? 41 : index,
column: 0,
presentationHint: null,
})),
});
moveToolWindow("debug", "right");
setToolWindowSize("right", 420);
toolWindowService().show("debug", true);
},
{ functionName, sourcePath },
);
const debug = page.getByRole("region", { name: "Debug", exact: true });
await debug.getByRole("tab", { name: "Threads & Variables", exact: true }).click();
const thread = debug.getByRole("button", { name: "Thread", exact: true });
const frames = debug.getByRole("listbox", { name: "Frames", exact: true });
const first = frames.getByRole("option", { selected: true });
await expect(first.getByText(functionName, { exact: true })).toBeVisible();
expect(await frames.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await expect(first.getByText(":42", { exact: true })).toBeInViewport({ ratio: 1 });
expect(await first.getByText(/build\.gradle\.kts/).evaluate((el) => el.clientWidth)).toBeGreaterThan(25);
const shortName = frames.getByText("runBatch", { exact: true });
expect(await shortName.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await frames.focus();
for (let i = 0; i < 25; i++) await page.keyboard.press("ArrowDown");
const selected = frames.getByRole("option", { selected: true });
await expect(selected.getByText("reconcile(25)", { exact: true })).toBeInViewport({ ratio: 0.95 });
expect(await frames.evaluate((el) => el.scrollTop)).toBeGreaterThan(0);
await thread.click();
await page.getByRole("option", { name: "Order worker", exact: true }).click();
await expect(thread).toContainText("Order worker");
await expect(frames.getByRole("option", { selected: true })).toContainText("processOrder");
});
+42
View File
@@ -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);
});
+62
View File
@@ -0,0 +1,62 @@
import { expect, stubDesktop, test } from "./fixtures";
test("File Types keeps association editors usable and opens ignored rules from search", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1120, height: 760 });
await page.keyboard.press("Meta+,");
const settings = page.getByRole("dialog", { name: "Settings", exact: true });
await expect(settings).toBeVisible();
await stubDesktop(page);
await page.evaluate(() => {
window.__ipc.handlers.languages = () => [
{ id: "javascript", name: "JavaScript", extensions: ["js"] },
{ id: "python", name: "Python", extensions: ["py", "pyi", "pyw"], filenames: ["SConstruct", "SConscript"] },
];
});
const search = settings.getByRole("textbox", { name: "Search settings" });
await search.fill("File Types");
await settings.getByRole("treeitem", { name: "File Types", exact: true }).click();
await search.clear();
const tabs = settings.getByRole("tablist", { name: "File Types" });
const recognized = tabs.getByRole("tab", { name: "Recognized File Types" });
const ignored = tabs.getByRole("tab", { name: "Ignored Files and Folders" });
await expect(recognized).toHaveAttribute("aria-selected", "true");
const divider = settings.getByRole("separator", { name: "Resize file type panes" });
await expect(divider).toHaveAttribute("aria-orientation", "vertical");
await page.setViewportSize({ width: 520, height: 660 });
await expect(divider).toHaveAttribute("aria-orientation", "horizontal");
const types = settings.getByRole("listbox", { name: "Recognized file types", exact: true });
await types.getByRole("option", { name: "Python", exact: true }).click();
const patterns = settings.getByRole("listbox", { name: "File name patterns of Python" });
const hashbangLabel = settings.getByText("Hashbang patterns", { exact: true });
await expect
.poll(async () => {
const nameList = await patterns.boundingBox();
const hashbangHeading = await hashbangLabel.boundingBox();
return nameList && hashbangHeading ? hashbangHeading.y - (nameList.y + nameList.height) : -1;
})
.toBeGreaterThan(0);
await expect
.poll(() => settings.locator("[class*='_patterns_']").evaluate((el) => el.scrollWidth - el.clientWidth))
.toBeLessThanOrEqual(1);
const toolbar = settings.locator(`[role="toolbar"][aria-controls="${await patterns.getAttribute("id")}"]`);
await toolbar.getByRole("button", { name: "Add" }).click();
const pattern = patterns.getByRole("textbox", { name: "Pattern" });
await pattern.fill("*.layout-demo");
await pattern.press("Enter");
await expect(patterns.getByRole("option", { name: "*.layout-demo", exact: true })).toBeVisible();
await expect
.poll(() => settings.locator("[class*='pageBody']").evaluate((el) => el.scrollWidth - el.clientWidth))
.toBeLessThanOrEqual(1);
await search.fill("Exclude patterns");
await expect(ignored).toHaveAttribute("aria-selected", "true");
await expect(settings.getByRole("listbox", { name: "Exclude patterns" })).toBeVisible();
await expect(patterns).toBeHidden();
await ignored.click();
await search.clear();
await ignored.press("ArrowLeft");
await expect(recognized).toHaveAttribute("aria-selected", "true");
await expect(patterns.getByRole("option", { name: "*.layout-demo", exact: true })).toBeVisible();
});
+93
View File
@@ -0,0 +1,93 @@
import { expect, stubDesktop, test } from "./fixtures";
test("Shelf keeps patch and file selection available in a narrow dock", async ({ workbench: page }) => {
const name = "Reconcile payment and settlement totals before exporting ledger reports";
const directory = "services/settlement/internal/payment-reconciliation/statement-generation";
const filename = "invoiceSettlementRowAssembler.ts";
const file = directory + "/" + filename;
await page.setViewportSize({ width: 1440, height: 760 });
await stubDesktop(page);
await page.evaluate(
async ({ name, file }) => {
const root = "/dev/acme-api";
const h = window.__ipc.handlers;
h.vcs_roots = () => [{ root, operation: null, head: "main", headCommit: "1111111" }];
h.vcs_branch_info = () => ({
head: "main",
headCommit: "1111111",
upstream: null,
ahead: 0,
behind: 0,
operation: null,
});
h.vcs_status = () => [];
h.vcs_shelves = () => [
{
id: "settlement",
name,
timeMs: null,
branch: "main",
files: [file, "README.md"].map((path) => ({ path, kind: "modified", oldPath: null })),
},
{
id: "docs",
name: "Update release notes",
timeMs: null,
branch: "main",
files: [{ path: "CHANGELOG.md", kind: "modified", oldPath: null }],
},
];
h.vcs_shelf_diff = () => [];
const vcs = "/src/features/vcs/store.ts";
const { useVcs } = await import(/* @vite-ignore */ vcs);
useVcs.setState({ root, repo: root, roots: [root], available: true });
const project = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ project);
const settings = useProject.getState().settings ?? {};
useProject.setState({ settings: { ...settings, vcs: { ...settings.vcs, commit: { nonModal: true } } } });
const context = "/src/platform/context.ts";
(await import(/* @vite-ignore */ context)).setContext("vcsAvailable", true);
const dock = "/src/workbench/toolwindows/store.ts";
(await import(/* @vite-ignore */ dock)).setToolWindowSize("left", 228);
const actions = "/src/platform/actions.ts";
await (await import(/* @vite-ignore */ actions)).executeAction("vcs.showShelf");
},
{ name, file },
);
const panel = page.locator("[data-shelf-panel]");
const patches = panel.getByRole("tree", { name: "Shelved changes" });
const patch = patches.getByRole("treeitem").filter({ hasText: name });
await patch.click({ position: { x: 90, y: 12 } });
if ((await patch.getAttribute("aria-expanded")) === "false") await page.keyboard.press("ArrowRight");
const location = panel.getByText(directory, { exact: true });
await expect.poll(() => location.evaluate((el) => el.clientWidth)).toBeGreaterThan(100);
const divider = panel.getByRole("separator", { name: "Resize shelf panes" });
await expect(divider).toHaveAttribute("aria-orientation", "horizontal");
const files = panel.getByRole("tree", { name: "Shelved files" });
await expect(files.getByRole("treeitem")).toHaveCount(2);
const pathBox = (await location.boundingBox())!;
const filesBox = (await files.boundingBox())!;
expect(pathBox.x).toBeLessThan(filesBox.x + filesBox.width - 50);
const row = files.getByRole("treeitem").filter({ hasText: filename });
await row.click({ position: { x: 90, y: 12 } });
await expect(row).toHaveAttribute("aria-selected", "true");
await panel.getByRole("button", { name: "Unshelve…", exact: true }).click();
const dialog = page.getByRole("dialog", { name: "Unshelve Changes" });
await expect(
dialog.getByRole("tree", { name: "Files to unshelve" }).getByText(filename, { exact: true }),
).toBeVisible();
await expect(dialog.getByText("README.md", { exact: true })).toHaveCount(0);
await dialog.getByRole("button", { name: "Cancel", exact: true }).click();
await page.evaluate(async () => {
const dock = "/src/workbench/toolwindows/store.ts";
(await import(/* @vite-ignore */ dock)).setToolWindowSize("left", 640);
});
await expect(divider).toHaveAttribute("aria-orientation", "vertical");
await expect(row).toHaveAttribute("aria-selected", "true");
await patches.getByRole("treeitem").filter({ hasText: "Update release notes" }).click();
await expect(files.getByRole("treeitem")).toHaveCount(1);
await expect(files.getByText("CHANGELOG.md", { exact: true })).toBeVisible();
});
+65
View File
@@ -0,0 +1,65 @@
import { expect, openFromTree, test } from "./fixtures";
test("Switcher keeps the open file list and path visible in a narrow workbench", async ({ workbench: page }) => {
await openFromTree(page, "README.md");
await openFromTree(page, "App.tsx");
await page.keyboard.down("Control");
await page.keyboard.press("Tab");
const switcher = page.getByRole("dialog", { name: "Switcher", exact: true });
const files = switcher.getByRole("listbox", { name: "Open files" });
const tools = switcher.getByRole("listbox", { name: "Tool windows" });
const selected = files.getByRole("option", { selected: true });
await expect(selected).toHaveText("README.md");
expect((await switcher.boundingBox())!.width).toBeLessThan(600);
await page.setViewportSize({ width: 400, height: 500 });
await expect.poll(async () => (await files.boundingBox())!.width).toBeGreaterThan(225);
const footer = switcher.locator("footer");
await expect(footer).toHaveText(/README\.md$/);
await expect(footer).toBeInViewport({ ratio: 1 });
await expect(footer).toHaveCSS("font-size", "12px");
expect(await tools.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
expect(await files.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
const structure = tools.getByText("Structure", { exact: true });
expect(await structure.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await page.keyboard.press("Tab");
const activeTool = tools.getByRole("option", { selected: true });
await expect(activeTool).toBeInViewport({ ratio: 1 });
const firstTool = await activeTool.getAttribute("aria-posinset");
await page.keyboard.press("PageDown");
await page.keyboard.press("PageDown");
await expect(activeTool).not.toHaveAttribute("aria-posinset", firstTool!);
await expect(activeTool).toBeInViewport({ ratio: 0.98 });
expect(await tools.evaluate((el) => el.scrollTop)).toBeGreaterThan(0);
await page.keyboard.press("Shift+Tab");
await expect(selected).toHaveText("README.md");
await page.keyboard.up("Control");
await expect(switcher).toBeHidden();
await expect(page.getByRole("tab", { name: "README.md", exact: true })).toHaveAttribute("aria-selected", "true");
});
test("Switcher takes up less space when both lists have only a few entries", async ({ workbench: page }) => {
await openFromTree(page, "README.md");
await openFromTree(page, "App.tsx");
await page.evaluate(async () => {
const path = "/src/workbench/contributions.ts";
const { useContributions } = (await import(
/* @vite-ignore */ path
)) as typeof import("../src/workbench/contributions");
useContributions.setState(({ toolWindows }) => ({
toolWindows: new Map([...toolWindows].filter(([id]) => id === "project" || id === "terminal")),
}));
});
await page.keyboard.down("Control");
await page.keyboard.press("Tab");
const switcher = page.getByRole("dialog", { name: "Switcher", exact: true });
const tools = switcher.getByRole("listbox", { name: "Tool windows" });
await expect(tools.getByRole("option")).toHaveCount(2);
await expect.poll(async () => (await switcher.boundingBox())!.height).toBeLessThan(380);
await expect(switcher.locator("footer")).toHaveText(/README\.md$/);
await page.keyboard.press("Escape");
await page.keyboard.up("Control");
});
+42
View File
@@ -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");
});
+177 -7
View File
@@ -106,7 +106,12 @@ impl Forward {
type Channels = Arc<Mutex<HashMap<u64, (Channel<ChannelFrame>, u64)>>>;
#[derive(Default)]
pub struct Connections(Mutex<HashMap<String, Arc<Connection>>>);
pub struct Connections {
windows: Mutex<HashMap<String, Arc<Connection>>>,
/// The connect attempt allowed to publish for each window. A later connect, or a
/// disconnect, supersedes an attempt that is still starting the server.
attempts: Mutex<HashMap<String, u64>>,
}
impl Connection {
/// Commands of a remote window that run on this machine follow this machine's decision about the
@@ -143,13 +148,13 @@ impl Connection {
impl Connections {
pub fn get(&self, window: &str) -> Option<Arc<Connection>> {
self.0.lock().get(window).cloned()
self.windows.lock().get(window).cloned()
}
/// The window connected to folder `root` of `target`.
pub fn window_of(&self, target: &RemoteTarget, root: &str) -> Option<String> {
let root = root.trim_end_matches('/');
self.0
self.windows
.lock()
.iter()
// A dev container is one project: its folder there is only known once connected.
@@ -162,17 +167,131 @@ impl Connections {
/// Every connected window.
pub fn all(&self) -> Vec<(String, Arc<Connection>)> {
self.0.lock().iter().map(|(w, c)| (w.clone(), c.clone())).collect()
self.windows.lock().iter().map(|(w, c)| (w.clone(), c.clone())).collect()
}
/// Starts a connect for `window`. An older attempt can no longer publish.
pub fn begin(&self, window: &str) -> u64 {
self.bump(window)
}
fn bump(&self, window: &str) -> u64 {
let mut attempts = self.attempts.lock();
let next = attempts.get(window).copied().unwrap_or(0).wrapping_add(1);
attempts.insert(window.to_owned(), next);
next
}
/// Installs `connection` when `attempt` is still the one [`begin`] returned for `window`.
/// An older attempt leaves the connection a newer one published.
pub fn publish(&self, window: &str, attempt: u64, connection: Arc<Connection>) -> bool {
let attempts = self.attempts.lock();
if attempts.get(window).copied() != Some(attempt) {
return false;
}
if let Some(old) = self.windows.lock().insert(window.to_owned(), connection) {
old.peer.kill();
old.forwards.lock().clear();
}
true
}
pub fn disconnect(&self, window: &str) {
if let Some(c) = self.0.lock().remove(window) {
// Invalidate an attempt that has not published yet, or it would put the
// connection back after this disconnect.
self.bump(window);
if let Some(c) = self.windows.lock().remove(window) {
c.peer.kill();
c.forwards.lock().clear();
}
}
}
/// `ssh://` / `wsl://` / `devcontainer://` location, the same spelling the frontend stores.
pub fn remote_location(target: &RemoteTarget, path: &str) -> String {
let (scheme, name) = match target {
RemoteTarget::Ssh { config } => ("ssh", config.as_str()),
RemoteTarget::Wsl { distro } => ("wsl", distro.as_str()),
RemoteTarget::DevContainer { folder, .. } => ("devcontainer", folder.as_str()),
};
let config = match target {
RemoteTarget::DevContainer { config, .. } if !config.is_empty() => format!(":{}", encode_uri_component(config)),
_ => String::new(),
};
let path = if path.starts_with('/') { path.to_owned() } else { format!("/{path}") };
format!("{scheme}://{}{config}{path}", encode_uri_component(name))
}
/// The remote project a `ssh://`, `wsl://` or `devcontainer://` location names.
pub fn parse_remote_location(location: &str) -> Option<(RemoteTarget, String)> {
let (kind, rest) = if let Some(rest) = location.strip_prefix("ssh://") {
("ssh", rest)
} else if let Some(rest) = location.strip_prefix("wsl://") {
("wsl", rest)
} else {
("devcontainer", location.strip_prefix("devcontainer://")?)
};
let slash = rest.find('/')?;
if slash == 0 {
return None;
}
let authority = &rest[..slash];
let path = rest[slash..].to_owned();
let (name, config) = if kind == "devcontainer" {
match authority.split_once(':') {
Some((name, config)) => (name, config),
None => (authority, ""),
}
} else {
(authority, "")
};
let name = decode_uri_component(name)?;
let config = decode_uri_component(config)?;
if name.is_empty() {
return None;
}
let target = match kind {
"ssh" => RemoteTarget::Ssh { config: name },
"wsl" => RemoteTarget::Wsl { distro: name },
_ => RemoteTarget::DevContainer { folder: name, config },
};
Some((target, path))
}
/// `encodeURIComponent`: the frontend builds locations with it.
fn encode_uri_component(value: &str) -> String {
let mut out = String::new();
for b in value.bytes() {
match b {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'!' | b'~' | b'*' | b'\'' | b'(' | b')' => {
out.push(b as char)
}
_ => out.push_str(&format!("%{b:02X}")),
}
}
out
}
fn decode_uri_component(value: &str) -> Option<String> {
let bytes = value.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%' {
if i + 2 >= bytes.len() {
return None;
}
let hex = std::str::from_utf8(&bytes[i + 1..i + 3]).ok()?;
out.push(u8::from_str_radix(hex, 16).ok()?);
i += 3;
} else {
out.push(bytes[i]);
i += 1;
}
}
String::from_utf8(out).ok()
}
/// Where [`remote_connect`] is (`fraction`: 0..1 of a download / upload).
#[derive(Clone, Copy, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
@@ -512,6 +631,9 @@ pub async fn remote_connect(
});
progress(RemoteStage::Connecting, None);
let label = AppState::owner_window(window.label()).to_owned();
// A later connect or a disconnect supersedes this attempt, so it cannot replace
// the connection that one published — or put one back after it was dropped.
let attempt = state.remote_dev.begin(&label);
let channels: Channels = Arc::default();
let connection_slot: Arc<std::sync::OnceLock<std::sync::Weak<Connection>>> = Arc::default();
let handler = Arc::new(ClientHandler {
@@ -613,10 +735,14 @@ pub async fn remote_connect(
if let RemoteTarget::DevContainer { folder, config } = &target {
forward_configured_ports(&connection, folder, config).await;
}
state.remote_dev.disconnect(&label);
if !state.remote_dev.publish(&label, attempt, connection.clone()) {
tracing::debug!("{label}: remote connection superseded");
connection.peer.kill();
connection.forwards.lock().clear();
return Err(IdeError::cancelled());
}
state.host.close_project(&label);
state.host.mcp_reports.set_remote(&label, std::path::PathBuf::from(&connection.root));
state.remote_dev.0.lock().insert(label.clone(), connection.clone());
let weak = Arc::downgrade(&connection);
let peer = connection.peer.clone();
let auth_plugins = state.plugins.clone();
@@ -641,6 +767,9 @@ pub async fn remote_connect(
sync_plugin_languages(&plugins, &connection, &label).await;
sync_plugin_packages(&plugins, &connection, &label).await;
});
if let Err(error) = crate::window_groups::persist(window.app_handle()).await {
tracing::warn!(%error, "cannot save window session after opening remote project");
}
Ok(RemoteProject { target, root, host, server_version: info.version, os: info.os, commands, project })
}
@@ -1069,6 +1198,29 @@ async fn invoke_reply(peer: &Peer, call: Invoke, entries_timeout: std::time::Dur
mod tests {
use super::*;
#[test]
fn remote_locations_round_trip_like_the_frontend() {
let cases = [
(RemoteTarget::Wsl { distro: "Ubuntu-24.04".into() }, "/home/me/app", "wsl://Ubuntu-24.04/home/me/app"),
(RemoteTarget::Ssh { config: "my box".into() }, "/srv/app", "ssh://my%20box/srv/app"),
(
RemoteTarget::DevContainer { folder: "/work/app".into(), config: "devcontainer.json".into() },
"/workspaces/app",
"devcontainer://%2Fwork%2Fapp:devcontainer.json/workspaces/app",
),
(
RemoteTarget::DevContainer { folder: "/work/app".into(), config: String::new() },
"/workspaces/app",
"devcontainer://%2Fwork%2Fapp/workspaces/app",
),
];
for (target, path, location) in cases {
assert_eq!(remote_location(&target, path), location);
assert_eq!(parse_remote_location(location), Some((target, path.to_owned())));
}
assert!(parse_remote_location(r"\\wsl.localhost\Ubuntu\home\me\app").is_none());
}
#[test]
fn a_command_missing_on_a_server_of_another_version_says_which_versions() {
let missing = || IdeError::unavailable("-32601: command web_url is not available remotely");
@@ -1159,6 +1311,24 @@ mod tests {
}
}
#[tokio::test]
async fn a_later_connect_supersedes_an_earlier_attempt() {
let connections = Connections::default();
let first = connections.begin("main");
let second = connections.begin("main");
let older = Arc::new(connected(RemoteTarget::Wsl { distro: "Ubuntu".into() }, "/home/me/old"));
assert!(!connections.publish("main", first, older.clone()));
assert!(connections.get("main").is_none());
let newer = Arc::new(connected(RemoteTarget::Wsl { distro: "Ubuntu".into() }, "/home/me/new"));
assert!(connections.publish("main", second, newer.clone()));
assert!(Arc::ptr_eq(&connections.get("main").unwrap(), &newer));
connections.disconnect("main");
assert!(connections.get("main").is_none());
assert!(!connections.publish("main", second, newer.clone()));
older.peer.kill();
newer.peer.kill();
}
#[tokio::test]
async fn the_server_does_not_decide_trust_for_commands_run_here() {
let tmp = tempfile::tempdir().unwrap();
+7 -4
View File
@@ -143,10 +143,11 @@ impl AppState {
/// Opens `root` in `window` and records it in the recent projects.
pub fn open_project(&self, window: &str, root: &Path) -> IdeResult<Arc<Project>> {
// A local project replaces a remote one in this window.
self.remote_dev.disconnect(window);
let project = self.host.open_project(window, root)?;
self.record_project(&project)?;
// Drop the remote connection only once the local project is actually open.
// A failed open leaves the window on the host it is still routing to.
self.remote_dev.disconnect(window);
Ok(project)
}
@@ -166,14 +167,16 @@ impl AppState {
/// Opens `window` for editing the loose file `file` (LightEdit); not a recent project.
pub fn open_light(&self, window: &str, file: &Path) -> IdeResult<Arc<Project>> {
let project = self.host.open_light(window, file)?;
self.remote_dev.disconnect(window);
self.host.open_light(window, file)
Ok(project)
}
/// LightEdit without a file (File › New File from a welcome window).
pub fn open_light_empty(&self, window: &str) -> IdeResult<Arc<Project>> {
let project = self.host.open_light_empty(window)?;
self.remote_dev.disconnect(window);
self.host.open_light_empty(window)
Ok(project)
}
/// Called on the event-loop thread (window destruction, the `close_project`
+28 -20
View File
@@ -276,10 +276,18 @@ pub async fn persist(app: &AppHandle) -> IdeResult<()> {
}
let groups = state.groups.lock().groups().to_vec();
let windows = labels_in_order(app);
let project_of = |label: &str| match host.project(label) {
Ok(p) => (!p.light).then(|| p.root.clone()),
// A restored window may have taken its launch but not finished opening yet.
Err(_) => state.pending(label).and_then(|l| l.project).map(Into::into),
let project_of = |label: &str| {
if let Some(path) = windows::window_project_path(app, label) {
return Some(path);
}
// Taken its launch, not finished opening: keep the remote location or local folder.
state.pending(label).and_then(|launch| {
launch
.remote
.as_ref()
.map(|remote| PathBuf::from(crate::remote_dev::remote_location(&remote.target, &remote.path)))
.or_else(|| launch.project.clone().map(Into::into))
})
};
let Some(saved) = ide_workspace::window_groups::session(&groups, &windows, project_of) else {
return Ok(());
@@ -314,8 +322,13 @@ pub async fn restore(app: &AppHandle, caller: &str) -> IdeResult<()> {
}
let state = app.state::<WindowsState>();
let host = app.state::<AppState>();
let project = host.project(caller)?;
if !project.settings.effective().general.reopen_last_project || state.groups_restored.swap(true, Ordering::SeqCst) {
// A remote window has no local project. Leave the flag clear until this window has
// one, so the call that runs once the connection is up can still restore its siblings.
let Some(root) = windows::window_project_path(app, caller) else {
return Ok(());
};
let settings = ide_host::ops::project::settings_get(&host.host, caller);
if !settings.general.reopen_last_project || state.groups_restored.swap(true, Ordering::SeqCst) {
return Ok(());
}
let saved = {
@@ -327,30 +340,25 @@ pub async fn restore(app: &AppHandle, caller: &str) -> IdeResult<()> {
};
// The caller's own group first (it already shows one of its projects), then every other
// group and single window that was open at quit. Missing folders are skipped.
let order = saved
.iter()
.filter(|g| g.projects.contains(&project.root))
.chain(saved.iter().filter(|g| !g.projects.contains(&project.root)));
let owns = |group: &ide_workspace::window_groups::SavedWindows| {
group.projects.iter().any(|path| windows::same_saved_project(path, &root))
};
let order = saved.iter().filter(|group| owns(group)).chain(saved.iter().filter(|group| !owns(group)));
for group in order {
let mut labels = Vec::new();
let mut selected = None;
for path in &group.projects {
let label = if path == &project.root {
let label = if windows::same_saved_project(path, &root) {
Some(caller.to_owned())
} else if path.is_dir() {
let window = match windows::find_project_window(app, path) {
Some(w) => Ok(w),
None => windows::create_restored_window(app, path.clone()),
};
match window {
Ok(w) => Some(w.label().to_owned()),
} else {
match windows::reopen_saved_window(app, path) {
Ok(Some(w)) => Some(w.label().to_owned()),
Ok(None) => None,
Err(e) => {
tracing::warn!("cannot reopen {}: {e}", path.display());
None
}
}
} else {
None
};
if let Some(label) = label {
if group.projects.get(group.selected) == Some(path) {
+99 -1
View File
@@ -211,6 +211,74 @@ pub fn wsl_launch(path: &Path) -> Option<RemoteLaunch> {
Some(RemoteLaunch { target: RemoteTarget::Wsl { distro: w.distro }, path: w.path })
}
/// A saved project path that is a remote location: `ssh://`, `wsl://`, `devcontainer://`,
/// or a `\\wsl.localhost` share remembered before those locations existed.
pub(crate) fn saved_remote(path: &Path) -> Option<RemoteLaunch> {
if let Some(text) = path.to_str()
&& let Some((target, root)) = crate::remote_dev::parse_remote_location(text)
{
return Some(RemoteLaunch { target, path: root });
}
wsl_launch(path)
}
/// What reopening `path` should launch. A remote location is recognised before any stat,
/// so a WSL share that is down still comes back as a remote project.
pub(crate) fn saved_project_launch(path: &Path) -> Option<Launch> {
if let Some(remote) = saved_remote(path) {
return Some(Launch { remote: Some(remote), ..Default::default() });
}
path.is_dir().then(|| Launch { project: Some(path.to_path_buf().into()), ..Default::default() })
}
/// The same project, including a WSL share and the `wsl://` location of that folder.
pub(crate) fn same_saved_project(a: &Path, b: &Path) -> bool {
if a == b {
return true;
}
match (saved_remote(a), saved_remote(b)) {
(Some(left), Some(right)) => {
left.target == right.target && left.path.trim_end_matches('/') == right.path.trim_end_matches('/')
}
_ => false,
}
}
/// The project `label` has open: a remote location (`wsl://` and the rest), else its local root.
pub(crate) fn window_project_path(app: &AppHandle, label: &str) -> Option<PathBuf> {
let state = app.try_state::<AppState>()?;
if let Some(c) = state.remote_dev.get(label) {
return Some(PathBuf::from(crate::remote_dev::remote_location(&c.target, &c.root)));
}
state.project(label).ok().filter(|p| !p.light).map(|p| p.root.clone())
}
/// Reopens a project saved at quit. Remote locations become a remote launch; a missing
/// local folder is skipped. An already connected window is focused instead of duplicated.
pub(crate) fn reopen_saved_window(app: &AppHandle, path: &Path) -> IdeResult<Option<WebviewWindow>> {
let Some(launch) = saved_project_launch(path) else {
return Ok(None);
};
if let Some(remote) = launch.remote.clone() {
let open = app.try_state::<AppState>().and_then(|s| s.remote_dev.window_of(&remote.target, &remote.path));
if let Some(w) = open.and_then(|label| app.get_webview_window(&label)) {
return Ok(Some(w));
}
let title = remote
.path
.trim_end_matches('/')
.rsplit('/')
.next()
.filter(|n| !n.is_empty() && *n != "~")
.map(str::to_owned);
return Ok(Some(create_window_for(app, title, launch, true)?));
}
if let Some(w) = find_project_window(app, path) {
return Ok(Some(w));
}
Ok(Some(create_restored_window(app, path.to_path_buf())?))
}
#[derive(Default)]
pub struct WindowsState {
pub groups: Mutex<ide_workspace::window_groups::WindowGroups>,
@@ -2446,11 +2514,41 @@ mod tests {
let folder = launch_for(share.clone(), true);
let remote =
RemoteLaunch { target: RemoteTarget::Wsl { distro: "Ubuntu".into() }, path: "/home/me/app".into() };
assert_eq!((folder.remote, folder.project, folder.files.len()), (Some(remote), None, 0));
assert_eq!((folder.remote, folder.project, folder.files.len()), (Some(remote.clone()), None, 0));
let file = launch_for(share.join("main.py"), false);
assert_eq!((file.remote, file.project, file.files.len()), (None, None, 1));
}
#[test]
fn a_saved_wsl_project_reopens_as_a_remote_launch_without_the_share() {
let remote =
RemoteLaunch { target: RemoteTarget::Wsl { distro: "Ubuntu".into() }, path: "/home/me/app".into() };
for saved in [r"\\wsl.localhost\Ubuntu\home\me\app", "wsl://Ubuntu/home/me/app", "//wsl$/Ubuntu/home/me/app"] {
let launch = saved_project_launch(Path::new(saved)).expect(saved);
assert_eq!(launch.remote, Some(remote.clone()));
assert!(launch.project.is_none(), "{saved}");
}
assert!(same_saved_project(
Path::new(r"\\wsl.localhost\Ubuntu\home\me\app"),
Path::new("wsl://Ubuntu/home/me/app/")
));
let ssh = saved_project_launch(Path::new("ssh://box/srv/app")).unwrap();
assert_eq!(
ssh.remote,
Some(RemoteLaunch { target: RemoteTarget::Ssh { config: "box".into() }, path: "/srv/app".into() })
);
let container =
saved_project_launch(Path::new("devcontainer://%2Fwork%2Fapp:devcontainer.json/workspaces/app")).unwrap();
assert_eq!(
container.remote,
Some(RemoteLaunch {
target: RemoteTarget::DevContainer { folder: "/work/app".into(), config: "devcontainer.json".into() },
path: "/workspaces/app".into(),
})
);
assert!(saved_project_launch(Path::new("/no/such/local/project-openidea")).is_none());
}
fn p(s: &str) -> PathBuf {
PathBuf::from(s)
}
+5
View File
@@ -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)!);
+4
View File
@@ -420,6 +420,9 @@ export const JAVA_TAGS: Parameters<typeof styleTags>[0] = {
this: t.keyword,
};
// @lezer/go leaves `default` uncoloured, unlike `case` and `switch`.
const GO_TAGS: Parameters<typeof styleTags>[0] = { default: t.controlKeyword };
/** Highlighting the stock grammars lack or colour unlike IntelliJ. */
const EXTRA_TAGS: Record<string, Parameters<typeof styleTags>[0]> = {
JavaScript: JS_TAGS,
@@ -437,6 +440,7 @@ const EXTRA_TAGS: Record<string, Parameters<typeof styleTags>[0]> = {
"MethodDeclaration/Name FunctionDefinition/Name": t.function(t.definition(t.variableName)),
"PropertyDeclaration/VariableDeclarator/VariableName": t.definition(t.propertyName),
},
Go: GO_TAGS,
CSS: CSS_TAGS,
SCSS: CSS_TAGS,
Sass: CSS_TAGS,
+40 -2
View File
@@ -35,6 +35,10 @@ import {
import styles from "./AgentList.module.css";
const errorText = (e: unknown) => (e instanceof Error ? e.message : String(e));
const COPILOT_GITHUB_ACCOUNT_ENV = "OPENIDEA_COPILOT_GITHUB_ACCOUNT";
const launchEnv = (env: Record<string, string>) =>
Object.fromEntries(Object.entries(env).filter(([name]) => name !== COPILOT_GITHUB_ACCOUNT_ENV));
/** How often the page checks on installs it did not start. */
const BACKGROUND_POLL_MS = 1500;
@@ -819,13 +823,26 @@ function ProviderSettings({
onChanged?.();
return command === agent.defaultProgram ? "" : (command ?? "");
});
const envBase = formatEnv(agent.env);
const accountBase = agent.env[COPILOT_GITHUB_ACCOUNT_ENV] ?? "";
const account = form.useExternal(`agents.${agent.id}.githubAccount`, accountBase, async (draft) => {
const next = { ...agent.env };
const value = draft.trim();
if (value) next[COPILOT_GITHUB_ACCOUNT_ENV] = value;
else delete next[COPILOT_GITHUB_ACCOUNT_ENV];
await backend.setEnv(agent.id, next);
await refresh();
onChanged?.();
return value;
});
const envBase = formatEnv(launchEnv(agent.env));
const env = form.useExternal(`agents.${agent.id}.env`, envBase, async (draft) => {
const parsed = parseEnv(draft);
const account = agent.env[COPILOT_GITHUB_ACCOUNT_ENV];
if (account) parsed[COPILOT_GITHUB_ACCOUNT_ENV] = account;
await backend.setEnv(agent.id, parsed);
await refresh();
onChanged?.();
return formatEnv(parsed);
return formatEnv(launchEnv(parsed));
});
const [error, setError] = useState<string | null>(null);
// An edit can have been staged by a previous page instance. Its Apply callback
@@ -849,6 +866,27 @@ function ProviderSettings({
</Section>
<Section title="Launch">
<div className={styles.form}>
{agent.id === "copilot" && (
<Row
label={<T>GitHub account</T>}
htmlFor={`agent-github-account-${agent.id}`}
hint={
<T>
Leave empty to use the active GitHub CLI account. OpenIDEA resolves the token at launch and never
stores it.
</T>
}
>
<Input
id={`agent-github-account-${agent.id}`}
mono
value={account.value}
disabled={account.saving}
placeholder="github-username"
onChange={(e) => account.set(e.target.value)}
/>
</Row>
)}
<Row label={<T>Command</T>}>
<code className={styles.launch} title={launch}>
{launch}
+1 -1
View File
@@ -284,7 +284,7 @@ function ModelPicker({
const pinnedModels = useAgents((s) => s.pinnedModels);
const anchor = useRef<HTMLButtonElement>(null);
const selectedModel = selected(model, modelValue);
const unavailable = modelRefresh?.draft && modelValue !== null && !selectedModel;
const unavailable = !!modelRefresh && modelValue !== null && !selectedModel;
const modelName = unavailable
? tx`${modelValue} (unavailable)`
: (selectedModel?.name ?? (modelRefresh ? modelValue : null) ?? tx("Default"));
+34 -2
View File
@@ -469,7 +469,7 @@ describe("Built-in executable overrides", () => {
dispose();
});
const openCommands = async (commands: FakeCommands, onChanged = vi.fn()) => {
const openCommands = async (commands: FakeCommands, onChanged = vi.fn(), name = "Claude Code") => {
const backend = new FakeBackend();
dispose = registerSettingsPage({
id: REGISTRY_PAGE,
@@ -478,7 +478,7 @@ describe("Built-in executable overrides", () => {
component: () => <RegistryPage backend={backend} commandBackend={commands} onChanged={onChanged} />,
});
render(<SettingsDialog />);
return screen.findByRole("region", { name: "Claude Code" });
return screen.findByRole("region", { name });
};
const apply = () => screen.getByRole("button", { name: "Apply" });
const field = () => screen.getByRole("textbox", { name: "Executable" });
@@ -564,6 +564,38 @@ describe("Built-in executable overrides", () => {
expect(commands.savedEnv.at(-1)).toEqual(["claude", {}]);
});
it("writes a Copilot GitHub account without storing a token or exposing the control variable", async () => {
const commands = new FakeCommands();
commands.list = [
{
...claudeProvider("copilot"),
id: "copilot",
name: "GitHub Copilot",
command: "copilot --acp",
defaultProgram: "copilot",
commandReadOnlyReason: "registry",
env: { COPILOT_TELEMETRY_OPTOUT: "1" },
},
];
await openCommands(commands, vi.fn(), "GitHub Copilot");
const account = screen.getByRole("textbox", { name: "GitHub account" });
expect(screen.queryByRole("textbox", { name: "Environment variables" })).toBeNull();
fireEvent.change(account, { target: { value: "dengliu_microsoft" } });
await act(async () => fireEvent.click(apply()));
expect(commands.savedEnv).toEqual([
[
"copilot",
{
COPILOT_TELEMETRY_OPTOUT: "1",
OPENIDEA_COPILOT_GITHUB_ACCOUNT: "dengliu_microsoft",
},
],
]);
expect(JSON.stringify(commands.savedEnv)).not.toMatch(/gho_|ghp_|token/i);
});
it("Cancel discards command edits without writing", async () => {
const commands = new FakeCommands();
commands.list = [
+38
View File
@@ -251,6 +251,44 @@ it("refreshes an existing chat's searchable model choices and switches through i
expect(useAgents.getState().draft).toBe(draft);
});
it("recovers a model picker after a Copilot ACP fallback removed the session option", async () => {
const task: AgentTask = {
id: "fallback-task",
title: "Recovered chat",
provider: "first",
status: "ready",
isolation: "local",
model: "stale-model",
cwd: "/models",
branch: null,
base: null,
baseCommit: null,
error: null,
createdMs: 0,
updatedMs: 0,
config: [{ ...option("mode", "mode", ["plan", "act"]), name: "Mode" }],
commands: [],
usage: null,
queue: [],
};
const input = { kind: SESSION_KIND, key: sessionKey(task.id), data: { task: task.id } };
backend.providers[0]!.config = [];
backend.tasks = [task];
backend.activeInput = input;
await connect();
backend.refresh.mockResolvedValueOnce(ok(catalog("first", { config: [option("model", "model", ["auto"])] })));
render(<SessionEditor input={input} />);
const modelButton = screen.getByRole("button", { name: "Model" });
expect(modelButton).toHaveTextContent("stale-model (unavailable)");
fireEvent.click(modelButton);
expect(await screen.findByRole("option", { name: "auto" })).toBeVisible();
fireEvent.click(screen.getByRole("option", { name: "auto" }));
expect(backend.refresh).toHaveBeenCalledWith("first", false, null);
expect(backend.setConfig).toHaveBeenCalledExactlyOnceWith("fallback-task", "model", "auto");
});
it("keeps cached choices usable while refreshing and shares the completion/cooldown from another window", async () => {
backend.refresh.mockImplementation(async (id: string) => ok(catalog(id, { refreshing: true })));
render(<HomeEditor />);
@@ -1,4 +1,4 @@
import type { AgentChange, AgentCommit, AgentEntry, AgentTask } from "@/bindings";
import type { AgentChange, AgentCommit, AgentConfigOption, AgentEntry, AgentTask } from "@/bindings";
import { executeAction } from "@/platform/actions";
import { tx, useTx } from "@/platform/i18n";
import { useProject } from "@/platform/project";
@@ -161,18 +161,37 @@ export function SessionComposer({
const catalog = useAgents((s) => s.modelCatalogs.get(task.provider));
const requestingModels = useAgents((s) => s.modelRequests.has(task.provider));
const model = task.config.find((o) => o.category === "model");
const canRefreshModels = task.status !== "archived" && !!model && !!provider?.installed && project?.trusted !== false;
const candidateModels = canRefreshModels
? (catalog?.config ?? provider?.config)?.find((o) => o.category === "model")?.values
: undefined;
const catalogModel = (catalog?.config ?? provider?.config)?.find((o) => o.category === "model");
const canRefreshModels =
task.status !== "archived" &&
(!!model || !!task.model || !!catalogModel) &&
!!provider?.installed &&
project?.trusted !== false;
const pickerConfig = useMemo(() => {
if (!model || !candidateModels?.length) return task.config;
if (!canRefreshModels) return task.config;
if (!model) {
const recovered: AgentConfigOption =
catalogModel === undefined
? {
id: "model",
name: "Model",
description: null,
category: "model",
current: task.model,
values: [],
via: "option",
}
: { ...catalogModel, current: task.model ?? catalogModel.current };
return [...task.config, recovered];
}
const candidateModels = catalogModel?.values;
if (!candidateModels?.length) return task.config;
const sessionModels = new Set(model.values.map((v) => v.value));
const extra = candidateModels.filter((v) => !sessionModels.has(v.value));
if (!extra.length) return task.config;
const pickerModel = { ...model, values: [...model.values, ...extra] };
return task.config.map((o) => (o === model ? pickerModel : o));
}, [task.config, model, candidateModels]);
}, [task.config, task.model, model, catalogModel, canRefreshModels]);
const [sending, setSending] = useState(false);
const configChange = useRef<{ loadingModel: boolean } | null>(null);
const [configuring, setConfiguring] = useState<typeof configChange.current>(null);
+1 -1
View File
@@ -421,7 +421,7 @@ export async function refreshModels(
export async function refreshTaskModels(id: string, force = true): Promise<void> {
const { tasks, providers } = useAgents.getState();
const task = tasks.get(id);
if (!task || task.status === "archived" || !task.config.some((o) => o.category === "model")) return;
if (!task || task.status === "archived" || (!task.model && !task.config.some((o) => o.category === "model"))) return;
const provider = providers.find((p) => p.id === task.provider);
if (!provider?.installed || useProject.getState().project?.trusted === false) return;
await refreshProviderModels(provider, force, null, null);
@@ -292,7 +292,7 @@ describe("debug tool window", () => {
expect(screen.getByRole("tab", { name: /main/ })).toBeTruthy();
expect(screen.getByRole("tab", { name: "Threads & Variables" })).toBeTruthy();
expect(screen.getByRole("tab", { name: "Console" })).toBeTruthy();
expect(screen.getByText(", main.py:12")).toBeTruthy();
expect(screen.getByRole("option", { selected: true })).toHaveTextContent("main:12, main.py");
expect(screen.getByPlaceholderText("Evaluate expression (↩) or add a watch (⇧⌘↩)")).toBeTruthy();
expect(await screen.findByText("{int}")).toBeTruthy();
expect(screen.getByText("'hi'")).toBeTruthy();
@@ -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…");
@@ -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");
+5
View File
@@ -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}`;
@@ -102,11 +102,20 @@
display: flex;
flex-direction: column;
min-height: 0;
padding: 4px 0;
padding-bottom: var(--space-1);
}
.threadHeader {
display: flex;
align-items: center;
flex: none;
height: 30px;
padding: 0 var(--space-1);
border-bottom: 1px solid var(--border);
}
.threadSelect {
margin: 0 8px 4px;
max-width: 100%;
}
.frameList {
@@ -116,7 +125,7 @@
display: flex;
flex-direction: column;
outline: none;
padding: 0 4px;
padding: var(--space-1) var(--space-1) 0;
}
.frame {
@@ -150,24 +159,36 @@
flex: none;
}
.frameName {
.frameText,
.frameLabel {
display: flex;
align-items: baseline;
min-width: 0;
}
.frameText {
flex: 1;
}
.frameLine {
flex: none;
}
.frameName,
.frameFile {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
}
.frameFile {
flex: 1;
min-width: 0;
/* ", File.java:12" hugs the name, cancelling the row gap. */
margin-left: -6px;
flex: 0 1000 auto;
min-width: min(12ch, 32%);
color: var(--fg-subtle);
overflow: hidden;
text-overflow: ellipsis;
font-size: var(--fs-small);
}
.hiddenFrames {
display: block;
overflow: hidden;
text-overflow: ellipsis;
color: var(--fg-subtle);
font-style: italic;
}
+33 -18
View File
@@ -1,6 +1,6 @@
/** Debug tool window: toolbar, Threads & Variables (frames + variables), Console. */
import { writeClipboardText } from "@/platform/clipboard";
import { useEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";
import clsx from "clsx";
import { executeAction } from "@/platform/actions";
import { basename, useProject } from "@/platform/project";
@@ -22,6 +22,7 @@ import {
type TabItem,
T,
} from "@/ui";
import { revealVertically } from "@/ui/Tabs";
import { setMuted, useBreakpoints } from "../breakpoints/store";
import { frameLabel, groupFrames } from "../frames";
import { blurDebugView, focusDebugView } from "./focusedView";
@@ -347,10 +348,15 @@ function ThreadsAndVariables({ session }: { session: DebugSession }) {
function FramesPane({ session }: { session: DebugSession }) {
const root = useProject((s) => s.project?.root ?? null);
const [showAll, setShowAll] = useState(false);
const list = useRef<HTMLDivElement>(null);
const selectedRow = useRef<HTMLButtonElement>(null);
const items = useMemo(
() => groupFrames(session.frames, root, session.selectedFrame, showAll),
[session.frames, root, session.selectedFrame, showAll],
);
useLayoutEffect(() => {
if (list.current && selectedRow.current) revealVertically(list.current, selectedRow.current);
}, [items]);
const paused = session.status === "paused";
const onKeyDown = (e: KeyboardEvent) => {
if (e.key !== "ArrowDown" && e.key !== "ArrowUp") return;
@@ -365,19 +371,24 @@ function FramesPane({ session }: { session: DebugSession }) {
return (
<div className={styles.frames}>
{session.threads.length > 0 && (
<Select
value={session.selectedThread != null ? String(session.selectedThread) : null}
options={session.threads.map((t) => ({
value: String(t.id),
label: t.name,
detail: t.id === session.stoppedThread ? "suspended" : undefined,
}))}
onChange={(v) => void selectThread(session.id, +v)}
aria-label="Thread"
className={styles.threadSelect}
/>
<div className={styles.threadHeader}>
<Select
value={session.selectedThread != null ? String(session.selectedThread) : null}
options={session.threads.map((t) => ({
value: String(t.id),
label: t.name,
verbatim: true,
detail: t.id === session.stoppedThread ? "suspended" : undefined,
}))}
onChange={(v) => void selectThread(session.id, +v)}
aria-label="Thread"
variant="ghost"
className={styles.threadSelect}
/>
</div>
)}
<div
ref={list}
className={styles.frameList}
role="listbox"
aria-label={tx("Frames")}
@@ -415,9 +426,11 @@ function FramesPane({ session }: { session: DebugSession }) {
) : (
<button
key={item.frame.id}
ref={item.frame.id === session.selectedFrame ? selectedRow : undefined}
type="button"
role="option"
aria-selected={item.frame.id === session.selectedFrame}
title={item.frame.path ? `${frameLabel(item.frame)}, ${basename(item.frame.path)}` : item.frame.name}
className={clsx(
styles.frame,
item.frame.id === session.selectedFrame && styles.frameSelected,
@@ -459,13 +472,15 @@ function FramesPane({ session }: { session: DebugSession }) {
}}
>
<Icon name="method" size={16} className={styles.frameIcon} />
<span className={styles.frameName}>{item.frame.name}</span>
{item.frame.path && (
<span className={styles.frameFile}>
, {basename(item.frame.path)}
{item.frame.line >= 0 ? `:${item.frame.line + 1}` : ""}
<span className={styles.frameText}>
<span className={styles.frameLabel}>
<span className={styles.frameName}>{item.frame.name}</span>
{item.frame.path && item.frame.line >= 0 && (
<span className={styles.frameLine}>:{item.frame.line + 1}</span>
)}
</span>
)}
{item.frame.path && <span className={styles.frameFile}>, {basename(item.frame.path)}</span>}
</span>
</button>
),
)}
+14 -2
View File
@@ -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) });
+1 -1
View File
@@ -265,7 +265,7 @@ function HeaderTable({ headers }: { headers: Array<[string, string]> }) {
export function HttpClientView() {
const history = useHttpClient((s) => s.history);
const selected = useHttpClient((s) => s.selected);
const exchange = useHttpClient((s) => (s.selected ? s.exchanges[s.selected] : undefined));
const exchange = useHttpClient((s) => s.exchanges.find((e) => e.entry.id === s.selected));
const running = useHttpClient((s) => s.running);
useEffect(() => {
void refreshHistory();
@@ -39,11 +39,11 @@ const exchange: HttpExchange = {
};
describe("HTTP response find", () => {
afterEach(() => useHttpClient.setState({ history: [], exchanges: {}, selected: null }));
afterEach(() => useHttpClient.setState({ history: [], exchanges: [], selected: null }));
it("opens a find bar with ⌘F in the response and marks the matches", () => {
Element.prototype.scrollIntoView ??= () => {};
useHttpClient.setState({ history: [exchange.entry], exchanges: { e1: exchange }, selected: "e1" });
useHttpClient.setState({ history: [exchange.entry], exchanges: [exchange], selected: "e1" });
render(<HttpClientView />);
const body = screen.getByLabelText("Response body");
fireEvent.keyDown(body, { key: "f", metaKey: true, ctrlKey: true });
+8 -2
View File
@@ -237,6 +237,12 @@ function annotation(p: Param, name: string): Annotation | undefined {
const isMap = (type: string) =>
/^(java\.util\.)?(Map|MultiValueMap|HttpHeaders|LinkedMultiValueMap|HashMap)\b/.test(type);
/** `name=value` of a `params`/`headers` condition. Only the first "=" divides it: `Accept=text/plain;charset=UTF-8`. */
function condition(cond: string): [name: string, value: string | undefined] {
const at = cond.indexOf("=");
return at < 0 ? [cond, undefined] : [cond.slice(0, at), cond.slice(at + 1)];
}
function endpoint(cls: ClassDecl, method: ClassDecl["methods"][number], c: Constants): Endpoint | null {
const m = mapping(method.annotations);
if (!m) return null;
@@ -267,12 +273,12 @@ function endpoint(cls: ClassDecl, method: ClassDecl["methods"][number], c: Const
}
// `params = "a=1"` / `headers = "X-Api=1"` narrow the mapping: the request must carry them.
for (const cond of [...c.strings(classMapping?.args.get("params")), ...c.strings(m.ann.args.get("params"))]) {
const [name, value] = cond.split("=", 2);
const [name, value] = condition(cond);
if (name && !cond.includes("!") && !query.some((q) => q.name === name.trim()))
query.push({ name: name.trim(), value: value?.trim() ?? null });
}
for (const cond of [...c.strings(classMapping?.args.get("headers")), ...c.strings(m.ann.args.get("headers"))]) {
const [name, value] = cond.split("=", 2);
const [name, value] = condition(cond);
if (name && !cond.includes("!") && value !== undefined) headers.push({ name: name.trim(), value: value.trim() });
}
const first = (key: string) =>
@@ -198,6 +198,32 @@ describe("Spring mappings (Kotlin)", () => {
});
});
describe("mapping conditions", () => {
it("keeps a value that has its own '='", () => {
const [controller] = springControllers(`package demo;
import org.springframework.web.bind.annotation.*;
@RestController
public class ReportController {
@GetMapping(path = "/report", headers = "Accept=text/plain;charset=UTF-8", params = "range=a=b")
public String report() { return ""; }
@PostMapping(path = "/upload", headers = {"Content-Type=multipart/form-data; boundary=xyz", "X-Token=YWJj=="})
public void upload() {}
}
`);
const [report, upload] = controller!.endpoints;
expect(report).toMatchObject({
query: [{ name: "range", value: "a=b" }],
headers: [{ name: "Accept", value: "text/plain;charset=UTF-8" }],
});
expect(upload!.headers).toEqual([
{ name: "Content-Type", value: "multipart/form-data; boundary=xyz" },
{ name: "X-Token", value: "YWJj==" },
]);
});
});
describe("non-controllers", () => {
it("ignores classes that are not controllers and files without any", () => {
expect(springControllers('@Service class A { @GetMapping("/x") void a() {} }')).toEqual([]);
+39 -1
View File
@@ -1,10 +1,11 @@
import { beforeEach, expect, it, vi } from "vitest";
import type { HttpExchange, HttpRequestBlock } from "@/platform/ipc";
import { runAll, runRequest, setEnvironment, useHttpClient } from "./store";
import { runAll, runRequest, selectEntry, setEnvironment, useHttpClient } from "./store";
const backend = vi.hoisted(() => ({
httpEnvironments: vi.fn(),
httpExecute: vi.fn(),
httpHistoryGet: vi.fn(),
httpRequests: vi.fn(),
}));
vi.mock("@/platform/ipc", async (importOriginal) => {
@@ -95,3 +96,40 @@ it.each(["A", "missing"])("validates the starting choice %s once when environmen
expect(backend.httpExecute).toHaveBeenNthCalledWith(1, expect.any(Number), path, text, 0, environment);
expect(backend.httpExecute).toHaveBeenNthCalledWith(2, expect.any(Number), path, text, 1, environment);
});
function response(id: string): HttpExchange {
return { ...exchange, entry: { ...exchange.entry, id } };
}
it("keeps 100 history rows and the four most recently used exchanges", async () => {
for (let n = 0; n < 101; n++) {
backend.httpExecute.mockResolvedValueOnce(ok(response(String(n))));
await runRequest(null, text, 0);
}
const state = useHttpClient.getState();
expect(state.history).toHaveLength(100);
expect(state.history.at(-1)?.id).toBe("1");
expect(state.exchanges).toHaveLength(4);
await selectEntry("97"); // Touch the oldest resident before opening a cold row.
backend.httpHistoryGet.mockResolvedValueOnce(ok(response("1")));
await selectEntry("1");
await selectEntry("97");
expect(backend.httpHistoryGet.mock.calls).toEqual([["1"]]);
expect(useHttpClient.getState().exchanges.map((e) => e.entry.id)).toEqual(["97", "1", "100", "99"]);
});
it("keeps the latest selection when two cold reads finish out of order", async () => {
let finishFirst!: (result: ReturnType<typeof ok<HttpExchange>>) => void;
const first = new Promise<ReturnType<typeof ok<HttpExchange>>>((resolve) => {
finishFirst = resolve;
});
backend.httpHistoryGet.mockReturnValueOnce(first).mockResolvedValueOnce(ok(response("b")));
const pending = selectEntry("a");
await selectEntry("b");
finishFirst(ok(response("a")));
await pending;
const { selected, exchanges } = useHttpClient.getState();
expect(selected).toBe("b");
expect(exchanges).toEqual([response("b")]);
});
+22 -9
View File
@@ -14,6 +14,9 @@ import { writeClipboardText } from "@/platform/clipboard";
import { editorService, notifications, showServiceView, showStatusInfo } from "@/workbench/contributions";
export const SERVICE_VIEW = "httpClient";
// Same bound as ide_http::history::MAX_ENTRIES. Only recent rows keep their bodies in the UI.
const HISTORY_LIMIT = 100;
const EXCHANGE_LIMIT = 4;
const ENV_KEY = "openidea.httpClient.environments";
function readEnvChoices(): Record<string, string> {
@@ -41,8 +44,8 @@ interface HttpClientState {
environments: Record<string, string[]>;
/** History entries, newest first (this session's runs included). */
history: HttpHistoryEntry[];
/** Loaded exchanges by entry id. */
exchanges: Record<string, HttpExchange>;
/** Loaded exchanges, most recently viewed first. */
exchanges: HttpExchange[];
selected: string | null;
running: Running | null;
}
@@ -51,7 +54,7 @@ export const useHttpClient = create<HttpClientState>(() => ({
envByFile: readEnvChoices(),
environments: {},
history: [],
exchanges: {},
exchanges: [],
selected: null,
running: null,
}));
@@ -96,6 +99,10 @@ function effectiveEnvironment(path: string | null, selection?: string | null): s
return null;
}
function rememberExchange(exchange: HttpExchange, recent: HttpExchange[]) {
return [exchange, ...recent.filter((e) => e.entry.id !== exchange.entry.id)].slice(0, EXCHANGE_LIMIT);
}
export async function refreshHistory() {
try {
const history = await call(commands.httpHistory());
@@ -106,12 +113,18 @@ export async function refreshHistory() {
}
export async function selectEntry(id: string) {
const { exchanges } = useHttpClient.getState();
const cached = exchanges.find((e) => e.entry.id === id);
if (cached) {
useHttpClient.setState({ selected: id, exchanges: rememberExchange(cached, exchanges) });
return;
}
useHttpClient.setState({ selected: id });
if (useHttpClient.getState().exchanges[id]) return;
try {
const ex = await call(commands.httpHistoryGet(id));
useHttpClient.setState((s) => ({ exchanges: { ...s.exchanges, [id]: ex } }));
useHttpClient.setState((s) => (s.selected === id ? { exchanges: rememberExchange(ex, s.exchanges) } : s));
} catch (e) {
if (useHttpClient.getState().selected !== id) return;
notifications().notify({
level: "error",
title: "Cannot open the response",
@@ -122,7 +135,7 @@ export async function selectEntry(id: string) {
export async function clearHistory() {
await call(commands.httpHistoryClear());
useHttpClient.setState({ history: [], exchanges: {}, selected: null });
useHttpClient.setState({ history: [], exchanges: [], selected: null });
}
export function parseRequests(text: string): Promise<HttpRequestBlock[]> {
@@ -159,8 +172,8 @@ export async function runRequest(
const env = batchEnvironment === undefined ? effectiveEnvironment(path) : batchEnvironment;
const ex = await call(commands.httpExecute(request, path, text, index, env));
useHttpClient.setState((s) => ({
history: [ex.entry, ...s.history.filter((h) => h.id !== ex.entry.id)],
exchanges: { ...s.exchanges, [ex.entry.id]: ex },
history: [ex.entry, ...s.history.filter((h) => h.id !== ex.entry.id)].slice(0, HISTORY_LIMIT),
exchanges: rememberExchange(ex, s.exchanges),
selected: ex.entry.id,
}));
return true;
@@ -235,5 +248,5 @@ export function cancelRunning() {
/** The window switched projects: history, responses and environments belong to the previous one. */
export function resetHttpClient() {
cancelRunning();
useHttpClient.setState({ environments: {}, history: [], exchanges: {}, selected: null, running: null });
useHttpClient.setState({ environments: {}, history: [], exchanges: [], selected: null, running: null });
}
+25
View File
@@ -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() }]
+129
View File
@@ -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<object>()), executeAction: actions.executeAction }));
vi.mock("@tanstack/react-virtual", () => ({
useVirtualizer: ({ count }: { count: number }) => ({
getTotalSize: () => count * 20,
getVirtualItems: () => Array.from({ length: count }, (_, index) => ({ index, start: index * 20, key: index })),
scrollToIndex: () => {},
measureElement: () => {},
measure: () => {},
}),
}));
beforeEach(() => {
actions.executeAction.mockClear();
useProject.setState({ settings: null });
window.getSelection()?.removeAllRanges();
});
afterEach(() => act(hideContextMenu));
function setup(chunks: { kind: "stdout" | "stderr" | "system"; text: string }[]) {
const model = new ConsoleModel();
for (const c of chunks) model.append(c);
model.flush();
const { container } = render(
<ConsoleView model={model} version={1} softWrap={false} follow={false} onFollowChange={() => {}} cwd="/" />,
);
return within(container).getByRole("log");
}
function foldItem(target: Element) {
fireEvent.contextMenu(target);
const items = useContextMenuStore.getState().menu?.items ?? [];
return items.find((i) => "label" in i && i.label === "Fold Lines Like This") as
| { disabled?: boolean; run?: () => void }
| undefined;
}
function select(node: Node, start: number, end: number) {
const range = document.createRange();
range.setStart(node, start);
range.setEnd(node, end);
window.getSelection()!.removeAllRanges();
window.getSelection()!.addRange(range);
}
describe("foldLineText", () => {
it("takes a one-line selection, else the clicked line, trimmed", () => {
expect(foldLineText(" at org.junit.Assert ", "ignored")).toBe("at org.junit.Assert");
expect(foldLineText("", "\tat java.base/Thread.run(Thread.java:1583) ")).toBe(
"at java.base/Thread.run(Thread.java:1583)",
);
// A whole row picked by a triple click ends in its line break.
expect(foldLineText("DEBUG pool\n", null)).toBe("DEBUG pool");
});
it("has nothing for a selection across lines, a blank selection or a blank line", () => {
expect(foldLineText("first\nsecond", "first")).toBeNull();
expect(foldLineText("first\r\nsecond", "first")).toBeNull();
expect(foldLineText(" ", "a line")).toBeNull();
expect(foldLineText("", " ")).toBeNull();
expect(foldLineText("", null)).toBeNull();
});
});
describe("Fold Lines Like This", () => {
it("opens Settings › Console with the clicked line to add as a fold pattern", () => {
const log = setup([
{
kind: "stdout",
text: "start\n at org.springframework.test.context.TestContextManager.prepare(TestContextManager.java:248)\n",
},
]);
const row = log.querySelectorAll("[data-index]")[1]!;
const item = foldItem(row.firstElementChild ?? row)!;
expect(item.disabled).toBeFalsy();
item.run!();
expect(actions.executeAction).toHaveBeenCalledWith(
"file.settings",
"build.console#at org.springframework.test.context.TestContextManager.prepare(TestContextManager.java:248)",
);
});
it("uses the selected part of a line rather than the whole line", () => {
const log = setup([{ kind: "stdout", text: "12:00 DEBUG pool: idle\n" }]);
const row = log.querySelector("[data-index]")!;
const text = document.createTreeWalker(row, NodeFilter.SHOW_TEXT).nextNode()!;
select(text, 6, 11);
foldItem(row)!.run!();
expect(actions.executeAction).toHaveBeenCalledWith("file.settings", "build.console#DEBUG");
});
it("is disabled for a selection over several lines", () => {
const log = setup([{ kind: "stdout", text: "one\ntwo\n" }]);
const rows = log.querySelectorAll("[data-index]");
const range = document.createRange();
range.setStart(rows[0]!, 0);
range.setEnd(rows[1]!, rows[1]!.childNodes.length);
window.getSelection()!.removeAllRanges();
window.getSelection()!.addRange(range);
expect(foldItem(rows[0]!)!.disabled).toBe(true);
});
it("is disabled on a blank line, the IDE's own messages and a folded run", () => {
useProject.setState({ settings: { console: { foldPatterns: ["at org."] } } as never });
const log = setup([
{ kind: "stdout", text: "\n" },
{ kind: "system", text: "Process finished with exit code 0\n" },
]);
const rows = log.querySelectorAll("[data-index]");
expect(foldItem(rows[0]!)!.disabled).toBe(true);
expect(foldItem(rows[1]!)!.disabled).toBe(true);
act(hideContextMenu);
const folded = setup([{ kind: "stdout", text: "at org.a\nat org.b\n" }]);
const fold = folded.querySelector("[data-index]")!;
expect(fold.textContent).toContain("internal lines");
expect(foldItem(fold)!.disabled).toBe(true);
expect(actions.executeAction).not.toHaveBeenCalled();
});
});
@@ -102,6 +102,20 @@
.locations > * {
flex: 1;
}
.switcher {
min-height: min(350px, 80vh);
}
.switcher .columns {
flex: auto;
height: auto;
max-height: 440px;
}
.switcher .tools {
width: clamp(112px, 32%, 184px);
}
.switcher .footer {
font-size: var(--fs-small);
}
.locationsLink {
flex: none;
display: flex;
@@ -267,6 +281,13 @@
.tools .shortcut {
display: none;
}
.switcher .columns {
--list-inset: var(--space-1);
}
.switcher .columns [role="option"] {
gap: var(--space-1);
padding-inline: var(--space-1);
}
.locationsLink {
margin-inline: var(--space-1);
}
+2 -2
View File
@@ -325,9 +325,9 @@ function RecentFilesDialog() {
open
onClose={hideRecentPopup}
restoreFocus={keepFocus}
width={720}
width={switcher ? 560 : 720}
aria-label={title}
className={styles.dialog}
className={clsx(styles.dialog, switcher && styles.switcher)}
>
<header className={styles.header}>
<span className={styles.title}>
@@ -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<typeof import("@/platform/ipc")>();
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(<SettingsDialog />);
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"]),
);
});
@@ -1,25 +1,35 @@
.tabs {
margin-bottom: var(--space-3);
}
.fileTypes {
display: grid;
grid-template-columns: minmax(180px, 260px) minmax(0, 1fr);
gap: var(--space-3);
container: file-types / inline-size;
height: clamp(382px, 67vh, 500px);
min-width: 0;
}
.split {
height: 100%;
}
.types {
display: flex;
flex-direction: column;
gap: var(--space-1-5);
min-width: 0;
height: 100%;
padding-inline-end: var(--space-2);
}
.filter {
flex: none;
width: 100%;
}
.typeList {
display: flex;
flex-direction: column;
max-height: 420px;
flex: 1;
min-height: 0;
overflow: auto;
padding: 2px 0;
border-radius: var(--radius-small);
@@ -27,11 +37,12 @@
}
.type {
flex: none;
display: flex;
align-items: center;
gap: var(--space-1-5);
height: var(--h-row);
padding: 0 8px;
padding: 0 var(--space-2);
border: none;
background: none;
color: var(--fg);
@@ -65,6 +76,20 @@
flex-direction: column;
gap: var(--space-1);
min-width: 0;
height: 100%;
overflow: auto;
padding-inline-start: var(--space-3);
}
.patterns > .patternRow {
flex: none;
margin-inline: 0;
padding-inline: 0;
}
.patterns [role="listbox"] {
min-height: 72px;
max-height: 128px;
}
.note {
@@ -74,10 +99,17 @@
.code {
font-family: var(--font-mono);
overflow-wrap: anywhere;
}
@media (max-width: 640px) {
.fileTypes {
grid-template-columns: minmax(0, 1fr);
@container file-types (width < 530px) {
.types {
padding-inline-end: 0;
padding-block-end: var(--space-2);
}
.patterns {
padding-inline-start: 0;
padding-block-start: var(--space-2);
}
}
+88 -62
View File
@@ -4,9 +4,9 @@
* user's) and hashbang patterns, stored in `files.fileTypes`. The backend
* detects languages with them; open editors re-detect when they change.
*/
import { useEffect, useMemo, useState } from "react";
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import clsx from "clsx";
import { Icon, Input, T, fileIconName } from "@/ui";
import { Icon, Input, SplitGroup, SplitHandle, SplitPanel, T, fileIconName } from "@/ui";
import { commands, isTauri, type LanguageInfo_Serialize as LanguageInfo } from "@/platform/ipc";
import {
addPattern,
@@ -52,6 +52,19 @@ export function applyPatternEdit(
}
export function RecognizedFileTypes() {
const desktop = isTauri();
const container = useRef<HTMLDivElement>(null);
const [stacked, setStacked] = useState(true);
useLayoutEffect(() => {
const element = container.current;
if (!element) return;
const measure = () => setStacked(element.clientWidth < 530);
measure();
if (typeof ResizeObserver === "undefined") return;
const observer = new ResizeObserver(measure);
observer.observe(element);
return () => observer.disconnect();
}, [desktop]);
const langs = useLanguages();
const [assoc, setAssoc] = useSetting<FileTypeAssociations>("files.fileTypes");
const [filter, setFilter] = useState("");
@@ -68,74 +81,87 @@ export function RecognizedFileTypes() {
}, [langs, filter, assoc]);
// Keep the last explicit choice for when it becomes visible again.
const selected = shown.find((l) => l.id === selectedId) ?? shown[0] ?? null;
if (!isTauri()) return null;
if (!desktop) return null;
const current = assoc ?? {};
const patterns = selected ? effectivePatterns(selected, current).map((p) => p.pattern) : [];
const hashbangs = selected ? (current[selected.id]?.hashbangs ?? []) : [];
return (
<div className={styles.fileTypes}>
<div className={styles.types}>
<Input
className={styles.filter}
value={filter}
placeholder="Filter file types"
aria-label="Filter file types"
onChange={(e) => setFilter(e.target.value)}
/>
<div className={styles.typeList} role="listbox" aria-label={tx("Recognized file types")}>
{shown.map((l) => {
const sample = sampleFileName(l);
return (
<button
key={l.id}
type="button"
role="option"
aria-selected={l.id === selected?.id}
className={clsx(styles.type, l.id === selected?.id && styles.typeSelected)}
onClick={() => setSelectedId(l.id)}
<div className={styles.fileTypes} ref={container}>
<SplitGroup orientation={stacked ? "vertical" : "horizontal"} className={styles.split}>
<SplitPanel defaultSize="34%" minSize={stacked ? "106px" : "148px"}>
<div className={styles.types}>
<Input
className={styles.filter}
value={filter}
placeholder="Filter file types"
aria-label="Filter file types"
onChange={(e) => setFilter(e.target.value)}
/>
<div className={styles.typeList} role="listbox" aria-label={tx("Recognized file types")}>
{shown.map((l) => {
const sample = sampleFileName(l);
return (
<button
key={l.id}
type="button"
role="option"
aria-selected={l.id === selected?.id}
className={clsx(styles.type, l.id === selected?.id && styles.typeSelected)}
onClick={() => setSelectedId(l.id)}
>
<Icon name={sample ? fileIconName(sample) : "file-text"} size={16} />
<span className={styles.typeName}>{l.name}</span>
{current[l.id] && (
<span className={styles.modified}>
<T>modified</T>
</span>
)}
</button>
);
})}
</div>
</div>
</SplitPanel>
<SplitHandle aria-label={tx("Resize file type panes")} />
<SplitPanel defaultSize="66%" minSize={stacked ? "196px" : "190px"}>
{selected && (
<div className={styles.patterns} key={selected.id}>
<Row
className={styles.patternRow}
label="File name patterns"
stacked
hint="* matches any characters, ? one (e.g. *.foo, Jenkinsfile)."
>
<Icon name={sample ? fileIconName(sample) : "file-text"} size={16} />
<span className={styles.typeName}>{l.name}</span>
{current[l.id] && (
<span className={styles.modified}>
<T>modified</T>
</span>
)}
</button>
);
})}
</div>
</div>
{selected && (
<div className={styles.patterns} key={selected.id}>
<Row label="File name patterns" stacked hint="* matches any characters, ? one (e.g. *.foo, Jenkinsfile).">
<GlobListEditor
value={patterns}
onChange={(next) => setAssoc(applyPatternEdit(current, langs, selected, next))}
placeholder="*.ext"
aria-label={tx`File name patterns of ${selected.name}`}
/>
</Row>
<Row
label="Hashbang patterns"
stacked
hint="Interpreters run by a #! first line, e.g. node for #!/usr/bin/env node."
>
<GlobListEditor
value={hashbangs}
onChange={(next) => setAssoc(setHashbangs(current, selected.id, next))}
placeholder="interpreter"
aria-label={tx`Hashbang patterns of ${selected.name}`}
/>
</Row>
{selected.firstLine && (
<div className={styles.note}>
<T>Also recognized by its first line:</T> <code className={styles.code}>{selected.firstLine}</code>
<GlobListEditor
value={patterns}
onChange={(next) => setAssoc(applyPatternEdit(current, langs, selected, next))}
placeholder="*.ext"
aria-label={tx`File name patterns of ${selected.name}`}
/>
</Row>
<Row
className={styles.patternRow}
label="Hashbang patterns"
stacked
hint="Interpreters run by a #! first line, e.g. node for #!/usr/bin/env node."
>
<GlobListEditor
value={hashbangs}
onChange={(next) => setAssoc(setHashbangs(current, selected.id, next))}
placeholder="interpreter"
aria-label={tx`Hashbang patterns of ${selected.name}`}
/>
</Row>
{selected.firstLine && (
<div className={styles.note}>
<T>Also recognized by its first line:</T> <code className={styles.code}>{selected.firstLine}</code>
</div>
)}
</div>
)}
</div>
)}
</SplitPanel>
</SplitGroup>
</div>
);
}
+88 -17
View File
@@ -1,9 +1,14 @@
/** Built-in settings pages (IDEA layout: Appearance & Behavior, Keymap, Editor). */
import { useId, useState } from "react";
import { Tabs } from "@/ui";
import { GlobListEditor, Row } from "../components/Form";
import { useSetting } from "../components/context";
import { useSearchQuery, useSetting } from "../components/context";
import { keymapSearchLabels } from "../keymap/model";
import { labelMatches, queryTerms } from "../model/pages";
import { lazyPage } from "./lazyPage";
import type { PageSpec } from "./spec";
import { OptionsPage } from "./OptionsPage";
import { specLabels, type PageSpec, type SectionSpec } from "./spec";
import styles from "./FileTypes.module.css";
export const EDITOR_GROUP = "Editor";
const KeymapPage = lazyPage("keymap", () => import("../keymap/KeymapPage").then((m) => m.KeymapPage));
@@ -38,22 +43,10 @@ function IgnoredNamesRow() {
);
}
export const BUILTIN_PAGES: PageSpec[] = [
const FILE_TYPE_TABS: { id: string; label: string; sections: SectionSpec[] }[] = [
{
id: "keymap",
title: "Keymap",
order: 10,
keywords: ["shortcut", "keyboard", "hotkey", "binding", "preset", "vs code", "intellij"],
component: KeymapPage,
dynamicLabels: keymapSearchLabels,
},
{
id: "editor.files",
title: "File Types",
group: EDITOR_GROUP,
order: 29,
projectScope: true,
keywords: ["ignore", "ignored", "excluded", "glob", "exclude patterns", "associate", "association", "extension"],
id: "recognized",
label: "Recognized File Types",
sections: [
{
title: "Recognized File Types",
@@ -77,6 +70,12 @@ export const BUILTIN_PAGES: PageSpec[] = [
},
],
},
],
},
{
id: "ignored",
label: "Ignored Files and Folders",
sections: [
{
title: "Ignored Files and Folders",
options: [
@@ -87,3 +86,75 @@ export const BUILTIN_PAGES: PageSpec[] = [
],
},
];
const FILE_TYPES: PageSpec = {
id: "editor.files",
title: "File Types",
group: EDITOR_GROUP,
order: 29,
projectScope: true,
keywords: ["ignore", "ignored", "excluded", "glob", "exclude patterns", "associate", "association", "extension"],
sections: FILE_TYPE_TABS.flatMap((tab) => tab.sections),
component: FileTypesPage,
};
function FileTypesPage() {
const prefix = useId();
const query = useSearchQuery();
const [selection, select] = useState({ id: "recognized", query: "" });
let active = selection.id;
if (query !== selection.query) {
const terms = queryTerms(query);
let best = 0;
for (const tab of FILE_TYPE_TABS) {
const labels = specLabels({ ...FILE_TYPES, keywords: [], sections: tab.sections });
const score = terms.filter((term) => labels.some((label) => labelMatches(label, term))).length;
if (score > best) {
best = score;
active = tab.id;
}
}
}
return (
<>
<Tabs
aria-label="File Types"
variant="compact"
layout="wrap"
className={styles.tabs}
items={FILE_TYPE_TABS.map(({ id, label }) => ({ id, label }))}
activeId={active}
panelIdPrefix={prefix}
onSelect={(id) => select({ id, query })}
/>
{FILE_TYPE_TABS.map(({ id, sections }) => (
<div
key={id}
role="tabpanel"
id={`${prefix}-panel-${id}`}
aria-labelledby={`${prefix}-tab-${id}`}
hidden={id !== active}
>
<OptionsPage
spec={{
...FILE_TYPES,
sections: sections.map((section, i) => (i === 0 ? { ...section, title: undefined } : section)),
}}
/>
</div>
))}
</>
);
}
export const BUILTIN_PAGES: PageSpec[] = [
{
id: "keymap",
title: "Keymap",
order: 10,
keywords: ["shortcut", "keyboard", "hotkey", "binding", "preset", "vs code", "intellij"],
component: KeymapPage,
dynamicLabels: keymapSearchLabels,
},
FILE_TYPES,
];
@@ -5,8 +5,20 @@ import { SCHEME_SUBPAGES, languagePageId } from "./colorSchemeMeta";
* italic / effects editor, and a live preview. Edits are staged in
* `editor.colorOverrides[scheme][attribute]`; `editor/core` injects them.
*/
import { useEffect, useMemo, useRef, useState, type CSSProperties } from "react";
import { Button, Checkbox, Icon, Input, Tree, type SelectOption, type TreeHandle, T } from "@/ui";
import { useEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from "react";
import {
Button,
Checkbox,
Icon,
Input,
SplitGroup,
SplitHandle,
SplitPanel,
Tree,
type SelectOption,
type TreeHandle,
T,
} from "@/ui";
import { fontWeightVars, type CustomColorSchemes, type TextAttributesOverride } from "@/platform/editorSettings";
import {
ATTRIBUTES,
@@ -1368,7 +1380,15 @@ function GitPreview({
);
}
export function ColorSchemePage({ scopes, landing }: { scopes: readonly string[]; landing?: boolean }) {
export function ColorSchemePage({
scopes,
landing,
children,
}: {
scopes: readonly string[];
landing?: boolean;
children?: ReactNode;
}) {
const translate = useTx();
const [scheme, setScheme] = useSetting<string>("editor.colorScheme", "global");
const [overrides, setOverrides] = useSetting<Overrides>("editor.colorOverrides", "global");
@@ -1580,7 +1600,7 @@ export function ColorSchemePage({ scopes, landing }: { scopes: readonly string[]
[],
);
return (
<div className={styles.page}>
<div className={landing ? styles.page : styles.schemePage}>
<div className={styles.schemeRow}>
<Row label="Scheme">
<Select value={scheme} options={options} onChange={setScheme} aria-label="Scheme" />
@@ -1631,84 +1651,88 @@ export function ColorSchemePage({ scopes, landing }: { scopes: readonly string[]
))}
</nav>
) : (
<>
<div className={styles.schemeBody} style={baseVars}>
<div className={styles.attrTree}>
<Tree<Node>
aria-label="Color scheme attributes"
roots={roots}
getKey={(n) => n.key}
getLabel={(n) => translate(n.label)}
getChildren={(n) => n.children}
isExpandable={(n) => !!n.children?.length}
expanded={expanded}
onExpandedChange={setExpanded}
handleRef={treeRef}
multiSelect={false}
selected={new Set([selected])}
onSelectionChange={(_s, lead) => lead?.attr && setSelected(lead.attr.id)}
renderNode={(n) => (
<span
className={`${styles.treeLabel} ${(n.attr ? mine?.[n.attr.id] : modifiedKeys.has(n.key)) ? styles.attrModified : ""}`}
>
{translate(n.label)}
</span>
)}
speedSearch
/>
</div>
{attr ? (
<div className={styles.attrPanel}>
<AttributeEditor
key={`${id}/${attr.id}`}
attr={attr}
inherited={inherited}
value={mine?.[attr.id]}
onChange={(v) => update(attr.id, v)}
<SplitGroup orientation="vertical" className={styles.schemeSplit}>
<SplitPanel defaultSize="62%" minSize="154px">
<div className={styles.schemeBody} style={baseVars}>
<div className={styles.attrTree}>
<Tree<Node>
aria-label="Color scheme attributes"
roots={roots}
getKey={(n) => n.key}
getLabel={(n) => translate(n.label)}
getChildren={(n) => n.children}
isExpandable={(n) => !!n.children?.length}
expanded={expanded}
onExpandedChange={setExpanded}
handleRef={treeRef}
multiSelect={false}
selected={new Set([selected])}
onSelectionChange={(_s, lead) => lead?.attr && setSelected(lead.attr.id)}
renderNode={(n) => (
<span
className={`${styles.treeLabel} ${(n.attr ? mine?.[n.attr.id] : modifiedKeys.has(n.key)) ? styles.attrModified : ""}`}
>
{translate(n.label)}
</span>
)}
speedSearch
/>
</div>
<section className={styles.attrPanel} aria-label={tx("Color scheme options")}>
{attr && (
<AttributeEditor
key={`${id}/${attr.id}`}
attr={attr}
inherited={inherited}
value={mine?.[attr.id]}
onChange={(v) => update(attr.id, v)}
/>
)}
{children && <div className={styles.schemeExtraOptions}>{children}</div>}
</section>
</div>
</SplitPanel>
<SplitHandle aria-label={tx("Resize color scheme preview")} />
<SplitPanel defaultSize="38%" minSize="88px">
{scopes[0] === "Git" ? (
<GitPreview vars={vars} ids={ids} reveal={reveal} />
) : (
<div />
)}
</div>
{scopes[0] === "Git" ? (
<GitPreview vars={vars} ids={ids} reveal={reveal} />
) : (
<pre className={styles.schemePreview} style={vars} aria-label={tx("Color scheme preview")}>
{sample.code.map((line, i) => (
<div key={i} className={`${styles.previewLine} ${i === sample.caret ? styles.previewCaretLine : ""}`}>
<span className={styles.previewGutter}>{i + 1}</span>
<code>
{line.map(([text, attrId], j) => {
const attr = attrId !== undefined ? A(attrId) : undefined;
const inPage = attr !== undefined && ids.has(attrId!);
return (
<span
key={j}
style={tokenStyle(attr)}
className={attr ? styles.clickable : undefined}
onClick={
attr
? () => {
if (inPage) reveal(attrId!);
else {
crossPageReveal = attrId!;
selectPage(attrPageId(attr));
<pre className={styles.schemePreview} style={vars} aria-label={tx("Color scheme preview")}>
{sample.code.map((line, i) => (
<div key={i} className={`${styles.previewLine} ${i === sample.caret ? styles.previewCaretLine : ""}`}>
<span className={styles.previewGutter}>{i + 1}</span>
<code>
{line.map(([text, attrId], j) => {
const attr = attrId !== undefined ? A(attrId) : undefined;
const inPage = attr !== undefined && ids.has(attrId!);
return (
<span
key={j}
style={tokenStyle(attr)}
className={attr ? styles.clickable : undefined}
onClick={
attr
? () => {
if (inPage) reveal(attrId!);
else {
crossPageReveal = attrId!;
selectPage(attrPageId(attr));
}
}
}
: undefined
}
>
{text}
</span>
);
})}
</code>
</div>
))}
</pre>
)}
</>
: undefined
}
>
{text}
</span>
);
})}
</code>
</div>
))}
</pre>
)}
</SplitPanel>
</SplitGroup>
)}
</div>
);
@@ -121,6 +121,24 @@
}
/* Font page */
.fontPage {
height: 100%;
min-height: 240px;
min-width: 0;
overflow: hidden;
border: 1px solid var(--border);
border-radius: var(--radius-small);
}
.fontSplit {
height: 100%;
}
.fontOptions {
container: font-options / inline-size;
height: 100%;
min-height: 0;
overflow-y: auto;
padding: var(--space-2) var(--space-3) var(--space-3);
}
.fontFamily {
display: flex;
align-items: center;
@@ -128,29 +146,51 @@
gap: var(--space-2);
min-width: 0;
}
.fontSelect {
.fontSelect,
.fontWeight {
width: 240px;
max-width: 100%;
}
@container font-options (max-width: 380px) {
.fontRow {
display: flex;
flex-direction: column;
align-items: stretch;
gap: var(--space-1);
margin-bottom: var(--space-1);
}
.fontRow > label {
padding-top: 0;
overflow-wrap: anywhere;
white-space: normal;
}
}
.previewTitle {
margin: 18px 0 6px;
color: var(--fg-strong);
flex: none;
padding: var(--space-1) var(--space-3);
border-bottom: 1px solid var(--border);
color: var(--fg-secondary);
font-size: var(--fs-small);
}
.previewArea {
flex: 1;
font-weight: var(--fw-code);
width: 100%;
min-height: 240px;
resize: vertical;
min-height: 0;
resize: none;
box-sizing: border-box;
padding: 8px 10px;
padding: var(--space-2) var(--space-3);
border: none;
border-radius: var(--radius-small);
box-shadow: inset 0 0 0 1px var(--border-strong);
background: var(--bg-editor, var(--bg-island));
color: var(--fg-editor, var(--fg));
white-space: pre;
white-space: pre-wrap;
overflow-wrap: anywhere;
outline: none;
}
.previewArea:focus-visible {
outline: 1px solid var(--focus-ring);
outline-offset: -1px;
}
/* Color Scheme page */
.schemeRow {
@@ -183,13 +223,38 @@
}
.schemeBody {
display: grid;
grid-template-columns: minmax(180px, 1fr) minmax(220px, 260px);
gap: 14px;
min-height: 320px;
grid-template-columns: minmax(0, 1fr) minmax(0, 280px);
gap: var(--space-2);
height: 100%;
min-height: 0;
padding-bottom: var(--space-2);
}
.schemePage {
display: flex;
flex-direction: column;
height: 100%;
min-height: 340px;
min-width: 0;
}
.schemeSplit {
flex: 1;
}
.schemePage > :not(.schemeSplit) {
flex: none;
}
.schemeExtraOptions {
margin-top: var(--space-4);
}
@container settings-content (max-width: 610px) {
.schemeBody {
grid-template-columns: minmax(0, 1fr);
grid-template-rows: minmax(72px, 2fr) minmax(0, 3fr);
}
}
.attrTree {
max-height: 360px;
overflow: auto;
min-height: 0;
min-width: 0;
overflow: hidden;
border-radius: var(--radius-small);
box-shadow: inset 0 0 0 1px var(--border-strong);
padding: 2px 0;
@@ -207,9 +272,9 @@
box-shadow: inset 0 0 0 1px var(--border-strong);
border-radius: var(--radius-small);
padding: 10px;
align-self: start;
min-width: 0;
min-height: 0;
overflow: auto;
max-height: 360px;
}
.attrEditor {
display: flex;
@@ -219,6 +284,7 @@
.attrRow {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: var(--space-2);
min-height: 28px;
}
@@ -234,7 +300,7 @@
}
.swatchInput {
flex: 1 1 90px;
min-width: 90px;
min-width: min(90px, 100%);
}
.colorBox {
position: relative;
@@ -258,7 +324,9 @@
font-size: var(--fs-small);
}
.schemePreview {
margin: 14px 0 0;
flex: 1;
min-height: 0;
margin: var(--space-2) 0 0;
padding: 8px 0;
border-radius: var(--radius-small);
box-shadow: inset 0 0 0 1px var(--border-strong);
@@ -269,7 +337,6 @@
font-size: var(--fs-code);
line-height: var(--lh-code);
overflow: auto;
max-height: 260px;
}
.previewLine {
display: flex;
@@ -298,12 +365,13 @@
/* Git preview mirrors the two real surfaces: the editor inline blame widget and
the project tree root branch suffix. Only the Git page uses these. */
.gitPreview {
margin: 14px 0 0;
flex: 1;
min-height: 0;
margin: var(--space-2) 0 0;
border-radius: var(--radius-small);
box-shadow: inset 0 0 0 1px var(--border-strong);
background: var(--bg-editor, var(--bg-island));
overflow: auto;
max-height: 260px;
}
.gitSection {
padding: 8px 0;
@@ -2,24 +2,34 @@ import { ATTRIBUTES, SCHEMES } from "@/platform/colorScheme";
import { lazyPage } from "../lazyPage";
import type { PageSpec } from "../spec";
import { LANGUAGES, SCHEME_SUBPAGES, languagePageId } from "./colorSchemeMeta";
import { editorPage } from "./kit";
import { editorPage, EditorSections, sectionLabels, type EditorSection } from "./kit";
const ALL_COLOR_SCHEME_PAGE_IDS = ["editor.colorScheme", ...SCHEME_SUBPAGES.map((p) => p.id)];
const LazyColorSchemePage = lazyPage(ALL_COLOR_SCHEME_PAGE_IDS, () =>
import("./ColorSchemeBody").then((m) => m.ColorSchemePage),
);
/** The scope chooser, import/export buttons and preview are identical on every sub-page. */
function colorSchemeSection(scopes: readonly string[]) {
function colorSchemePage(
spec: Pick<PageSpec, "id" | "title" | "order" | "keywords">,
scope: string,
extraSections: EditorSection[] = [],
): PageSpec {
const scopes = [scope];
const labels = [
"Scheme",
...ATTRIBUTES.filter((a) => a.path[0] === scope).map((a) => a.name),
...sectionLabels(extraSections),
];
return {
items: [
{
t: "custom" as const,
label: "Scheme",
keywords: ATTRIBUTES.filter((a) => scopes.includes(a.path[0]!)).map((a) => a.name),
component: () => <LazyColorSchemePage scopes={scopes} />,
},
],
...spec,
group: "Editor",
projectScope: false,
dynamicLabels: () => labels,
component: () => (
<LazyColorSchemePage scopes={scopes}>
{extraSections.length > 0 && <EditorSections sections={extraSections} />}
</LazyColorSchemePage>
),
};
}
@@ -55,22 +65,23 @@ const COLOR_SCHEME_PAGE = editorPage({
/** JetBrains layout: scopes and languages live in the settings tree under Color Scheme, one page each. */
export const COLOR_SCHEME_PAGES: PageSpec[] = [
COLOR_SCHEME_PAGE,
editorPage({
id: "editor.colorScheme.general",
title: "General",
order: 1,
projectScope: false,
keywords: ATTRIBUTES.filter((a) => a.path[0] === "General").map((a) => a.name),
sections: [colorSchemeSection(["General"])],
}),
editorPage({
id: "editor.colorScheme.language-defaults",
title: "Language Defaults",
order: 2,
projectScope: false,
keywords: ["semantic highlighting", "rainbow"],
sections: [
colorSchemeSection(["Language Defaults"]),
colorSchemePage(
{
id: "editor.colorScheme.general",
title: "General",
order: 1,
},
"General",
),
colorSchemePage(
{
id: "editor.colorScheme.language-defaults",
title: "Language Defaults",
order: 2,
keywords: ["semantic highlighting", "rainbow"],
},
"Language Defaults",
[
{
title: "Language Defaults",
items: [
@@ -101,39 +112,42 @@ export const COLOR_SCHEME_PAGES: PageSpec[] = [
],
},
],
}),
editorPage({
id: "editor.colorScheme.debugger",
title: "Debugger",
order: 3,
projectScope: false,
keywords: ["breakpoint", "inline values"],
sections: [colorSchemeSection(["Debugger"])],
}),
editorPage({
id: "editor.colorScheme.console-colors",
title: "Console Colors",
order: 4,
projectScope: false,
keywords: ["terminal", "ansi", "console", "background"],
sections: [colorSchemeSection(["Console Colors"])],
}),
editorPage({
id: "editor.colorScheme.git",
title: "Git",
order: 5,
projectScope: false,
keywords: ["git", "blame", "branch", "inline blame", "project view", "decoration"],
sections: [colorSchemeSection(["Git"])],
}),
),
colorSchemePage(
{
id: "editor.colorScheme.debugger",
title: "Debugger",
order: 3,
keywords: ["breakpoint", "inline values"],
},
"Debugger",
),
colorSchemePage(
{
id: "editor.colorScheme.console-colors",
title: "Console Colors",
order: 4,
keywords: ["terminal", "ansi", "console", "background"],
},
"Console Colors",
),
colorSchemePage(
{
id: "editor.colorScheme.git",
title: "Git",
order: 5,
keywords: ["git", "blame", "branch", "inline blame", "project view", "decoration"],
},
"Git",
),
...LANGUAGES.map((language, i) =>
editorPage({
id: languagePageId(language),
title: language,
order: 6 + i,
projectScope: false,
keywords: ATTRIBUTES.filter((a) => a.path[0] === language).map((a) => a.name),
sections: [colorSchemeSection([language])],
}),
colorSchemePage(
{
id: languagePageId(language),
title: language,
order: 6 + i,
},
language,
),
),
];
+74 -29
View File
@@ -4,14 +4,15 @@
*/
import { FontPicker } from "../../components/FontPicker";
import { useId, useState } from "react";
import { Checkbox, type SelectOption, T } from "@/ui";
import { useId, useLayoutEffect, useRef, useState } from "react";
import { Checkbox, type SelectOption, SplitGroup, SplitHandle, SplitPanel, T } from "@/ui";
import { monoFontFamily } from "@/platform/fonts";
import { NumberInput, Row, SearchLabel, Select } from "../../components/Form";
import { useLabelMatch, usePageContext, useSetting } from "../../components/context";
import { FONT_WEIGHTS, fontWeightOf, fontWeightVars } from "@/platform/editorSettings";
import { LIMITS } from "../../model/schema";
import { editorPage } from "./kit";
import type { PageSpec } from "../spec";
import { EditorSections, type EditorSection, sectionLabels } from "./kit";
import styles from "./Editor.module.css";
import { tx } from "@/platform/i18n";
@@ -20,11 +21,12 @@ function FontRow() {
const [monoSetting, setMonoOnly] = useSetting<boolean>("editor.onlyMonospacedFonts");
const monoOnly = monoSetting !== false;
const matched = useLabelMatch("Show only monospaced fonts");
const id = useId();
return (
<Row label="Font">
<Row label="Font" htmlFor={id} className={styles.fontRow}>
<span className={styles.fontFamily}>
<span className={styles.fontSelect}>
<FontPicker value={family} onChange={setFamily} label="Font" monoOnly={monoOnly} />
<FontPicker id={id} value={family} onChange={setFamily} label="Font" monoOnly={monoOnly} />
</span>
<span className={matched ? styles.matched : undefined}>
<Checkbox
@@ -41,10 +43,11 @@ function FontRow() {
function SizeRow() {
const [size, setSize] = useSetting<number>("editor.fontSize");
const [line, setLine] = useSetting<number>("editor.lineHeight");
const sizeId = useId();
const lineId = useId();
return (
<Row label="Size">
<NumberInput value={size} onChange={setSize} {...LIMITS.fontSize} aria-label="Size" unit="px" />
<Row label="Size" htmlFor={sizeId} className={styles.fontRow}>
<NumberInput id={sizeId} value={size} onChange={setSize} {...LIMITS.fontSize} aria-label="Size" unit="px" />
<span className={styles.inline}>
<label htmlFor={lineId} className={styles.inlineLabel}>
<SearchLabel text="Line height" />
@@ -64,9 +67,17 @@ function SizeRow() {
function FallbackRow() {
const [fallback, setFallback] = useSetting<string>("editor.fallbackFont");
const id = useId();
return (
<Row label="Fallback font" hint="For symbols not supported by the main font">
<FontPicker value={fallback} onChange={setFallback} label="Fallback font" allowEmpty />
<Row
label="Fallback font"
htmlFor={id}
hint="For symbols not supported by the main font"
className={styles.fontRow}
>
<span className={styles.fontSelect}>
<FontPicker id={id} value={fallback} onChange={setFallback} label="Fallback font" allowEmpty />
</span>
</Row>
);
}
@@ -93,8 +104,9 @@ function WeightRow({
const weight = fontWeightOf(value, defaultWeight);
const custom = customSelected || !FONT_WEIGHTS.some(([w]) => w === weight);
return (
<Row label={label} hint={hint}>
<Row label={label} hint={hint} className={styles.fontRow}>
<Select
className={styles.fontWeight}
value={custom ? "custom" : String(weight)}
options={WEIGHT_OPTIONS}
onChange={(v) => {
@@ -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<HTMLDivElement>(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 (
<div className={styles.fontPage} ref={page}>
<SplitGroup orientation={stacked ? "vertical" : "horizontal"} className={styles.fontSplit}>
<SplitPanel defaultSize={stacked ? "52%" : "45%"} minSize={stacked ? "96px" : "220px"}>
<section className={styles.fontOptions} aria-label={tx("Font options")}>
<EditorSections sections={FONT_SECTIONS} />
</section>
</SplitPanel>
<SplitHandle aria-label={tx("Resize font preview")} />
<SplitPanel defaultSize={stacked ? "48%" : "55%"} minSize={stacked ? "96px" : "200px"}>
<Preview />
</SplitPanel>
</SplitGroup>
</div>
);
}
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),
};
+18 -1
View File
@@ -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<string[]>("console.foldPatterns");
// Opened as `build.console#<text>` 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 (
<Row
label="Fold console lines that contain"
@@ -0,0 +1,81 @@
.dialog {
height: min(540px, calc(100vh - 48px));
}
.ranges {
flex: 1;
min-height: 0;
}
.range,
.list {
display: flex;
flex-direction: column;
min-height: 0;
}
.range {
height: 100%;
}
.list {
flex: 1;
}
.rangeHeader {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: var(--space-2);
padding: var(--space-2) var(--space-3);
border-bottom: 1px solid var(--border-strong);
background: var(--bg-elev);
}
.rangeHeader h3 {
min-width: 0;
margin: 0;
overflow-wrap: anywhere;
font-size: var(--fs-ui);
font-weight: 500;
}
.count,
.metadata {
color: var(--fg-secondary);
font-size: var(--fs-small);
}
.count {
font-variant-numeric: tabular-nums;
}
.commit {
display: flex;
flex: 1;
flex-direction: column;
gap: var(--space-0-5);
min-width: 0;
}
.subject,
.author {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.metadata {
display: flex;
align-items: baseline;
gap: var(--space-2);
}
.date {
flex-shrink: 0;
}
.error {
padding: var(--space-3);
overflow-wrap: anywhere;
}
+70 -41
View File
@@ -3,12 +3,13 @@ import { useEffect, useState } from "react";
import type { Commit } from "@/bindings";
import { executeAction } from "@/platform/actions";
import { call, commands } from "@/platform/ipc";
import { Dialog, List, Spinner, Tabs, T, tooltipAttrs } from "@/ui";
import { Dialog, List, Spinner, SplitGroup, SplitHandle, SplitPanel, T, tooltipAttrs } from "@/ui";
import { openDialog } from "./dialogs";
import { formatTime } from "./model";
import { showCompareRevisions } from "./operations";
import { currentRepo, useVcs } from "./store";
import styles from "./common.module.css";
import compareStyles from "./CompareBranches.module.css";
import { tx } from "@/platform/i18n";
import { useRowHeight } from "@/ui/density";
@@ -69,16 +70,18 @@ function RangeDialog(props: { title: string; from: string; to: string; repo: str
function CommitList({
commits,
error,
error = null,
rangeLabel,
onClose,
}: {
commits: Commit[] | null;
error: string | null;
error?: string | null;
rangeLabel?: string;
onClose: () => void;
}) {
const rowHeight = useRowHeight(22);
const rowHeight = useRowHeight(rangeLabel ? 42 : 22);
return (
<div className={styles.commitListBody}>
<div className={rangeLabel ? compareStyles.list : styles.commitListBody}>
{error ? (
<div className={styles.error} style={{ padding: 14 }}>
{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={
<span>
@@ -103,27 +106,53 @@ function CommitList({
onClose();
void executeAction("vcs.showCommit", c);
}}
renderItem={(c) => (
<span className={styles.commitRow} style={{ flex: 1, minWidth: 0, padding: 0 }}>
<span className={styles.commitHash}>{c.shortId}</span>
<span className={styles.commitSubject} {...tooltipAttrs(c.message || c.summary, undefined, true)}>
{c.summary}
renderItem={(c) =>
rangeLabel ? (
<div className={compareStyles.commit}>
<span className={compareStyles.subject} {...tooltipAttrs(c.message || c.summary, undefined, true)}>
{c.summary}
</span>
<div className={compareStyles.metadata}>
<span className={styles.commitHash}>{c.shortId}</span>
<span className={compareStyles.author}>{c.author}</span>
<span className={compareStyles.date}>{formatTime(c.timeMs)}</span>
</div>
</div>
) : (
<span className={styles.commitRow} style={{ flex: 1, minWidth: 0, padding: 0 }}>
<span className={styles.commitHash}>{c.shortId}</span>
<span className={styles.commitSubject} {...tooltipAttrs(c.message || c.summary, undefined, true)}>
{c.summary}
</span>
<span className={styles.commitMeta}>{c.author}</span>
<span className={styles.commitMeta}>{formatTime(c.timeMs)}</span>
</span>
<span className={styles.commitMeta}>{c.author}</span>
<span className={styles.commitMeta}>{formatTime(c.timeMs)}</span>
</span>
)}
)
}
/>
)}
</div>
);
}
function CompareRange({ label, commits, onClose }: { label: string; commits: Commit[] | null; onClose: () => void }) {
return (
<SplitPanel defaultSize="50%" minSize="25%">
<div className={compareStyles.range}>
<div className={compareStyles.rangeHeader}>
<h3>{label}</h3>
{commits && <span className={compareStyles.count}>{commits.length}</span>}
</div>
<CommitList rangeLabel={label} commits={commits} onClose={onClose} />
</div>
</SplitPanel>
);
}
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<string | null>(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 (
<Dialog
open
title={tx`Compare ${current} with ${branch}`}
onClose={onClose}
width={640}
minWidth={420}
width={800}
minWidth={360}
minHeight={360}
resizable="both"
className={styles.listDialog}
className={`${styles.listDialog} ${compareStyles.dialog}`}
buttons={[
{
label: "Show Diff",
@@ -152,31 +181,31 @@ function CompareDialog({ branch, current, onClose }: { branch: string; current:
onClick: () => {
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" },
]}
>
<Tabs
variant="compact"
activeId={tab}
onSelect={setTab}
aria-label="Direction"
items={[
{
id: "incoming",
label: tx`In ${branch}, not in ${current}`,
trailing: data ? String(data.incoming.length) : undefined,
},
{
id: "outgoing",
label: tx`In ${current}, not in ${branch}`,
trailing: data ? String(data.outgoing.length) : undefined,
},
]}
/>
<CommitList commits={data ? list : null} error={error} onClose={onClose} />
{error ? (
<div className={`${styles.error} ${compareStyles.error}`} role="alert">
{error}
</div>
) : (
<SplitGroup orientation="vertical" className={compareStyles.ranges}>
<CompareRange
label={tx`In ${branch}, not in ${current}`}
commits={data?.incoming ?? null}
onClose={onClose}
/>
<SplitHandle aria-label={tx("Resize branch comparison panes")} />
<CompareRange
label={tx`In ${current}, not in ${branch}`}
commits={data?.outgoing ?? null}
onClose={onClose}
/>
</SplitGroup>
)}
</Dialog>
);
}
+41
View File
@@ -0,0 +1,41 @@
.split {
flex: 1;
min-height: 0;
}
.patchName {
min-width: 0;
overflow: hidden;
color: var(--fg-strong);
text-overflow: ellipsis;
}
.fileText {
display: flex;
flex-direction: column;
}
.filesHeader {
flex: none;
display: flex;
align-items: center;
min-height: var(--h-compact-header);
padding-inline: var(--space-2);
border-bottom: 1px solid var(--border);
color: var(--fg-subtle);
font-size: var(--fs-small);
}
.detail {
flex: none;
color: var(--fg-subtle);
font-size: var(--fs-small);
}
.date {
composes: detail;
flex: 0 10000 auto;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
}
+41 -1
View File
@@ -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<typeof import("../dialogs")>()),
@@ -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);
});
+3 -5
View File
@@ -240,12 +240,10 @@ describe("shelf scope and diffs", () => {
</>,
);
await waitFor(() => expect(screen.getByText("Work")).toBeTruthy());
fireEvent.doubleClick(screen.getByText("Work"));
// Expand explicitly through the accessible tree keyboard navigation.
const tree = screen.getByRole("tree");
fireEvent.keyDown(tree, { key: "ArrowRight" });
fireEvent.mouseDown(screen.getByText("Work"), { button: 0 });
expect(useCommit.getState().selectedShelf).toBe("work");
const file = await screen.findByText("a.txt");
fireEvent.click(file);
fireEvent.mouseDown(file, { button: 0 });
expect(useCommit.getState().selectedShelf).toBe("work\u0000a.txt");
fireEvent.click(screen.getByRole("button", { name: "Unshelve…" }));
expect(mocks.execute).toHaveBeenCalledWith("vcs.unshelve", { id: "work", path: "a.txt" });
@@ -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<typeof import("@/platform/ipc")>();
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 = <T,>(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(<WorktreesPanel />);
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(<WorktreesPanel />);
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();
}
});
+2 -1
View File
@@ -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;
}
}
+3 -3
View File
@@ -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)}
/>
</div>
<Tree<WorktreeNode>
@@ -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"
/>
+29
View File
@@ -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<void> {
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),
});
}
}
+153 -72
View File
@@ -4,7 +4,7 @@
* merge UI), rename and delete.
*/
import { writeClipboardText } from "@/platform/clipboard";
import { useEffect, useMemo, useState, type MouseEvent } from "react";
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type MouseEvent } from "react";
import { create } from "zustand";
import type {
ApplyOutcome,
@@ -21,7 +21,21 @@ import { showCreatePatchForShelf } from "./patches";
import { executeAction } from "@/platform/actions";
import { call, commands } from "@/platform/ipc";
import { workflowSettings } from "@/platform/workflowSettings";
import { Checkbox, Dialog, Icon, IconButton, Input, Select, Tree, fileIconName, showContextMenu, T } from "@/ui";
import {
Checkbox,
Dialog,
Icon,
IconButton,
Input,
Select,
SplitGroup,
SplitHandle,
SplitPanel,
Tree,
fileIconName,
showContextMenu,
T,
} from "@/ui";
import { notifications } from "@/workbench/contributions";
import { groupOf } from "./changes";
import { buildFileTree, dirKeys, type FileTreeNode } from "./fileTree";
@@ -45,6 +59,7 @@ import { conflictedFiles, currentRepo, refreshNow, useVcs } from "./store";
import { repositoryPath } from "./repositoryPaths";
import styles from "./common.module.css";
import viewStyles from "./CommitView.module.css";
import shelfStyles from "./Shelf.module.css";
import { tx } from "@/platform/i18n";
interface ShelfState {
@@ -473,7 +488,6 @@ interface ShelfNode {
key: string;
entry: ShelvedChangeList;
file?: ShelvedChangeList["files"][number];
children?: ShelfNode[];
}
export interface ShelfTarget {
@@ -600,31 +614,130 @@ export function createShelfPatch(arg?: unknown) {
if (target) showCreatePatchForShelf(target.entry, target.path);
}
function ShelfTree({
nodes,
kind,
selectedKey,
empty,
}: {
nodes: ShelfNode[];
kind: "changes" | "files";
selectedKey: string | null;
empty: string;
}) {
const selected = useMemo(() => new Set(selectedKey ? [selectedKey] : []), [selectedKey]);
const filePane = kind === "files";
return (
<Tree<ShelfNode>
roots={nodes}
getKey={(n) => n.key}
getLabel={(n) => (n.file ? baseName(n.file.path) : n.entry.name)}
getChildren={() => undefined}
isExpandable={() => false}
selected={selected}
onSelectionChange={(sel) => useCommit.setState({ selectedShelf: [...sel][0] ?? null })}
horizontalScroll={filePane}
rowHeight={filePane ? 40 : undefined}
multiSelect={false}
onActivate={(n) => {
void executeAction(n.file ? "vcs.shelf.showDiff" : "vcs.unshelve", { id: n.entry.id, path: n.file?.path });
}}
onContextMenu={(node, _sel, e: MouseEvent) => {
if (!node) return;
e.preventDefault();
useCommit.setState({ selectedShelf: node.key });
const point = { x: e.clientX, y: e.clientY };
const target = { id: node.entry.id, path: node.file?.path };
void Promise.all(
shelfDiffs(target, true).map(async (d) => {
try {
return !(await call(commands.fsProbe(d.path))).binary;
} catch {
return false;
}
}),
).then((supported) => showContextMenu(point, shelfMenu(node, supported.some(Boolean))));
}}
aria-label={filePane ? "Shelved files" : "Shelved changes"}
empty={<span className={viewStyles.empty}>{tx(empty)}</span>}
renderNode={(n) => {
const file = n.file;
if (file) {
const directory = dirName(file.path);
return (
<>
<Icon name={fileIconName(baseName(file.path), file.path)} size={16} className={viewStyles.icon} />
<span className={shelfStyles.fileText} title={file.path}>
<span style={{ color: KIND_COLOR[file.kind === "untracked" ? "added" : file.kind] }}>
{baseName(file.path)}
</span>
{directory && <span className={shelfStyles.detail}>{directory}</span>}
</span>
</>
);
}
const time = n.entry.timeMs ? formatTime(n.entry.timeMs) : null;
return (
<>
<Icon name="shelve" size={16} className={viewStyles.icon} />
<span className={shelfStyles.patchName} title={n.entry.name}>
{n.entry.name}
</span>
<span className={shelfStyles.detail}>{fileCount(n.entry.files.length)}</span>
{time && (
<span className={shelfStyles.date} title={time}>
{time}
</span>
)}
</>
);
}}
/>
);
}
/** The Shelf tab of the Commit tool window. */
export function ShelfPanel() {
const shelves = useShelf((s) => s.shelves);
const loaded = useShelf((s) => s.loaded);
const root = useVcs((s) => s.root);
useShelf((s) => s.diffs);
const selectedShelf = useCommit((s) => s.selectedShelf);
const selected = useMemo(() => new Set(selectedShelf ? [selectedShelf] : []), [selectedShelf]);
const panelRef = useRef<HTMLDivElement>(null);
const [stacked, setStacked] = useState(true);
useLayoutEffect(() => {
const panel = panelRef.current;
if (!panel) return;
const measure = () => setStacked(panel.clientWidth < 560);
measure();
if (typeof ResizeObserver === "undefined") return;
const observer = new ResizeObserver(measure);
observer.observe(panel);
return () => observer.disconnect();
}, []);
useEffect(() => {
void loadShelves().catch(() => undefined);
return () => setContext("shelfFocus", false);
}, [root]);
const roots = useMemo<ShelfNode[]>(
() =>
shelves.map((entry) => ({
key: entry.id,
entry,
children: entry.files.map((file) => ({ key: `${entry.id}\u0000${file.path}`, entry, file })),
})),
[shelves],
const selectedId = selectedShelf?.split("\u0000", 1)[0];
const entry = shelves.find((s) => s.id === selectedId);
const patches = useMemo<ShelfNode[]>(() => shelves.map((s) => ({ key: s.id, entry: s })), [shelves]);
const files = useMemo<ShelfNode[]>(
() => entry?.files.map((file) => ({ key: `${entry.id}\u0000${file.path}`, entry, file })) ?? [],
[entry],
);
const current = selectedShelf ? shelfTarget(selectedShelf) : null;
const patchTree = (
<ShelfTree
nodes={patches}
kind="changes"
selectedKey={entry?.id ?? null}
empty={loaded ? "No shelved changes" : "Loading…"}
/>
);
const current = shelfTarget([...selected][0]);
return (
<div
className={viewStyles.changes}
ref={panelRef}
data-shelf-panel
onFocusCapture={() => setContext("shelfFocus", true)}
onBlurCapture={(e) => {
@@ -652,64 +765,32 @@ export function ShelfPanel() {
}
/>
</div>
<div className={viewStyles.treeWrap}>
<Tree<ShelfNode>
roots={roots}
getKey={(n) => n.key}
getLabel={(n) => (n.file ? baseName(n.file.path) : n.entry.name)}
getChildren={(n) => n.children}
isExpandable={(n) => !n.file}
selected={selected}
onSelectionChange={(sel) => {
const key = [...sel][0];
useCommit.setState({ selectedShelf: key ?? null });
}}
multiSelect={false}
onActivate={(n) => {
void executeAction(n.file ? "vcs.shelf.showDiff" : "vcs.unshelve", { id: n.entry.id, path: n.file?.path });
}}
onContextMenu={(node, _sel, e: MouseEvent) => {
if (!node) return;
e.preventDefault();
const point = { x: e.clientX, y: e.clientY };
const target = { id: node.entry.id, path: node.file?.path };
void Promise.all(
shelfDiffs(target, true).map(async (d) => {
try {
return !(await call(commands.fsProbe(d.path))).binary;
} catch {
return false;
}
}),
).then((supported) => showContextMenu(point, shelfMenu(node, supported.some(Boolean))));
}}
aria-label="Shelved changes"
empty={<span className={viewStyles.empty}>{loaded ? tx("No shelved changes") : tx("Loading…")}</span>}
renderNode={(n) =>
n.file ? (
<>
<Icon name={fileIconName(baseName(n.file.path), n.file.path)} size={16} className={viewStyles.icon} />
<span
className={viewStyles.label}
style={{ color: KIND_COLOR[n.file.kind === "untracked" ? "added" : n.file.kind] }}
>
{baseName(n.file.path)}
</span>
<span className={viewStyles.detail}>{dirName(n.file.path)}</span>
</>
) : (
<>
<Icon name="shelve" size={16} className={viewStyles.icon} />
<span className={viewStyles.label}>{n.entry.name}</span>
<span className={viewStyles.detail}>
{fileCount(n.entry.files.length)}
{n.entry.timeMs ? ` · ${formatTime(n.entry.timeMs)}` : ""}
</span>
</>
)
}
/>
</div>
{patches.length ? (
<SplitGroup
id="shelf-panes"
className={shelfStyles.split}
orientation={stacked ? "vertical" : "horizontal"}
storageKey={`openidea.vcs.shelf.layout.${stacked ? "stacked" : "sideBySide"}`}
>
<SplitPanel id="shelf-changes" defaultSize="50%" minSize="25%">
{patchTree}
</SplitPanel>
<SplitHandle aria-label={tx("Resize shelf panes")} />
<SplitPanel id="shelf-files" defaultSize="50%" minSize="25%">
<div className={shelfStyles.filesHeader}>
<T>Shelved files</T>
</div>
<ShelfTree
nodes={files}
kind="files"
selectedKey={current?.path ? selectedShelf : null}
empty={entry ? "No files" : "Select a shelf to view its files"}
/>
</SplitPanel>
</SplitGroup>
) : (
<div className={viewStyles.treeWrap}>{patchTree}</div>
)}
</div>
);
}
+1 -1
View File
@@ -332,7 +332,7 @@ describe("markdown preview re-rendering", () => {
same(render, doc(blocks));
});
it("renders a large document as a whole, sanitizing only what an edit changed", () => {
it("renders a large document as a whole, sanitizing only what an edit changed", { timeout: 20_000 }, () => {
const asWritten = readFileSync(resolve(import.meta.dirname, "../../../../plugins/README.md"), "utf8");
// As written, a bare `<title>` swallows the rest of the file, so it is rendered as a whole.
for (const [readme, reuses] of [
+54 -29
View File
@@ -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>
);
}
+45 -16
View File
@@ -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 {
+16 -1
View File
@@ -1,9 +1,15 @@
{
"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",
"Problems actions": "Problems actions",
"TODO actions": "TODO actions",
"Same as the existing configuration '{existing}'": "Same as the existing configuration '{existing}'",
@@ -2697,9 +2703,18 @@
"Resize rebase panes": "Resize rebase panes",
"New message for {id}": "New message for {id}",
"Resize right merge pane": "Resize right merge pane",
"Resize shelf panes": "Resize shelf panes",
"Shelved files": "Shelved files",
"Select a shelf to view its files": "Select a shelf to view its files",
"No files": "No files",
"Database and schema": "Database and schema",
"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"
}
-1
View File
@@ -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)",
-1
View File
@@ -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",
-1
View File
@@ -715,7 +715,6 @@
"Detecting installations": "설치 항목 감지 중",
"Detecting…": "감지 중…",
"Different tool window background": "도구 창 배경을 다르게 표시",
"Direction": "방향",
"Directory": "디렉터리",
"Staging State": "스테이징 상태",
"Staged Changes": "스테이징된 변경 사항",
-1
View File
@@ -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)",
-1
View File
@@ -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",
+16 -2
View File
@@ -1,9 +1,15 @@
{
"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": "调整文件类型窗格大小",
"Problems actions": "问题操作",
"Windows file and folder names cannot end with a period or space": "Windows 文件和文件夹名称不能以句点或空格结尾",
"Use URL template": "使用 URL 模板",
@@ -1272,7 +1278,6 @@
"Detecting…": "正在检测…",
"Diff": "差异",
"Different tool window background": "不同的工具窗口背景",
"Direction": "方向",
"Directory": "目录",
"Staging State": "暂存状态",
"Staged Changes": "已暂存的更改",
@@ -2755,6 +2760,9 @@
"Shelve Changes": "搁置更改",
"Shelve Changes…": "搁置更改…",
"Shelved changes": "已搁置的更改",
"Shelved files": "已搁置的文件",
"Select a shelf to view its files": "选择一条搁置记录以查看文件",
"No files": "没有文件",
"Show": "显示",
"Show \"Today\", \"Yesterday\" and \"N min ago\" for recent dates": "对最近的日期显示“今天”、“昨天”和“N 分钟前”",
"Show All": "全部显示",
@@ -3346,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": "没有打开的文件",
@@ -9066,7 +9075,12 @@
"Resize left merge pane": "调整左侧合并窗格宽度",
"Resize rebase panes": "调整变基计划和详细信息窗格大小",
"Resize right merge pane": "调整右侧合并窗格宽度",
"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 用户名"
}
+2 -1
View File
@@ -226,8 +226,9 @@ export async function connectRemote(target: RemoteTarget, path: string) {
});
try {
const r = await call(commands.remoteConnect(target, path, onProgress));
// Another connect replaced this one, or the user cancelled. Disconnecting here
// would drop the connection that replacement published. Cancel already disconnects.
if (useRemoteProgress.getState().location !== location) {
await commands.remoteDisconnect().catch(() => {});
throw new IpcError({ kind: "cancelled", message: "Remote connection cancelled" });
}
await attachRemote(r, path);
+33
View File
@@ -9,6 +9,8 @@ import {
isRemoteWindow,
localGlobalSettings,
remoteRouting,
useRemote,
useRemoteProgress,
} from "./remote";
import { invoke as routedInvoke } from "./tauriCore";
@@ -62,6 +64,7 @@ beforeEach(() => {
afterEach(() => {
disableRemote();
useProject.setState({ opening: false, settings: null });
useRemoteProgress.setState({ progress: null, location: null });
});
describe("remote client settings", () => {
@@ -205,6 +208,36 @@ describe("remote client settings", () => {
await connectRemote({ kind: "ssh", config: "test" }, "/remote");
expect(useProject.getState().settings).toMatchObject({ keymap: "my-map", editor: { tabSize: 2, fontSize: 19 } });
});
it("does not disconnect a newer connect when an older one finishes", async () => {
disableRemote();
useRemoteProgress.setState({ progress: null, location: null });
let releaseFirst: (value: unknown) => void = () => {};
const first = new Promise((resolve) => {
releaseFirst = resolve;
});
let connects = 0;
invoke.mockImplementation(async (cmd: string) => {
if (cmd !== "remote_connect") return cmd === "remote_invoke" ? "null" : local;
connects += 1;
const root = connects === 1 ? "/home/me/old" : "/home/me/new";
const project = {
target: { kind: "wsl", distro: "Ubuntu" },
root,
host: "Ubuntu",
os: "linux",
commands: [...served],
project: { root, name: "app", displayName: "app", settings: remote },
};
return connects === 1 ? first.then(() => project) : project;
});
const older = connectRemote({ kind: "wsl", distro: "Ubuntu" }, "/home/me/old");
const newer = connectRemote({ kind: "wsl", distro: "Ubuntu" }, "/home/me/new");
await newer;
releaseFirst(undefined);
await expect(older).rejects.toMatchObject({ kind: "cancelled" });
expect(invoke.mock.calls.filter(([cmd]) => cmd === "remote_disconnect")).toHaveLength(0);
expect(useRemote.getState().session?.root).toBe("/home/me/new");
});
it("overlays the project snapshot used by the settings window", async () => {
invoke.mockImplementation(async (cmd: string) =>
cmd === "remote_invoke" ? JSON.stringify({ root: "/remote", settings: remote }) : local,