дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-27 13:06:07 +02:00
Порівняти коміти
16
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
64ee535eb7 | ||
|
|
7850429174 | ||
|
|
3dd5c75fa0 | ||
|
|
36ecb53159 | ||
|
|
006405ca11 | ||
|
|
40b95650cf | ||
|
|
0a571c0b4d | ||
|
|
16cda13915 | ||
|
|
b1f88bf79c | ||
|
|
0a6b3d011f | ||
|
|
fd9b20fa05 | ||
|
|
4f5622d72c | ||
|
|
f4a7a7bafb | ||
|
|
737afc6a8d | ||
|
|
6bf75155b6 | ||
|
|
bbedf7e1f6 |
No files matched your search
Створено
@@ -5017,6 +5017,7 @@ dependencies = [
|
||||
"ignore",
|
||||
"notify",
|
||||
"parking_lot",
|
||||
"rayon",
|
||||
"rustix",
|
||||
"serde",
|
||||
"serde_json",
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -100,16 +100,6 @@ pub struct AgentSettings {
|
||||
pub smooth_text: bool,
|
||||
/// Conversations and the composer expand to the full width of the pane instead of staying in a centred column.
|
||||
pub fit_window_width: bool,
|
||||
/// While the agent works, playful words fill the pauses in what it reports.
|
||||
pub playful_status: bool,
|
||||
/// Seconds the agent reports nothing new before the playful words take over; 0 shows them
|
||||
/// from the start.
|
||||
pub playful_after_seconds: u32,
|
||||
/// The user's playful words by activity (`working`, `thinking`, `reading`, …), replacing
|
||||
/// the built-in ones of that activity; an empty list keeps its status factual.
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = BTreeMap<String, Vec<String>>)]
|
||||
pub playful_words: BTreeMap<String, Vec<String>>,
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = ThinkingDisplay)]
|
||||
pub thinking: ThinkingDisplay,
|
||||
@@ -152,9 +142,6 @@ impl Default for AgentSettings {
|
||||
fold_turns: true,
|
||||
smooth_text: true,
|
||||
fit_window_width: false,
|
||||
playful_status: false,
|
||||
playful_after_seconds: 0,
|
||||
playful_words: BTreeMap::new(),
|
||||
thinking: ThinkingDisplay::Auto,
|
||||
tool_calls: ToolCallDisplay::Grouped,
|
||||
expand_tool_output: false,
|
||||
|
||||
@@ -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()))
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -22,6 +22,7 @@ parking_lot.workspace = true
|
||||
zip.workspace = true
|
||||
flate2.workspace = true
|
||||
tar.workspace = true
|
||||
rayon.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
|
||||
@@ -10,6 +10,7 @@ mod rules;
|
||||
mod watch;
|
||||
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use rayon::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::cmp::Ordering;
|
||||
@@ -133,51 +134,57 @@ pub fn read_dir(dir: &Path, excludes: &[String]) -> IdeResult<Vec<FileEntry>> {
|
||||
let base = gitignore.repo_root().unwrap_or(dir).to_path_buf();
|
||||
let excludes = ExcludeMatcher::new(excludes);
|
||||
|
||||
let mut entries: Vec<(bool, FileEntry)> = Vec::new();
|
||||
for entry in fs::read_dir(dir)? {
|
||||
let entry = match entry {
|
||||
Ok(e) => e,
|
||||
let paths: Vec<PathBuf> = fs::read_dir(dir)?
|
||||
.filter_map(|entry| match entry {
|
||||
Ok(e) => Some(e.path()),
|
||||
Err(e) => {
|
||||
tracing::debug!("read_dir {}: {e}", dir.display());
|
||||
continue;
|
||||
None
|
||||
}
|
||||
};
|
||||
let path = entry.path();
|
||||
let name = entry.file_name().to_string_lossy().into_owned();
|
||||
let Ok(lmeta) = fs::symlink_metadata(&path) else { continue };
|
||||
let (kind, meta, target_kind) = if lmeta.file_type().is_symlink() {
|
||||
match fs::metadata(&path) {
|
||||
Ok(m) => {
|
||||
let target = if m.is_dir() { EntryKind::Dir } else { EntryKind::File };
|
||||
(EntryKind::Symlink, m, Some(target))
|
||||
})
|
||||
.collect();
|
||||
// One stat per entry dominates a large folder (and every stat is a round trip on a network
|
||||
// share): stat in parallel; small folders stay on this thread.
|
||||
let mut entries: Vec<(bool, FileEntry)> = paths
|
||||
.into_par_iter()
|
||||
.with_min_len(256)
|
||||
.filter_map(|path| {
|
||||
let name = path.file_name()?.to_string_lossy().into_owned();
|
||||
let lmeta = fs::symlink_metadata(&path).ok()?;
|
||||
let (kind, meta, target_kind) = if lmeta.file_type().is_symlink() {
|
||||
match fs::metadata(&path) {
|
||||
Ok(m) => {
|
||||
let target = if m.is_dir() { EntryKind::Dir } else { EntryKind::File };
|
||||
(EntryKind::Symlink, m, Some(target))
|
||||
}
|
||||
Err(_) => (EntryKind::Symlink, lmeta, None),
|
||||
}
|
||||
Err(_) => (EntryKind::Symlink, lmeta, None),
|
||||
}
|
||||
} else if lmeta.is_dir() {
|
||||
(EntryKind::Dir, lmeta, None)
|
||||
} else {
|
||||
(EntryKind::File, lmeta, None)
|
||||
};
|
||||
let is_dir = meta.is_dir();
|
||||
let rel = path.strip_prefix(&base).unwrap_or(&path);
|
||||
let excluded = excludes.is_excluded(rel);
|
||||
let ignored = excluded || gitignore.is_ignored(&path, is_dir);
|
||||
entries.push((
|
||||
is_dir,
|
||||
FileEntry {
|
||||
hidden: name.starts_with('.'),
|
||||
size: if is_dir { 0 } else { meta.len() },
|
||||
mtime_ms: mtime_ms(&meta),
|
||||
name,
|
||||
path: path.into(),
|
||||
kind,
|
||||
ignored,
|
||||
excluded,
|
||||
target_kind,
|
||||
},
|
||||
));
|
||||
}
|
||||
entries.sort_by(|(da, a), (db, b)| db.cmp(da).then_with(|| natural_cmp(&a.name, &b.name)));
|
||||
} else if lmeta.is_dir() {
|
||||
(EntryKind::Dir, lmeta, None)
|
||||
} else {
|
||||
(EntryKind::File, lmeta, None)
|
||||
};
|
||||
let is_dir = meta.is_dir();
|
||||
let rel = path.strip_prefix(&base).unwrap_or(&path);
|
||||
let excluded = excludes.is_excluded(rel);
|
||||
let ignored = excluded || gitignore.is_ignored(&path, is_dir);
|
||||
Some((
|
||||
is_dir,
|
||||
FileEntry {
|
||||
hidden: name.starts_with('.'),
|
||||
size: if is_dir { 0 } else { meta.len() },
|
||||
mtime_ms: mtime_ms(&meta),
|
||||
name,
|
||||
path: path.into(),
|
||||
kind,
|
||||
ignored,
|
||||
excluded,
|
||||
target_kind,
|
||||
},
|
||||
))
|
||||
})
|
||||
.collect();
|
||||
entries.par_sort_by(|(da, a), (db, b)| db.cmp(da).then_with(|| natural_cmp(&a.name, &b.name)));
|
||||
Ok(entries.into_iter().map(|(_, e)| e).collect())
|
||||
}
|
||||
|
||||
|
||||
@@ -137,7 +137,7 @@ Tasks are saved per project and survive restarts. When the agent supports resumi
|
||||
- **Agent Configs**: discovers servers already configured in `~/.copilot/mcp-config.json` (and installed Copilot CLI plugins), `~/.claude.json`, `~/.codex/config.toml`, `~/.cursor/mcp.json`, `~/.gemini/settings.json`, `~/.jetbrains/mcp/mcp.json`, `.mcp.json`, and `.vscode/mcp.json` so you can import them into Global or Project settings with one click. You can also add or edit servers via structured fields or raw `mcpServers` JSON (**Add from JSON**), and run **Test Connection** to inspect the tools a server advertises.
|
||||
- **Per-session (`MCP` / `/mcp`)**: in both **New Agent Task** and active task conversations, open **MCP** in the composer toolbar (or run `/mcp`) to enable or disable individual servers—including the built-in `openidea` server—for that task only, or click **Reset** to return to the inherited defaults.
|
||||
|
||||
While the agent works, the line under the conversation says what it is doing: thinking, reading, editing, running a command, writing its reply. **Settings › Agents › Working Status** can show playful words for what it does there instead; they are off by default. Once turned on, they take turns from the moment the work changes, or only after the agent reports nothing new for a number of seconds (0 to 600, 0 by default); screen readers still hear what the agent is doing. Each word stays eight seconds while the agent keeps at the same work, and at least three when it moves on, so the line doesn't flicker. The same page replaces the words: pick what the status says (**Reading…**, **Running a command…**…) and add or remove its words. **Restore Built-in Words** brings back OpenIDEA's; an activity left without words keeps its plain status.
|
||||
While the agent works, the line under the conversation says what it is doing: thinking, reading, editing, running a command, writing its reply.
|
||||
|
||||
## Add a custom agent
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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).
|
||||
|
||||
|
||||
@@ -137,7 +137,7 @@ agent 运行过一个任务后,新任务会以它自动批准所有操作的
|
||||
- **智能体配置**:自动发现 `~/.copilot/mcp-config.json`(及已安装的 Copilot CLI 插件)、`~/.claude.json`、`~/.codex/config.toml`、`~/.cursor/mcp.json`、`~/.gemini/settings.json`、`~/.jetbrains/mcp/mcp.json`、`.mcp.json` 和 `.vscode/mcp.json` 中已配置的服务器,可一键导入到全局或项目设置。添加或编辑服务器时既可使用表单,也可直接粘贴 `mcpServers` JSON(**从 JSON 添加**),并可通过 **测试连接** 查看服务器声明的工具列表。
|
||||
- **按会话覆盖(`MCP` / `/mcp`)**:在 **新建 Agent 任务** 和进行中的任务对话中,单击输入框工具栏的 **MCP**(或输入 `/mcp`),即可仅针对当前任务开启或关闭任意服务器(包括内置的 `openidea` 服务器),或点击 **重置** 恢复继承的默认状态。
|
||||
|
||||
agent 工作时,对话下方的状态行显示它正在做什么:思考、读取、编辑、运行命令、输出回复。在 **设置 › 智能体 › 工作状态** 中可以让这里改为显示与当前工作相关的趣味文字,默认关闭。开启后,工作一变化就轮换显示,也可以设置在 agent 无新进展多少秒后才显示(0 到 600,默认 0);屏幕阅读器读出的仍是 agent 实际在做的事。agent 持续做同一类工作时,每条文字停留八秒;转向其他工作时也至少停留三秒,状态行不会频繁跳动。同一页面还可以替换这些文字:选择状态(**正在读取…**、**正在运行命令…**…),再添加或移除对应的文字。**恢复内置文字** 会换回 OpenIDEA 自带的文字;没有任何文字的状态只显示实际进展。
|
||||
agent 工作时,对话下方的状态行显示它正在做什么:思考、读取、编辑、运行命令、输出回复。
|
||||
|
||||
## 添加自定义 agent
|
||||
|
||||
|
||||
@@ -125,7 +125,7 @@ C 和 C++ 的配置也可以改用 GDB 14 及以上版本(`gdb -i dap`):
|
||||
程序挂起时:
|
||||
|
||||
- **变量** 视图显示选中帧的变量。右键点击某个值,可以 **设置值…**(`F2`)、**复制值**、**复制名称**、**跳转到源代码**(`F4`)和 **添加到监视**。
|
||||
- 监视表达式显示在变量视图顶部,每次停下或切换帧时重新计算。用 **添加到监视** 添加,用 **移除监视** 删除。
|
||||
- 监视表达式显示在变量视图顶部,每次停下或切换帧时重新计算。用 **添加到监视** 添加,用 **移除监视** 删除,用 **移除所有监视** 一次全部删除。
|
||||
- 在编辑器里悬停变量会显示它的值。`⌥` 点击(`Alt` 点击)或 **快速计算表达式**(`⌘⌥F8` / `Ctrl+Alt+F8`)计算鼠标下的表达式或选中的内容。
|
||||
- 局部变量的值会内联显示在使用它们的行尾。
|
||||
- **计算表达式…**(`⌥F8` / `Alt+F8`)打开对话框,在选中帧里计算任意表达式,带历史记录,也能把表达式加入监视。
|
||||
|
||||
@@ -156,7 +156,7 @@ Maven 模块在 **自动** 和 **构建(Make)** 时由 jdtls(ECJ)构建
|
||||
每次启动都会在底部的 **运行** 工具窗口里开一个标签页。工具栏有 **重新运行**、**调试**、**重新运行失败的测试**(测试运行时)、**更新应用**、**查找…**、**滚动到末尾**、**软换行**、**全部清除** 和 **编辑配置…**。
|
||||
|
||||
- 输出里的文件路径和堆栈帧都可以点击跳转。
|
||||
- 重复的行可以折叠。折叠规则、缓冲区大小和控制台编码在 **设置 › 构建、执行、部署 › 控制台** 中配置。
|
||||
- 重复的行可以折叠。折叠规则、缓冲区大小和控制台编码在 **设置 › 构建、执行、部署 › 控制台** 中配置。控制台右键菜单中的 **折叠与此类似的行** 会打开该页面,并把选中的文本(或右键所在的行)添加为折叠规则。
|
||||
- 日志行可按级别着色(`ERROR`、`WARN`、`INFO`、`DEBUG`、`TRACE`);程序自行输出的颜色保持不变。默认关闭,可在 **设置 › 构建、执行、部署 › 控制台** 开启并修改颜色。
|
||||
- 测试运行时,标签页会在输出旁显示测试树,参见[测试](/zh/guide/testing)。
|
||||
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
import type { EditorView } from "@codemirror/view";
|
||||
import { expect, stubDesktop, test } from "./fixtures";
|
||||
|
||||
test("Hierarchy keeps source context and controls reachable in a narrow dock", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 940, height: 680 });
|
||||
const path = "/dev/acme-api/QuarterlySettlementReconciliationCoordinator.ts";
|
||||
const caller = "reconcileQuarterlySettlementForMerchantOrders";
|
||||
const context = "Checkout and settlement coordinator";
|
||||
await page.evaluate(
|
||||
async ({ path, caller }) => {
|
||||
const backend = "/src/editor/core/backend.ts";
|
||||
const { docBackend } = await import(/* @vite-ignore */ backend);
|
||||
docBackend().files.set(
|
||||
path,
|
||||
[
|
||||
"function settleOrder() {}",
|
||||
"",
|
||||
`function ${caller}() {`,
|
||||
" settleOrder();",
|
||||
" settleOrder();",
|
||||
"}",
|
||||
`function flushSettlementQueue() { ${caller}(); }`,
|
||||
].join("\n"),
|
||||
);
|
||||
const service = "/src/workbench/contributions.ts";
|
||||
await (await import(/* @vite-ignore */ service)).editorService().openFile(path);
|
||||
},
|
||||
{ path, caller },
|
||||
);
|
||||
const editor = page.locator(".cm-content");
|
||||
await expect(editor).toContainText("settleOrder");
|
||||
await editor.evaluate((el) => {
|
||||
const view = (el as HTMLElement & { cmTile: { view: EditorView } }).cmTile.view;
|
||||
view.dispatch({ selection: { anchor: 11 } });
|
||||
view.focus();
|
||||
});
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(
|
||||
async ({ path, caller, context }) => {
|
||||
const range = (line: number, col: number) => ({ start: { line, col }, end: { line, col: col + 5 } });
|
||||
const item = (name: string, line: number, detail: string, fromRanges: ReturnType<typeof range>[]) => ({
|
||||
name,
|
||||
path,
|
||||
detail,
|
||||
kind: "function",
|
||||
range: range(line, 0),
|
||||
selectionRange: range(line, 9),
|
||||
fromRanges,
|
||||
});
|
||||
window.__ipc.handlers.lsp_call_hierarchy = ({ pos }) => {
|
||||
const line = (pos as { line: number }).line;
|
||||
return {
|
||||
items:
|
||||
line === 0
|
||||
? [item(caller, 2, context, [range(3, 2), range(4, 2)])]
|
||||
: [item("flushSettlementQueue", 6, "Queue processing", [range(6, 34)])],
|
||||
incomplete: null,
|
||||
};
|
||||
};
|
||||
const actions = "/src/platform/actions.ts";
|
||||
await (await import(/* @vite-ignore */ actions)).executeAction("navigate.callHierarchy");
|
||||
const dock = "/src/workbench/toolwindows/store.ts";
|
||||
(await import(/* @vite-ignore */ dock)).setToolWindowSize("right", 136);
|
||||
},
|
||||
{ path, caller, context },
|
||||
);
|
||||
|
||||
const tree = page.getByRole("tree", { name: "Call hierarchy" });
|
||||
const row = tree.getByRole("treeitem").filter({ hasText: caller });
|
||||
await expect(row).toBeVisible();
|
||||
const detail = row.getByText(context, { exact: true });
|
||||
await expect.poll(() => detail.evaluate((el) => el.clientWidth)).toBeGreaterThan(100);
|
||||
expect((await row.getByText("(2 calls)", { exact: true }).boundingBox())!.x).toBeLessThan(
|
||||
(await detail.boundingBox())!.x,
|
||||
);
|
||||
const toolbar = page.getByRole("toolbar", { name: "Hierarchy actions" });
|
||||
expect(await toolbar.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
|
||||
await tree.evaluate((el) => {
|
||||
el.scrollLeft = el.scrollWidth;
|
||||
});
|
||||
expect(await tree.evaluate((el) => el.scrollLeft)).toBeGreaterThan(100);
|
||||
await tree.evaluate((el) => {
|
||||
el.scrollLeft = 0;
|
||||
});
|
||||
await row.click({ position: { x: 90, y: 12 } });
|
||||
await page.keyboard.press("ArrowRight");
|
||||
await expect(tree.getByRole("treeitem").filter({ hasText: "flushSettlementQueue" })).toBeVisible();
|
||||
await page.keyboard.press("Enter");
|
||||
await expect
|
||||
.poll(() =>
|
||||
page.evaluate(async () => {
|
||||
const service = "/src/workbench/contributions.ts";
|
||||
const cursor = (await import(/* @vite-ignore */ service)).editorService().activeCursor();
|
||||
return { path: cursor?.path, line: cursor?.line, col: cursor?.col };
|
||||
}),
|
||||
)
|
||||
.toEqual({ path, line: 3, col: 2 });
|
||||
});
|
||||
@@ -0,0 +1,52 @@
|
||||
import { expect, test } from "./fixtures";
|
||||
|
||||
test("Inspections keeps the selected rule and its controls usable as the pane changes width", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 620, height: 720 });
|
||||
await page.keyboard.press("Meta+,");
|
||||
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
|
||||
await expect(dialog).toBeVisible();
|
||||
await page.evaluate(async () => {
|
||||
const path = "/src/features/settings/model/staging.ts";
|
||||
(await import(/* @vite-ignore */ path)).selectPage("editor.inspections");
|
||||
});
|
||||
|
||||
const search = dialog.getByRole("textbox", { name: "Search inspections" });
|
||||
await search.fill("typo");
|
||||
const tree = dialog.getByRole("tree", { name: "Inspections" });
|
||||
const typo = tree.getByRole("treeitem", { name: /Typo/ });
|
||||
await typo.click();
|
||||
const body = dialog.locator("[class*='pageBody']");
|
||||
await expect.poll(() => body.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
|
||||
|
||||
const resize = dialog.getByRole("separator", { name: "Resize inspection panes" });
|
||||
const details = dialog.getByRole("region", { name: "Inspection details" });
|
||||
await expect(resize).toHaveAttribute("aria-orientation", "horizontal");
|
||||
await expect(details.getByRole("heading", { name: "Typo" })).toBeVisible();
|
||||
const narrowTree = await tree.boundingBox();
|
||||
const narrowDetails = await details.boundingBox();
|
||||
expect(narrowDetails!.y).toBeGreaterThan(narrowTree!.y + narrowTree!.height);
|
||||
|
||||
await expect(details.getByRole("separator", { name: "Resize inspection description" })).toHaveAttribute(
|
||||
"aria-orientation",
|
||||
"horizontal",
|
||||
);
|
||||
const severity = details.getByRole("button", { name: "Severity" });
|
||||
const severityBox = await severity.boundingBox();
|
||||
expect(severityBox!.y + severityBox!.height).toBeLessThan(narrowDetails!.y + narrowDetails!.height);
|
||||
await severity.click();
|
||||
await page.getByRole("option", { name: "Warning", exact: true }).click();
|
||||
const code = details.getByRole("checkbox", { name: "Process code" });
|
||||
await code.uncheck();
|
||||
await expect(severity).toHaveText("Warning");
|
||||
|
||||
await page.setViewportSize({ width: 1040, height: 740 });
|
||||
await expect(resize).toHaveAttribute("aria-orientation", "vertical");
|
||||
const width = (await tree.boundingBox())!.width;
|
||||
await resize.press("ArrowRight");
|
||||
await expect.poll(async () => (await tree.boundingBox())!.width).toBeGreaterThan(width + 5);
|
||||
await expect(typo).toHaveAttribute("aria-selected", "true");
|
||||
await expect(severity).toHaveText("Warning");
|
||||
await expect(code).not.toBeChecked();
|
||||
});
|
||||
@@ -0,0 +1,90 @@
|
||||
import { expect, stubDesktop, test } from "./fixtures";
|
||||
|
||||
test("Interactive rebase keeps commit messages and plan controls usable at narrow widths", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
const first = "Keep regional settlement references stable when reconciling delayed ledger updates";
|
||||
const second = "Add settlement summary";
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(
|
||||
async ({ first, second }) => {
|
||||
const root = "/dev/acme-api";
|
||||
const id = (n: string) => n.repeat(40);
|
||||
const commits = [
|
||||
{ id: id("c"), shortId: "cccccccc", parents: [id("b")], summary: second, timeMs: 1795100200000 },
|
||||
{ id: id("b"), shortId: "bbbbbbbb", parents: [id("a")], summary: first, timeMs: 1795100100000 },
|
||||
].map((commit) => ({
|
||||
...commit,
|
||||
refs: [],
|
||||
author: "Sam Rivera",
|
||||
email: "[email protected]",
|
||||
message: commit.summary + "\n\nKeep the audit trail linked to the settlement job.",
|
||||
}));
|
||||
const h = window.__ipc.handlers;
|
||||
h.vcs_roots = () => [{ root, operation: null, head: "main", headCommit: id("c") }];
|
||||
h.vcs_branch_info = () => ({
|
||||
head: "main",
|
||||
headCommit: id("c"),
|
||||
upstream: null,
|
||||
ahead: 0,
|
||||
behind: 0,
|
||||
operation: null,
|
||||
});
|
||||
h.vcs_status = () => [];
|
||||
h.vcs_log = () => commits;
|
||||
h.vcs_log_refs = () => ({});
|
||||
h.vcs_log_users = () => ["Sam Rivera <[email protected]>"];
|
||||
h.vcs_config_get = () => null;
|
||||
h.vcs_commit_files = () => [];
|
||||
h.vcs_log_details_batch = () => [];
|
||||
const vcsPath = "/src/features/vcs/store.ts";
|
||||
const { useVcs } = await import(/* @vite-ignore */ vcsPath);
|
||||
useVcs.setState({ available: true, root, roots: [root], repo: root, branchesLoaded: true });
|
||||
const contextPath = "/src/platform/context.ts";
|
||||
(await import(/* @vite-ignore */ contextPath)).setContext("vcsAvailable", true);
|
||||
const actionsPath = "/src/platform/actions.ts";
|
||||
await (await import(/* @vite-ignore */ actionsPath)).executeAction("vcs.showLog");
|
||||
},
|
||||
{ first, second },
|
||||
);
|
||||
const log = page.getByRole("listbox", { name: "Commits" });
|
||||
await log.getByRole("option", { name: new RegExp(first) }).click({ button: "right" });
|
||||
await page.getByRole("menuitem", { name: /Interactively Rebase from Here/ }).click();
|
||||
const dialog = page.getByRole("dialog", { name: /Rebasing 2 commits/ });
|
||||
await expect(dialog).toBeVisible();
|
||||
|
||||
await page.setViewportSize({ width: 440, height: 640 });
|
||||
const list = dialog.getByRole("list", { name: "Commits to rebase" });
|
||||
const originalRows = list.getByRole("listitem");
|
||||
await dialog.getByRole("button", { name: "Action for bbbbbbbb" }).click();
|
||||
await page.getByRole("option", { name: "Reword", exact: true }).click();
|
||||
const reword = dialog.getByRole("textbox", { name: "New message for bbbbbbbb" });
|
||||
await expect(reword).toHaveValue(first + "\n\nKeep the audit trail linked to the settlement job.");
|
||||
const editor = (await reword.boundingBox())!;
|
||||
expect(editor.width).toBeGreaterThan(260);
|
||||
expect(editor.height).toBeGreaterThan(160);
|
||||
|
||||
const divider = dialog.getByRole("separator", { name: "Resize rebase panes" });
|
||||
await expect(divider).toHaveAttribute("aria-orientation", "horizontal");
|
||||
const start = dialog.getByRole("button", { name: "Start Rebasing" });
|
||||
await expect(start).toBeDisabled();
|
||||
const message = "Keep settlement references stable\n\nPreserve the audit trail.";
|
||||
await reword.fill(message);
|
||||
await expect(start).toBeEnabled();
|
||||
|
||||
await dialog.getByRole("button", { name: "Move Down" }).click();
|
||||
await expect(originalRows.first()).toContainText(second);
|
||||
await expect(reword).toHaveValue(message);
|
||||
await originalRows
|
||||
.first()
|
||||
.getByRole("button", { name: new RegExp(second) })
|
||||
.click();
|
||||
const details = dialog.getByRole("region", { name: "Commit details" });
|
||||
await expect(details).toContainText("Keep the audit trail linked to the settlement job.");
|
||||
|
||||
await page.setViewportSize({ width: 1120, height: 760 });
|
||||
await expect(divider).toHaveAttribute("aria-orientation", "vertical");
|
||||
await expect(details).toContainText(second);
|
||||
await dialog.getByRole("button", { name: "Cancel", exact: true }).click();
|
||||
await expect(dialog).toBeHidden();
|
||||
});
|
||||
@@ -0,0 +1,56 @@
|
||||
import { expect, test } from "./fixtures";
|
||||
|
||||
test("Keymap fits a narrow Settings pane and keeps shortcut editing reachable", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 1080, height: 760 });
|
||||
await page.keyboard.press("Meta+,");
|
||||
const settings = page.getByRole("dialog", { name: "Settings", exact: true });
|
||||
await settings.getByRole("treeitem", { name: "Keymap", exact: true }).click();
|
||||
|
||||
const search = settings.getByRole("textbox", { name: "Search actions" });
|
||||
const expand = settings.getByRole("button", { name: "Expand All", exact: true });
|
||||
await expect(search).toBeVisible();
|
||||
const wideSearch = (await search.boundingBox())!;
|
||||
const wideExpand = (await expand.boundingBox())!;
|
||||
expect(wideExpand.x).toBeLessThan(wideSearch.x);
|
||||
expect(Math.abs(wideExpand.y - wideSearch.y)).toBeLessThan(8);
|
||||
|
||||
await page.setViewportSize({ width: 520, height: 760 });
|
||||
const narrowSearch = (await search.boundingBox())!;
|
||||
const narrowExpand = (await expand.boundingBox())!;
|
||||
expect(narrowSearch.y).toBeGreaterThan(narrowExpand.y + narrowExpand.height);
|
||||
|
||||
const body = settings.locator("[class*='pageBody']");
|
||||
const fitPane = () =>
|
||||
expect.poll(() => body.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
|
||||
await fitPane();
|
||||
|
||||
await search.fill("Reformat Code");
|
||||
const tree = settings.getByRole("tree", { name: "Actions", exact: true });
|
||||
const action = tree
|
||||
.getByRole("treeitem")
|
||||
.filter({ hasText: /Reformat Code/ })
|
||||
.first();
|
||||
await action.click();
|
||||
await settings.getByRole("button", { name: "Add Keyboard Shortcut", exact: true }).click();
|
||||
const recorder = page.getByRole("dialog", { name: /Keyboard Shortcut: Reformat Code/ });
|
||||
await recorder.getByRole("textbox", { name: "First stroke" }).press("Control+Alt+Shift+F8");
|
||||
await expect(recorder.getByText("No conflicts")).toBeVisible();
|
||||
await recorder.getByRole("button", { name: "OK", exact: true }).click();
|
||||
await expect(action.locator("kbd").filter({ hasText: "F8" })).toHaveCount(1);
|
||||
|
||||
const title = action.getByText(/Reformat Code/).first();
|
||||
await expect.poll(() => title.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
|
||||
await tree.evaluate((el) => {
|
||||
el.scrollLeft = el.scrollWidth;
|
||||
});
|
||||
expect(await tree.evaluate((el) => el.scrollLeft)).toBeGreaterThan(0);
|
||||
await fitPane();
|
||||
|
||||
await settings.getByRole("button", { name: "Find Actions by Shortcut" }).click();
|
||||
await settings.getByRole("textbox", { name: "Find actions by shortcut" }).press("Control+Alt+Shift+F8");
|
||||
await expect(action).toBeVisible();
|
||||
await fitPane();
|
||||
|
||||
await settings.getByRole("button", { name: "Apply", exact: true }).click();
|
||||
await expect(settings.getByRole("button", { name: "Apply", exact: true })).toBeDisabled();
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
import { expect, test } from "./fixtures";
|
||||
|
||||
test("Plugin management keeps the selected details reachable when Settings narrows", async ({ workbench: page }) => {
|
||||
const name = "ReconciliationTimelineInspectorEnterprise";
|
||||
const notes = "SettlementTimeline".repeat(18);
|
||||
await page.evaluate(
|
||||
async ({ name, notes }) => {
|
||||
const path = "/src/features/plugins/backend.ts";
|
||||
const { createMemoryPluginsBackend, setPluginsBackend } = await import(/* @vite-ignore */ path);
|
||||
const { plugins } = await createMemoryPluginsBackend().list();
|
||||
const longPlugin = { ...plugins[0], id: "settlement-inspector", name, changeNotes: notes };
|
||||
setPluginsBackend(createMemoryPluginsBackend([longPlugin, ...plugins.slice(1)]));
|
||||
},
|
||||
{ name, notes },
|
||||
);
|
||||
|
||||
await page.setViewportSize({ width: 1080, height: 760 });
|
||||
await page.keyboard.press("Meta+,");
|
||||
const settings = page.getByRole("dialog", { name: "Settings", exact: true });
|
||||
await settings.getByRole("treeitem", { name: "Plugins", exact: true }).click();
|
||||
await settings.getByRole("tab", { name: "Installed", exact: true }).click();
|
||||
|
||||
const filter = settings.getByRole("textbox", { name: "Filter plugins" });
|
||||
const list = settings.getByRole("list", { name: "Installed plugins" });
|
||||
const details = settings.getByLabel(`${name} details`);
|
||||
const heading = details.getByRole("heading", { name, exact: true });
|
||||
await expect(heading).toBeVisible();
|
||||
|
||||
const filterBox = (await filter.boundingBox())!;
|
||||
const headingBox = (await heading.boundingBox())!;
|
||||
expect(headingBox.x).toBeGreaterThan(filterBox.x + filterBox.width);
|
||||
|
||||
await page.setViewportSize({ width: 520, height: 760 });
|
||||
const body = settings.locator("[class*='pageBody']");
|
||||
await expect.poll(() => body.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
|
||||
const divider = settings.getByRole("separator", { name: "Resize plugin panes" });
|
||||
await expect(divider).toHaveAttribute("aria-orientation", "horizontal");
|
||||
const sources = settings.getByRole("tablist", { name: "Plugin sources" });
|
||||
await expect(sources.getByRole("tab", { name: "Marketplace" })).toBeVisible();
|
||||
await expect(sources.getByRole("tab", { name: "Installed" })).toBeVisible();
|
||||
expect(await sources.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
|
||||
|
||||
const before = (await divider.boundingBox())!.y;
|
||||
await divider.focus();
|
||||
await page.keyboard.press("ArrowDown");
|
||||
await expect.poll(async () => (await divider.boundingBox())!.y).toBeGreaterThan(before);
|
||||
await expect(details.getByRole("button", { name: "Disable", exact: true })).toBeVisible();
|
||||
|
||||
await details.getByRole("tab", { name: "What's New" }).click();
|
||||
await expect(details.getByText(notes, { exact: true })).toBeVisible();
|
||||
expect(await details.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
|
||||
|
||||
await filter.click();
|
||||
await expect(filter).toBeFocused();
|
||||
await filter.pressSequentially("Harbor");
|
||||
await list.getByRole("button", { name: /Harbor Night Theme/ }).click();
|
||||
await expect(settings.getByRole("heading", { name: "Harbor Night Theme", exact: true })).toBeVisible();
|
||||
await page.setViewportSize({ width: 1080, height: 760 });
|
||||
await expect(divider).toHaveAttribute("aria-orientation", "vertical");
|
||||
await expect(filter).toHaveValue("Harbor");
|
||||
await expect(settings.getByRole("heading", { name: "Harbor Night Theme", exact: true })).toBeVisible();
|
||||
});
|
||||
@@ -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();
|
||||
});
|
||||
@@ -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");
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
diff --git a/dist/index.cjs b/dist/index.cjs
|
||||
index b20aa9d84be6ff4b85b126bdd930065277668a26..e677ab06ca9668407e202979e14b75ab7641d6b1 100644
|
||||
--- a/dist/index.cjs
|
||||
+++ b/dist/index.cjs
|
||||
@@ -9675,7 +9675,9 @@ const hideNativeSelection = state.Prec.highest(EditorView.theme({
|
||||
"& :focus": {
|
||||
caretColor: "initial !important",
|
||||
...drawMainRange ? {
|
||||
- "&::selection, & ::selection": {
|
||||
+ // Not `& ::selection` too: a pseudo-class with a universal descendant restyles the
|
||||
+ // whole subtree of every element that gains or loses focus.
|
||||
+ "&::selection": {
|
||||
backgroundColor: "Highlight !important"
|
||||
}
|
||||
} : {}
|
||||
diff --git a/dist/index.js b/dist/index.js
|
||||
index 216f754db06f65f7f17f056b47d8f6fab45067bf..22282993239d836ea1da19af10ccfc61b6480cc5 100644
|
||||
--- a/dist/index.js
|
||||
+++ b/dist/index.js
|
||||
@@ -9670,7 +9670,9 @@ const hideNativeSelection = /*@__PURE__*/Prec.highest(/*@__PURE__*/EditorView.th
|
||||
"& :focus": {
|
||||
caretColor: "initial !important",
|
||||
...drawMainRange ? {
|
||||
- "&::selection, & ::selection": {
|
||||
+ // Not `& ::selection` too: a pseudo-class with a universal descendant restyles the
|
||||
+ // whole subtree of every element that gains or loses focus.
|
||||
+ "&::selection": {
|
||||
backgroundColor: "Highlight !important"
|
||||
}
|
||||
} : {}
|
||||
+34
-25
@@ -323,6 +323,18 @@ const scroll: Scenario = {
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* Runs an action without a default shortcut from a key press: the press is the measured input,
|
||||
* and the action runs in its handler, as from a key binding. Pause is bound to nothing.
|
||||
*/
|
||||
async function runActionOnKey(h: Harness, id: string) {
|
||||
await h.page.evaluate((id) => {
|
||||
const probe = (window as never as { __openideaPerf: { runAction(id: string): Promise<boolean> } }).__openideaPerf;
|
||||
addEventListener("keydown", () => void probe.runAction(id), { capture: true, once: true });
|
||||
}, id);
|
||||
await h.page.keyboard.press("Pause");
|
||||
}
|
||||
|
||||
/**
|
||||
* Git Log with 20,000 commits on branching lanes, loaded page by page as the
|
||||
* backend does (150 ms a page, like `git log`): showing it, walking the
|
||||
@@ -339,12 +351,7 @@ const gitLog: Scenario = {
|
||||
).__openideaPerf.fakeGitLog(20_000, 150),
|
||||
);
|
||||
const showMs = await h.measure(
|
||||
() =>
|
||||
h.page.evaluate(() =>
|
||||
(window as never as { __openideaPerf: { runAction(id: string): Promise<boolean> } }).__openideaPerf.runAction(
|
||||
"vcs.showLog",
|
||||
),
|
||||
),
|
||||
() => runActionOnKey(h, "vcs.showLog"),
|
||||
'[role="listbox"][aria-label="Commits"]',
|
||||
"order flow step 0",
|
||||
);
|
||||
@@ -430,16 +437,13 @@ const resizePanels: Scenario = {
|
||||
await h.page.evaluate(() =>
|
||||
(window as never as { __openideaPerf: { fakeGitLog(n: number): void } }).__openideaPerf.fakeGitLog(2_000),
|
||||
);
|
||||
await h.measure(
|
||||
() =>
|
||||
h.page.evaluate(() =>
|
||||
(window as never as { __openideaPerf: { runAction(id: string): Promise<boolean> } }).__openideaPerf.runAction(
|
||||
"vcs.showLog",
|
||||
),
|
||||
),
|
||||
'[role="listbox"][aria-label="Commits"]',
|
||||
"order flow step 0",
|
||||
await h.page.evaluate(() =>
|
||||
(window as never as { __openideaPerf: { runAction(id: string): Promise<boolean> } }).__openideaPerf.runAction(
|
||||
"vcs.showLog",
|
||||
),
|
||||
);
|
||||
// Set-up, not measured: the splitters are dragged once the log is shown.
|
||||
await h.inPage((p) => p.waitShown('[role="listbox"][aria-label="Commits"]', "order flow step 0", 10_000));
|
||||
const refresh = await h.refreshMs();
|
||||
const drag = async (name: string, dx: number, dy: number) => {
|
||||
const box = (await h.page.getByRole("separator", { name }).boundingBox())!;
|
||||
@@ -560,7 +564,9 @@ const agentTabs: Scenario = {
|
||||
window as never as { __openideaPerf: { runAction(id: string, arg?: unknown): Promise<boolean> } }
|
||||
).__openideaPerf.runAction("agents.openSampleConversations", { tasks: 2, turns: 150 }),
|
||||
);
|
||||
const shown = (n: number) => `[data-editor-focus] span[title="Sample task ${n}"]`;
|
||||
// The conversation shown: its requests end with its task's title.
|
||||
const SHOWN = "[data-editor-focus] [data-message]";
|
||||
const title = (n: number) => `(Sample task ${n})`;
|
||||
// Both conversations get their earlier entries painted in background batches, also the
|
||||
// first one, hidden behind the second as soon as it opened.
|
||||
await h.page.waitForFunction(
|
||||
@@ -575,25 +581,28 @@ const agentTabs: Scenario = {
|
||||
// Rows painted while hidden are laid out the first time their conversation shows.
|
||||
for (const n of [1, 2]) {
|
||||
await h.page.getByRole("tab", { name: `Sample task ${n}` }).click();
|
||||
await h.page.locator(shown(n)).waitFor();
|
||||
await h.page
|
||||
.locator(SHOWN, { hasText: title(n) })
|
||||
.first()
|
||||
.waitFor();
|
||||
await h.page.waitForTimeout(300);
|
||||
}
|
||||
// WebKit restyles a hidden conversation in full when it is shown again (Chromium keeps its
|
||||
// style): what bounds that there is the history's DOM, and rows skipping rendering off screen.
|
||||
const { conversationNodes, rowsAlwaysRendered } = await h.page.evaluate((selector) => {
|
||||
const conversation = document.querySelector(selector)!.closest("[data-editor-focus]")!;
|
||||
const conversation = document.querySelector(selector)!;
|
||||
const rows = [...conversation.querySelector("[data-message]")!.parentElement!.children];
|
||||
return {
|
||||
conversationNodes: conversation.querySelectorAll("*").length,
|
||||
rowsAlwaysRendered: rows.filter((r) => getComputedStyle(r).contentVisibility !== "auto").length,
|
||||
};
|
||||
}, shown(2));
|
||||
}, "[data-editor-focus]");
|
||||
|
||||
const t0 = await h.now();
|
||||
const before = await h.counters();
|
||||
const switches: number[] = [];
|
||||
for (let i = 0; i < 10; i++) {
|
||||
switches.push(await h.measure(() => h.pressAction("navigate.switcher"), shown(i % 2 ? 2 : 1)));
|
||||
switches.push(await h.measure(() => h.pressAction("navigate.switcher"), SHOWN, title(i % 2 ? 2 : 1)));
|
||||
await h.page.waitForTimeout(150);
|
||||
}
|
||||
const work = Harness.delta(before, await h.counters());
|
||||
@@ -602,10 +611,7 @@ const agentTabs: Scenario = {
|
||||
// Scrolling up from the end, a step at a time: how far the text under the pointer moves
|
||||
// beyond the scroll itself.
|
||||
const scrollJumps = await h.page.evaluate(async (selector) => {
|
||||
const stream = document
|
||||
.querySelector(selector)!
|
||||
.closest("[data-editor-focus]")!
|
||||
.querySelector("[data-message]")!.parentElement!;
|
||||
const stream = document.querySelector(selector)!.parentElement!;
|
||||
const frame = () => new Promise(requestAnimationFrame);
|
||||
stream.scrollTop = stream.scrollHeight;
|
||||
await frame();
|
||||
@@ -626,7 +632,7 @@ const agentTabs: Scenario = {
|
||||
}
|
||||
stream.scrollTop = stream.scrollHeight;
|
||||
return jumps;
|
||||
}, shown(2));
|
||||
}, SHOWN);
|
||||
|
||||
const refresh = await h.refreshMs();
|
||||
const box = (await h.page.locator("[data-editor-focus]").boundingBox())!;
|
||||
@@ -732,6 +738,9 @@ const projectTree: Scenario = {
|
||||
async run(h) {
|
||||
const generated = h.page.locator('[role="treeitem"][aria-level="2"]', { hasText: "generated" }).first();
|
||||
await generated.click();
|
||||
// Measure from a settled selection: a key pressed in the click's own frame also pays for that frame.
|
||||
await generated.and(h.page.locator('[aria-selected="true"]')).waitFor();
|
||||
await h.page.evaluate(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r))));
|
||||
const expandMs = await h.measure(
|
||||
() => h.page.keyboard.press("ArrowRight"),
|
||||
'[role="tree"][aria-label="Project"]',
|
||||
|
||||
Створено
+20
-24
@@ -7,6 +7,9 @@ settings:
|
||||
overrides:
|
||||
mermaid>katex: ^0.18.2
|
||||
|
||||
patchedDependencies:
|
||||
'@codemirror/view': 0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5
|
||||
|
||||
importers:
|
||||
|
||||
.:
|
||||
@@ -61,7 +64,7 @@ importers:
|
||||
version: 6.7.6
|
||||
'@codemirror/view':
|
||||
specifier: ^6.43.14
|
||||
version: 6.43.14
|
||||
version: 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
|
||||
'@floating-ui/react-dom':
|
||||
specifier: ^2.1.9
|
||||
version: 2.1.9([email protected]([email protected]))([email protected])
|
||||
@@ -85,7 +88,7 @@ importers:
|
||||
version: 1.2.0
|
||||
'@replit/codemirror-vim':
|
||||
specifier: 6.4.0
|
||||
version: 6.4.0(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])
|
||||
version: 6.4.0(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected](patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5))
|
||||
'@tanstack/react-virtual':
|
||||
specifier: ^3.14.21
|
||||
version: 3.14.21([email protected]([email protected]))([email protected])
|
||||
@@ -591,7 +594,6 @@ packages:
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
cpu: [riscv64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@oxc-parser/[email protected]':
|
||||
resolution: {integrity: sha512-JSlhgoK+/g1TGJI5NuADx2+6syhxnQNLCWLXyO5QLFyetomcr/vIxSdiNlmyAv963YXUzCuwAwRG6npZ5xyJ1A==}
|
||||
@@ -1069,7 +1071,6 @@ packages:
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
libc: [musl]
|
||||
|
||||
'@rolldown/[email protected]':
|
||||
resolution: {integrity: sha512-4+Kl8daPV8NDHaD7mfCcc1pRM+Qg7ab8DyMm5FG5WoZgv4h2i3KFN1CybYBNbQqmuYm7ftJLvmMI1eHYJ22S/Q==}
|
||||
@@ -1083,14 +1084,12 @@ packages:
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
cpu: [s390x]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@rolldown/[email protected]':
|
||||
resolution: {integrity: sha512-WxalXzgrLVpKC93xfpaJ3gCXUWzeCr+FRCbDVD2mUAy4L6Vo3lNVz0epUEUpxPWJkLNYUwM4OSIikv36OJ9mLg==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@rolldown/[email protected]':
|
||||
resolution: {integrity: sha512-3G3tnAmTpdk9jO3GQtyHXqeFD2SlecfTws/Y3M2mmj9nMBwwuLT4kur8sZKeu7ENUHSpVO3cIsm5A52LEWWwlg==}
|
||||
@@ -1864,7 +1863,6 @@ packages:
|
||||
engines: {node: '>= 12.0.0'}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==}
|
||||
@@ -1878,14 +1876,12 @@ packages:
|
||||
engines: {node: '>= 12.0.0'}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==}
|
||||
engines: {node: '>= 12.0.0'}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
libc: [musl]
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==}
|
||||
@@ -2391,14 +2387,14 @@ snapshots:
|
||||
dependencies:
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.14
|
||||
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
|
||||
'@lezer/common': 1.5.3
|
||||
|
||||
'@codemirror/[email protected]':
|
||||
dependencies:
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.14
|
||||
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
|
||||
'@lezer/common': 1.5.3
|
||||
|
||||
'@codemirror/[email protected]':
|
||||
@@ -2438,7 +2434,7 @@ snapshots:
|
||||
'@codemirror/lang-javascript': 6.2.5
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.14
|
||||
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/css': 1.3.9
|
||||
'@lezer/html': 1.3.13
|
||||
@@ -2454,7 +2450,7 @@ snapshots:
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/lint': 6.9.7
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.14
|
||||
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/javascript': 1.5.6
|
||||
|
||||
@@ -2464,7 +2460,7 @@ snapshots:
|
||||
'@codemirror/lang-html': 6.4.12
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.14
|
||||
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11
|
||||
@@ -2488,7 +2484,7 @@ snapshots:
|
||||
'@codemirror/lang-html': 6.4.12
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.14
|
||||
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11
|
||||
@@ -2499,7 +2495,7 @@ snapshots:
|
||||
'@codemirror/lang-html': 6.4.12
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.14
|
||||
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/markdown': 1.8.0
|
||||
|
||||
@@ -2562,7 +2558,7 @@ snapshots:
|
||||
'@codemirror/autocomplete': 6.20.3
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.14
|
||||
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/xml': 1.0.6
|
||||
|
||||
@@ -2606,7 +2602,7 @@ snapshots:
|
||||
dependencies:
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/streamparser': 6.0.0
|
||||
'@codemirror/view': 6.43.14
|
||||
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11
|
||||
@@ -2619,21 +2615,21 @@ snapshots:
|
||||
'@codemirror/[email protected]':
|
||||
dependencies:
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.14
|
||||
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
|
||||
crelt: 1.0.7
|
||||
|
||||
'@codemirror/[email protected]':
|
||||
dependencies:
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.14
|
||||
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
|
||||
'@lezer/highlight': 1.2.5
|
||||
style-mod: 4.1.4
|
||||
|
||||
'@codemirror/[email protected]':
|
||||
dependencies:
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.14
|
||||
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
|
||||
crelt: 1.0.7
|
||||
|
||||
'@codemirror/[email protected]':
|
||||
@@ -2642,7 +2638,7 @@ snapshots:
|
||||
|
||||
'@codemirror/[email protected]': {}
|
||||
|
||||
'@codemirror/[email protected]':
|
||||
'@codemirror/[email protected](patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)':
|
||||
dependencies:
|
||||
'@codemirror/state': 6.7.6
|
||||
crelt: 1.0.7
|
||||
@@ -3105,13 +3101,13 @@ snapshots:
|
||||
|
||||
'@replit/[email protected]': {}
|
||||
|
||||
'@replit/[email protected](@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])':
|
||||
'@replit/[email protected](@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected](patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5))':
|
||||
dependencies:
|
||||
'@codemirror/commands': 6.11.1
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/search': 6.7.2
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.14
|
||||
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
|
||||
'@replit/codemirror-vim-core': 0.1.0
|
||||
|
||||
'@rolldown/[email protected]':
|
||||
|
||||
@@ -3,3 +3,5 @@ allowBuilds:
|
||||
overrides:
|
||||
# GHSA-238p-pmpm-9mq7 (fixed in 0.18.2); mermaid 12.1 still asks for katex ^0.16.
|
||||
mermaid>katex: ^0.18.2
|
||||
patchedDependencies:
|
||||
"@codemirror/view": patches/@codemirror__view.patch
|
||||
@@ -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();
|
||||
|
||||
@@ -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`
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -2602,18 +2602,6 @@ export type AgentSettings_Deserialize = {
|
||||
smoothText?: boolean,
|
||||
/** Conversations and the composer expand to the full width of the pane instead of staying in a centred column. */
|
||||
fitWindowWidth?: boolean,
|
||||
/** While the agent works, playful words fill the pauses in what it reports. */
|
||||
playfulStatus?: boolean,
|
||||
/**
|
||||
* Seconds the agent reports nothing new before the playful words take over; 0 shows them
|
||||
* from the start.
|
||||
*/
|
||||
playfulAfterSeconds?: number,
|
||||
/**
|
||||
* The user's playful words by activity (`working`, `thinking`, `reading`, …), replacing
|
||||
* the built-in ones of that activity; an empty list keeps its status factual.
|
||||
*/
|
||||
playfulWords?: { [key in string]: string[] },
|
||||
thinking?: ThinkingDisplay,
|
||||
toolCalls?: ToolCallDisplay,
|
||||
/** A tool call's output (a command's, a diff) is shown without opening it. */
|
||||
@@ -2654,18 +2642,6 @@ export type AgentSettings_Serialize = {
|
||||
smoothText: boolean,
|
||||
/** Conversations and the composer expand to the full width of the pane instead of staying in a centred column. */
|
||||
fitWindowWidth: boolean,
|
||||
/** While the agent works, playful words fill the pauses in what it reports. */
|
||||
playfulStatus: boolean,
|
||||
/**
|
||||
* Seconds the agent reports nothing new before the playful words take over; 0 shows them
|
||||
* from the start.
|
||||
*/
|
||||
playfulAfterSeconds: number,
|
||||
/**
|
||||
* The user's playful words by activity (`working`, `thinking`, `reading`, …), replacing
|
||||
* the built-in ones of that activity; an empty list keeps its status factual.
|
||||
*/
|
||||
playfulWords: { [key in string]: string[] },
|
||||
thinking: ThinkingDisplay,
|
||||
toolCalls: ToolCallDisplay,
|
||||
/** A tool call's output (a command's, a diff) is shown without opening it. */
|
||||
|
||||
@@ -51,7 +51,9 @@ class CornerInset {
|
||||
|
||||
private measure() {
|
||||
const corner = this.corner;
|
||||
if (!corner) return;
|
||||
// A hidden tab's view is detached and measures 0: keeping the inset spares every line
|
||||
// a restyle when the tab hides and another when it shows again.
|
||||
if (!corner || !this.view.dom.isConnected) return;
|
||||
const width = corner.getBoundingClientRect().width;
|
||||
let inset = width > 0 ? round(width) + CORNER_GAP : 0;
|
||||
// A narrow window or a wide corner: keep at least half of the width for text.
|
||||
|
||||
@@ -20,16 +20,12 @@ import { countColumn, Facet, RangeSetBuilder, type EditorState, type Extension }
|
||||
import { Decoration, EditorView, ViewPlugin, type DecorationSet, type ViewUpdate } from "@codemirror/view";
|
||||
import { getIndentUnit, matchBrackets, syntaxTree } from "@codemirror/language";
|
||||
import { LINE_INSET } from "./lineInset";
|
||||
import { SPACE, spaceWidth } from "./spaceWidth";
|
||||
import { BRACKET_COLORS, LONG_LINE, bracketScanner, type BracketScanner } from "./rainbowBrackets";
|
||||
|
||||
/** How far (px) a guide sits left of its column, so a caret in that column is right of it (IDEA's indent guide shift). */
|
||||
const GUIDE_SHIFT = 2;
|
||||
|
||||
/** One column of indentation: a space in the editor font, as measured by the guides plugin. */
|
||||
const SPACE = "var(--openidea-space, 1ch)";
|
||||
|
||||
const SPACE_SAMPLE = 64;
|
||||
|
||||
/** Number of `--openidea-guide-<n>` rainbow colours; deeper guides repeat them. */
|
||||
export const GUIDE_COLORS = 5;
|
||||
|
||||
@@ -325,37 +321,20 @@ function build(
|
||||
}
|
||||
|
||||
export const indentGuides: Extension = [
|
||||
spaceWidth,
|
||||
ViewPlugin.fromClass(
|
||||
class {
|
||||
decorations: DecorationSet;
|
||||
private probe: HTMLElement;
|
||||
private brackets: BracketCache[] = [];
|
||||
/** Guide variables of each decorated line, by its start: code lens rows above it repeat them. */
|
||||
private lineVars = new Map<number, { images: string; positions: string }>();
|
||||
private scanner: BracketScanner | null;
|
||||
constructor(readonly view: EditorView) {
|
||||
// Inherits the editor font from the scroller, outside the content CodeMirror observes;
|
||||
// the measured width goes on the scroller, where lines and code lens rows pick it up.
|
||||
this.probe = document.createElement("span");
|
||||
this.probe.setAttribute("aria-hidden", "true");
|
||||
this.probe.style.cssText = "position: absolute; top: 0; left: 0; visibility: hidden; white-space: pre";
|
||||
this.probe.textContent = " ".repeat(SPACE_SAMPLE);
|
||||
view.scrollDOM.appendChild(this.probe);
|
||||
const scanner = bracketScanner(view);
|
||||
this.scanner = scanner;
|
||||
this.decorations = build(view, scanner, this.brackets, this.lineVars);
|
||||
this.measure();
|
||||
this.syncLenses();
|
||||
}
|
||||
measure() {
|
||||
this.view.requestMeasure({
|
||||
key: this,
|
||||
read: (view) => this.probe.getBoundingClientRect().width / (view.scaleX || 1) / SPACE_SAMPLE,
|
||||
write: (width, view) => {
|
||||
if (width > 0) view.scrollDOM.style.setProperty("--openidea-space", `${+width.toFixed(3)}px`);
|
||||
},
|
||||
});
|
||||
}
|
||||
/** Gives code lens rows the guides of the line they annotate, once they are in the DOM. */
|
||||
syncLenses() {
|
||||
this.view.requestMeasure({
|
||||
@@ -379,15 +358,12 @@ export const indentGuides: Extension = [
|
||||
});
|
||||
}
|
||||
destroy() {
|
||||
this.probe.remove();
|
||||
this.view.scrollDOM.style.removeProperty("--openidea-space");
|
||||
for (const el of this.view.contentDOM.querySelectorAll<HTMLElement>(".cm-openidea-lens")) {
|
||||
el.style.removeProperty("--openidea-guide-images");
|
||||
el.style.removeProperty("--openidea-guide-positions");
|
||||
}
|
||||
}
|
||||
update(u: ViewUpdate) {
|
||||
if (u.geometryChanged) this.measure();
|
||||
const scanner = bracketScanner(u.view);
|
||||
// A new scanner (rainbow brackets toggled or reconfigured) may colour blocks differently.
|
||||
const bracketsChanged = scanner !== this.scanner;
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { registerEditorContribution } from "@/editor/api";
|
||||
import { prewarmEditor } from "./prewarm";
|
||||
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
|
||||
it("builds an off-screen editor with embedded contributions only, then removes it", () => {
|
||||
let frame: FrameRequestCallback | undefined;
|
||||
vi.stubGlobal("requestAnimationFrame", (f: FrameRequestCallback) => ((frame = f), 1));
|
||||
const seen: string[] = [];
|
||||
const offEmbedded = registerEditorContribution({
|
||||
id: "test.embedded",
|
||||
embedded: true,
|
||||
extensions: (ctx) => (seen.push(`embedded ${ctx.doc}`), []),
|
||||
});
|
||||
const offFile = registerEditorContribution({
|
||||
id: "test.file",
|
||||
extensions: () => (seen.push("file"), []),
|
||||
});
|
||||
try {
|
||||
prewarmEditor();
|
||||
expect(document.querySelectorAll(".cm-editor")).toHaveLength(1);
|
||||
expect(seen).toEqual(["embedded -1"]);
|
||||
frame!(0);
|
||||
expect(document.querySelector(".cm-editor")).toBeNull();
|
||||
expect(document.body.children).toHaveLength(0);
|
||||
} finally {
|
||||
offEmbedded();
|
||||
offFile();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
import { EditorState, type Extension } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { editorContributions, type EditorDocContext } from "@/editor/api";
|
||||
import { baseExtensions } from "./setup";
|
||||
|
||||
/**
|
||||
* Builds and drops an off-screen editor with the file editors' setup, so the first file opened
|
||||
* does not also pay for compiling the editor code and mounting its stylesheets. The document is
|
||||
* virtual and empty, and only contributions that accept such editors (`embedded`) take part:
|
||||
* nothing reaches a language server or the file system.
|
||||
*/
|
||||
export function prewarmEditor(): void {
|
||||
const host = document.createElement("div");
|
||||
host.setAttribute("aria-hidden", "true");
|
||||
host.style.cssText = "position:fixed;left:-10000px;top:0;width:480px;height:240px;visibility:hidden;contain:strict";
|
||||
document.body.appendChild(host);
|
||||
const ctx: EditorDocContext = {
|
||||
doc: -1,
|
||||
path: "prewarm.txt",
|
||||
language: "plaintext",
|
||||
uiMode: null,
|
||||
readOnly: true,
|
||||
virtual: true,
|
||||
};
|
||||
const contributions: Extension[] = [];
|
||||
for (const c of editorContributions()) {
|
||||
if (!c.embedded) continue;
|
||||
try {
|
||||
contributions.push(c.extensions(ctx));
|
||||
} catch {
|
||||
// Warming is best effort: the real editor reports a failing contribution.
|
||||
}
|
||||
}
|
||||
const view = new EditorView({
|
||||
parent: host,
|
||||
state: EditorState.create({
|
||||
doc: "",
|
||||
extensions: baseExtensions({
|
||||
ctx,
|
||||
settings: undefined,
|
||||
info: undefined,
|
||||
language: null,
|
||||
docLength: 0,
|
||||
indent: { tabSize: 4, insertSpaces: true },
|
||||
wrapOverride: false,
|
||||
contributions,
|
||||
}),
|
||||
}),
|
||||
});
|
||||
// One frame so its measure pass runs too, then nothing of it is left behind.
|
||||
requestAnimationFrame(() => {
|
||||
view.destroy();
|
||||
host.remove();
|
||||
});
|
||||
}
|
||||
@@ -189,7 +189,7 @@ it("indents by the code's character width, so a font size change keeps it in lin
|
||||
const v = open(true, ["class A {", "\t/**", "\t * Books.", "\t */", "\tvoid book() {}", "}"].join("\n"));
|
||||
const body = v.dom.querySelector<HTMLElement>(".cm-openidea-renderedDoc")!;
|
||||
// A tab is a tab size of columns, not one character.
|
||||
expect(body.style.marginLeft).toContain(`${v.state.tabSize} * var(--openidea-doc-char`);
|
||||
expect(body.style.marginLeft).toContain(`${v.state.tabSize} * var(--openidea-space`);
|
||||
});
|
||||
|
||||
it("forgets a flip whose comment is deleted, so the feature turns off again", async () => {
|
||||
|
||||
@@ -61,6 +61,7 @@ import { tx, useI18n } from "@/platform/i18n";
|
||||
import { loadMarkdown, markupToHtml } from "@/editor/lsp/markdown";
|
||||
import { hasContent, renderDoc, type DocComment, type DocStyle, type RenderedDoc } from "./docRender";
|
||||
import { LINE_INSET } from "./lineInset";
|
||||
import { SPACE, spaceWidth } from "./spaceWidth";
|
||||
|
||||
/** The file's default: render its doc comments or not. */
|
||||
export const renderDocComments = Facet.define<boolean, boolean>({
|
||||
@@ -320,9 +321,9 @@ class DocWidget extends WidgetType {
|
||||
const titles = doc.sections.map(sectionTitle);
|
||||
const dom = document.createElement("div");
|
||||
dom.className = "cm-openidea-renderedDoc";
|
||||
// In the code's character width, which `docMetrics` keeps current: the DOM stays
|
||||
// right through a font size change or zoom, which does not draw the widget again.
|
||||
const left = `(${this.indent} * var(--openidea-doc-char, 1ch) + ${LINE_INSET}px)`;
|
||||
// In columns of the code's font (`spaceWidth`): the DOM stays right through a font
|
||||
// size change or zoom, which does not draw the widget again.
|
||||
const left = `(${this.indent} * ${SPACE} + ${LINE_INSET}px)`;
|
||||
dom.style.marginLeft = `calc${left}`;
|
||||
// The content is as wide as its longest line; the comment wraps at the visible width instead.
|
||||
dom.style.maxWidth = `calc(var(--openidea-doc-width, 100%) - ${left} - ${DOC_RIGHT_GAP}px)`;
|
||||
@@ -827,12 +828,10 @@ export function toggleRenderedViewAtCaret(view: EditorView): boolean {
|
||||
const DOC_RIGHT_GAP = 24;
|
||||
|
||||
/**
|
||||
* Publishes on the content the visible width of the text area, `--openidea-doc-width`,
|
||||
* and the code's character width, `--openidea-doc-char`. A block widget is as wide as
|
||||
* the content, which without soft wraps is as wide as the longest line, so a rendered
|
||||
* comment needs the first to wrap where the reader can see, as IDEA's does; it indents
|
||||
* by the second, which a font size change or zoom changes. Horizontal scrolling leaves
|
||||
* both unchanged.
|
||||
* Publishes on the content the visible width of the text area, `--openidea-doc-width`.
|
||||
* A block widget is as wide as the content, which without soft wraps is as wide as the
|
||||
* longest line, so a rendered comment needs it to wrap where the reader can see.
|
||||
* Scrolling leaves it unchanged, so lines are not restyled while scrolling.
|
||||
*/
|
||||
const docMetrics = ViewPlugin.fromClass(
|
||||
class {
|
||||
@@ -845,18 +844,12 @@ const docMetrics = ViewPlugin.fromClass(
|
||||
measure() {
|
||||
this.view.requestMeasure({
|
||||
key: this,
|
||||
read: (view) => ({
|
||||
width: view.scrollDOM.clientWidth - view.contentDOM.offsetLeft,
|
||||
char: view.defaultCharacterWidth,
|
||||
}),
|
||||
write: ({ width, char }, view) => {
|
||||
read: (view) => view.scrollDOM.clientWidth - view.contentDOM.offsetLeft,
|
||||
write: (width, view) => {
|
||||
const style = view.contentDOM.style;
|
||||
const widthValue = `${Math.max(0, Math.floor(width))}px`;
|
||||
if (style.getPropertyValue("--openidea-doc-width") !== widthValue)
|
||||
style.setProperty("--openidea-doc-width", widthValue);
|
||||
const charValue = `${char}px`;
|
||||
if (style.getPropertyValue("--openidea-doc-char") !== charValue)
|
||||
style.setProperty("--openidea-doc-char", charValue);
|
||||
const value = `${Math.max(0, Math.floor(width))}px`;
|
||||
if (style.getPropertyValue("--openidea-doc-width") !== value)
|
||||
style.setProperty("--openidea-doc-width", value);
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -947,5 +940,6 @@ export const renderedDocsExtension: Extension = [
|
||||
markdownReady,
|
||||
languageWatcher,
|
||||
docMetrics,
|
||||
spaceWidth,
|
||||
docsTheme,
|
||||
];
|
||||
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* The editor font's space width, published on the scroller as `--openidea-space`
|
||||
* for anything laid out in columns of indentation (indent guides, code lens rows,
|
||||
* rendered doc comments). A space is measured, not `ch`: in a proportional font it
|
||||
* is narrower than "0". The probe's text is fixed, so the value only changes with
|
||||
* the font, its size or zoom; `defaultCharacterWidth` is sampled from whichever
|
||||
* line is in view and drifts while scrolling, and an inherited variable that
|
||||
* changes restyles every line.
|
||||
*/
|
||||
import { EditorView, ViewPlugin, type ViewUpdate } from "@codemirror/view";
|
||||
|
||||
/** One column of indentation, as a CSS length. */
|
||||
export const SPACE = "var(--openidea-space, 1ch)";
|
||||
|
||||
const SAMPLE = 64;
|
||||
|
||||
/** Shared by every extension that lays out by `SPACE`; CodeMirror installs it once. */
|
||||
export const spaceWidth = ViewPlugin.fromClass(
|
||||
class {
|
||||
private probe: HTMLElement;
|
||||
private written = "";
|
||||
constructor(readonly view: EditorView) {
|
||||
// Inherits the editor font from the scroller, outside the content CodeMirror observes.
|
||||
this.probe = document.createElement("span");
|
||||
this.probe.setAttribute("aria-hidden", "true");
|
||||
this.probe.style.cssText = "position: absolute; top: 0; left: 0; visibility: hidden; white-space: pre";
|
||||
this.probe.textContent = " ".repeat(SAMPLE);
|
||||
view.scrollDOM.appendChild(this.probe);
|
||||
this.measure();
|
||||
}
|
||||
measure() {
|
||||
this.view.requestMeasure({
|
||||
key: this,
|
||||
read: (view) => this.probe.getBoundingClientRect().width / (view.scaleX || 1) / SAMPLE,
|
||||
write: (width, view) => {
|
||||
const value = `${+width.toFixed(3)}px`;
|
||||
if (width <= 0 || value === this.written) return;
|
||||
this.written = value;
|
||||
view.scrollDOM.style.setProperty("--openidea-space", value);
|
||||
},
|
||||
});
|
||||
}
|
||||
update(u: ViewUpdate) {
|
||||
if (u.geometryChanged) this.measure();
|
||||
}
|
||||
destroy() {
|
||||
this.probe.remove();
|
||||
this.view.scrollDOM.style.removeProperty("--openidea-space");
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -61,6 +61,20 @@ export interface Reveal {
|
||||
const KEPT_VIEWS = 8;
|
||||
const keptSlots: EditorSlot[] = [];
|
||||
|
||||
/**
|
||||
* Holds the visible tabs' tooltip layers. A layer added to `document.body` itself on every
|
||||
* tab switch would change which element is the body's last child, and Chromium then
|
||||
* restyles the whole workbench (`:last-child` rules); inside this host it restyles nothing else.
|
||||
*/
|
||||
let tooltipHost: HTMLElement | null = null;
|
||||
function tooltipHostElement(): HTMLElement {
|
||||
if (!tooltipHost?.isConnected) {
|
||||
tooltipHost = document.createElement("div");
|
||||
document.body.appendChild(tooltipHost);
|
||||
}
|
||||
return tooltipHost;
|
||||
}
|
||||
|
||||
export class EditorSlot {
|
||||
private stored: EditorState;
|
||||
private historyTarget: WorkspaceHistoryTarget;
|
||||
@@ -70,7 +84,7 @@ export class EditorSlot {
|
||||
/** The view kept, detached from the document, while the tab is hidden. */
|
||||
private kept: EditorView | null = null;
|
||||
/**
|
||||
* The tab's tooltips (hints, hover, completion…). They live outside the view, in `document.body`,
|
||||
* The tab's tooltips (hints, hover, completion…). They live outside the view, under `document.body`,
|
||||
* so they leave the page with the view when the tab is hidden instead of floating over the next tab.
|
||||
*/
|
||||
private readonly tooltipLayer = typeof document === "undefined" ? null : document.createElement("div");
|
||||
@@ -207,7 +221,7 @@ export class EditorSlot {
|
||||
|
||||
mount(parent: HTMLElement): EditorView {
|
||||
if (this.view) return this.view;
|
||||
if (this.tooltipLayer && !this.tooltipLayer.isConnected) document.body.appendChild(this.tooltipLayer);
|
||||
if (this.tooltipLayer && !this.tooltipLayer.isConnected) tooltipHostElement().appendChild(this.tooltipLayer);
|
||||
const kept = this.kept;
|
||||
let view: EditorView;
|
||||
if (kept) {
|
||||
|
||||
@@ -568,7 +568,8 @@ function EditorTabActions({ paneId, tab }: { paneId: string; tab: Tab }) {
|
||||
anchor={moreRef}
|
||||
placement="bottom-end"
|
||||
aria-label="Tab actions"
|
||||
items={ctrl.tabMenu(paneId, tab)}
|
||||
// Built when shown: every tab render (each open and switch) would otherwise assemble the whole menu.
|
||||
items={open ? ctrl.tabMenu(paneId, tab) : []}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -232,8 +232,10 @@
|
||||
.conversationRow[data-measured] {
|
||||
content-visibility: auto;
|
||||
}
|
||||
/* Keep turns distinct and the work within a turn close to its author. */
|
||||
.stream > * + * {
|
||||
/* Keep turns distinct and the work within a turn close to its author. Not `* + *`: a
|
||||
universal adjacent-sibling rule makes Chromium restyle whole sibling subtrees on every
|
||||
DOM insertion anywhere in the window, which costs every editor scroll frame. */
|
||||
.stream > :where(:not(:first-child)) {
|
||||
margin-top: var(--space-4);
|
||||
}
|
||||
.stream > [data-process] + [data-process] {
|
||||
@@ -336,7 +338,7 @@
|
||||
.agentAuthor > .role {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
.agentAuthor + * {
|
||||
:where(.conversationRow[data-author]) > :nth-child(2) {
|
||||
margin-top: calc(var(--space-2) / 2);
|
||||
}
|
||||
.conversationRow > .process,
|
||||
@@ -1067,16 +1069,6 @@
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
|
||||
/* Announced to screen readers, not shown: the fact behind a playful status. */
|
||||
.srOnly {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
overflow: hidden;
|
||||
clip-path: inset(50%);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.retrying {
|
||||
color: var(--warning);
|
||||
}
|
||||
|
||||
@@ -1,73 +0,0 @@
|
||||
.body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.notice {
|
||||
margin: 0;
|
||||
color: var(--fg-muted);
|
||||
font-size: var(--fs-small);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.activity {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.after {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.seconds {
|
||||
width: 64px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.items {
|
||||
flex: 1;
|
||||
min-height: 120px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-1);
|
||||
padding: 8px;
|
||||
overflow: auto;
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--radius-control);
|
||||
}
|
||||
|
||||
.item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-1-5);
|
||||
padding: 4px 8px;
|
||||
background: var(--bg-hover);
|
||||
border-radius: var(--radius-control);
|
||||
}
|
||||
|
||||
.word {
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.empty {
|
||||
color: var(--fg-muted);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
|
||||
.add {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
}
|
||||
|
||||
.input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
@@ -1,147 +0,0 @@
|
||||
/**
|
||||
* Settings › Agents › Working Status: whether the status under a conversation turns playful, after
|
||||
* how long without news, and the playful words of each activity, the built-in ones until the user
|
||||
* writes their own.
|
||||
*/
|
||||
import { useId, useState } from "react";
|
||||
import { useTx } from "@/platform/i18n";
|
||||
import { PLAYFUL_AFTER_LIMITS } from "@/platform/agentStatus";
|
||||
import { Button, Checkbox, IconButton, Input, Select, T, type SelectOption } from "@/ui";
|
||||
import { useSettingsForm } from "@/workbench/contributions";
|
||||
import { AGENT_SETTINGS_DEFAULTS } from "./agentSettings";
|
||||
import { ACTIVITIES, ACTIVITY_STATUS, PLAYFUL_WORDS, type Activity } from "./workingStatus";
|
||||
import styles from "./WorkingStatus.module.css";
|
||||
|
||||
export function WorkingStatusPage() {
|
||||
const tx = useTx();
|
||||
const form = useSettingsForm();
|
||||
const playful =
|
||||
(form.useValue("agents.playfulStatus") as boolean | undefined) ?? AGENT_SETTINGS_DEFAULTS.playfulStatus;
|
||||
const own = (form.useValue("agents.playfulWords") ?? {}) as Record<string, string[]>;
|
||||
const [activity, setActivity] = useState<Activity>("working");
|
||||
const [draft, setDraft] = useState("");
|
||||
const selectId = useId();
|
||||
const custom = own[activity];
|
||||
const words = custom ?? PLAYFUL_WORDS[activity].map((w) => tx(w));
|
||||
|
||||
const options: SelectOption<Activity>[] = ACTIVITIES.map((a) => ({
|
||||
value: a,
|
||||
label: ACTIVITY_STATUS[a],
|
||||
detail: own[a] ? "Custom" : undefined,
|
||||
}));
|
||||
const setWords = (next: string[] | null) => {
|
||||
const others = Object.fromEntries(Object.entries(own).filter(([a]) => a !== activity));
|
||||
form.set("agents.playfulWords", next ? { ...others, [activity]: next } : others);
|
||||
};
|
||||
const add = () => {
|
||||
const word = draft.trim();
|
||||
if (!word) return;
|
||||
setDraft("");
|
||||
if (!words.includes(word)) setWords([...words, word]);
|
||||
};
|
||||
|
||||
return (
|
||||
<section className={styles.body} aria-label={tx("Working Status")}>
|
||||
<p className={styles.notice}>
|
||||
<T>
|
||||
While the agent works, the line under the conversation says what it is doing. With playful words on, words for
|
||||
what it does take turns there instead, from the start or once it reports nothing new for a while; screen
|
||||
readers still hear the plain status.
|
||||
</T>
|
||||
</p>
|
||||
<Checkbox
|
||||
checked={playful}
|
||||
onChange={(on) => form.set("agents.playfulStatus", on)}
|
||||
label="Playful words while the agent works"
|
||||
/>
|
||||
<PlayfulAfter disabled={!playful} />
|
||||
<div className={styles.activity}>
|
||||
<label htmlFor={selectId}>
|
||||
<T>While the status says</T>
|
||||
</label>
|
||||
<Select id={selectId} value={activity} options={options} onChange={setActivity} disabled={!playful} />
|
||||
</div>
|
||||
<div className={styles.items} role="list" aria-label={tx("Playful words")}>
|
||||
{words.length === 0 && (
|
||||
<div className={styles.empty}>
|
||||
<T>No playful words: the status stays factual</T>
|
||||
</div>
|
||||
)}
|
||||
{words.map((word, i) => (
|
||||
<div key={`${i}:${word}`} className={styles.item} role="listitem">
|
||||
<span className={styles.word}>{word}</span>
|
||||
<IconButton
|
||||
icon="close"
|
||||
size="small"
|
||||
title={tx`Remove ${word}`}
|
||||
disabled={!playful}
|
||||
onClick={() => setWords(words.filter((_, j) => j !== i))}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div className={styles.add}>
|
||||
<input
|
||||
type="text"
|
||||
className={styles.input}
|
||||
value={draft}
|
||||
disabled={!playful}
|
||||
onChange={(e) => setDraft(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key !== "Enter") return;
|
||||
// Enter adds the word; it does not press the dialog's OK.
|
||||
e.preventDefault();
|
||||
add();
|
||||
}}
|
||||
placeholder={tx("e.g. Reticulating splines…")}
|
||||
aria-label={tx("New playful word")}
|
||||
/>
|
||||
<Button size="small" disabled={!playful} onClick={add}>
|
||||
Add
|
||||
</Button>
|
||||
<Button size="small" disabled={!playful || !custom} onClick={() => setWords(null)}>
|
||||
Restore Built-in Words
|
||||
</Button>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
/** Seconds without news before the status turns playful; invalid text is flagged and reverted on blur. */
|
||||
function PlayfulAfter({ disabled }: { disabled: boolean }) {
|
||||
const tx = useTx();
|
||||
const form = useSettingsForm();
|
||||
const value =
|
||||
(form.useValue("agents.playfulAfterSeconds") as number | undefined) ?? AGENT_SETTINGS_DEFAULTS.playfulAfterSeconds;
|
||||
const [draft, setDraft] = useState<string | null>(null);
|
||||
const id = useId();
|
||||
const { min, max } = PLAYFUL_AFTER_LIMITS;
|
||||
const parse = (text: string) => {
|
||||
const n = /^\s*\d+\s*$/.test(text) ? Number(text) : NaN;
|
||||
return n >= min && n <= max ? n : null;
|
||||
};
|
||||
const invalid = draft !== null && parse(draft) === null;
|
||||
return (
|
||||
<div className={styles.after}>
|
||||
<label htmlFor={id}>
|
||||
<T>Start after the agent reports nothing new for</T>
|
||||
</label>
|
||||
<Input
|
||||
id={id}
|
||||
className={styles.seconds}
|
||||
inputMode="numeric"
|
||||
value={draft ?? String(value)}
|
||||
invalid={invalid}
|
||||
disabled={disabled}
|
||||
title={invalid ? tx`Enter a value between ${min} and ${max}` : undefined}
|
||||
onChange={(e) => {
|
||||
setDraft(e.target.value);
|
||||
const n = parse(e.target.value);
|
||||
if (n !== null) form.set("agents.playfulAfterSeconds", n);
|
||||
}}
|
||||
onBlur={() => setDraft(null)}
|
||||
/>
|
||||
<T>seconds</T>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -13,9 +13,6 @@ export const AGENT_SETTINGS_DEFAULTS: ResolvedAgentSettings = {
|
||||
foldTurns: true,
|
||||
smoothText: true,
|
||||
fitWindowWidth: false,
|
||||
playfulStatus: false,
|
||||
playfulAfterSeconds: 0,
|
||||
playfulWords: {},
|
||||
thinking: "auto",
|
||||
toolCalls: "grouped",
|
||||
expandToolOutput: false,
|
||||
|
||||
@@ -15,8 +15,6 @@ export const AGENTS_GROUP = "Agents";
|
||||
export const MCP_PAGE = "agents.mcpServers";
|
||||
/** Settings › Agents › Command Permissions. */
|
||||
export const POLICY_PAGE = "agents.policy";
|
||||
/** Settings › Agents › Working Status: the playful words under a working conversation. */
|
||||
export const WORKING_STATUS_PAGE = "agents.workingStatus";
|
||||
|
||||
export const sessionKey = (task: string) => `agent:${task}`;
|
||||
|
||||
|
||||
@@ -29,7 +29,7 @@ function task(id: string, title: string, cwd: string): AgentTask {
|
||||
}
|
||||
|
||||
/** A turn as agents work: a request, reasoning, a run of tool calls, then a reply with code. */
|
||||
function turn(cwd: string, i: number): AgentEntry[] {
|
||||
function turn(cwd: string, i: number, title: string): AgentEntry[] {
|
||||
const file = (k: number) => `${cwd}/src/orders/Order${(i + k) % 40}.kt`;
|
||||
const tools: AgentEntry[] = Array.from({ length: 10 }, (_, k) => {
|
||||
// Tool titles as agents report them (commands and paths, not UI text).
|
||||
@@ -49,7 +49,8 @@ function turn(cwd: string, i: number): AgentEntry[] {
|
||||
};
|
||||
});
|
||||
// What a user and an agent wrote (conversation content, not UI text).
|
||||
const request = `Turn ${i}: make the order service retry failed payments and cover it with tests`;
|
||||
// Ends with the task's title, so each conversation shown can be told apart.
|
||||
const request = `Turn ${i}: make the order service retry failed payments and cover it with tests (${title})`;
|
||||
const reasoning = `The payment client throws on timeouts; retrying belongs in the service (turn ${i}).`;
|
||||
return [
|
||||
{
|
||||
@@ -94,14 +95,14 @@ function turn(cwd: string, i: number): AgentEntry[] {
|
||||
/** Opens `count` tasks of `turns` turns each (14 entries a turn), the last one shown. */
|
||||
export function openSampleConversations(count: number, turns: number) {
|
||||
const cwd = useProject.getState().project?.root ?? "/";
|
||||
const entries = Array.from({ length: turns }, (_, i) => turn(cwd, i)).flat();
|
||||
const s = useAgents.getState();
|
||||
const tasks = new Map(s.tasks);
|
||||
const all = new Map(s.entries);
|
||||
const ids = Array.from({ length: count }, (_, n) => `sample-${n + 1}`);
|
||||
ids.forEach((id, n) => {
|
||||
tasks.set(id, task(id, `Sample task ${n + 1}`, cwd));
|
||||
all.set(id, entries);
|
||||
const title = `Sample task ${n + 1}`;
|
||||
tasks.set(id, task(id, title, cwd));
|
||||
all.set(id, Array.from({ length: turns }, (_, i) => turn(cwd, i, title)).flat());
|
||||
});
|
||||
useAgents.setState({ tasks, entries: all });
|
||||
for (const id of ids) openTask(id);
|
||||
|
||||
@@ -559,6 +559,7 @@ export function Stream({
|
||||
(row.kind === "entry" && (row.entry.type === "user" || row.entry.type === "agent")) || undefined
|
||||
}
|
||||
data-process={row.kind !== "entry" || row.entry.type !== "user" || undefined}
|
||||
data-author={authorHeaders.has(row.index) || undefined}
|
||||
>
|
||||
{authorHeaders.has(row.index) && (
|
||||
<div className={styles.agentAuthor}>
|
||||
|
||||
@@ -1,23 +1,12 @@
|
||||
import type { AgentEntry, AgentRetry, AgentTask } from "@/bindings";
|
||||
import { useTx } from "@/platform/i18n";
|
||||
import { Spinner, T } from "@/ui";
|
||||
import { useState } from "react";
|
||||
import styles from "../Session.module.css";
|
||||
import { useAgentSettings } from "../agentSettings";
|
||||
import { retryParts } from "../composerModel";
|
||||
import { formatDuration } from "../conversation";
|
||||
import { subagentWorking, type SubagentEntry } from "../model";
|
||||
import { asksInCard } from "../permission";
|
||||
import {
|
||||
ACTIVITY_STATUS,
|
||||
activityOf,
|
||||
PLAYFUL_MIN_MS,
|
||||
PLAYFUL_WORD_MS,
|
||||
PLAYFUL_WORDS,
|
||||
playfulIndex,
|
||||
progressKey,
|
||||
type Activity,
|
||||
} from "../workingStatus";
|
||||
import { ACTIVITY_STATUS, activityOf } from "../workingStatus";
|
||||
import { useNow, type UserEntry } from "./shared";
|
||||
|
||||
/** The agent lost its API connection (or was refused) and retries on its own. */
|
||||
@@ -57,11 +46,7 @@ export function WorkingRow({
|
||||
return (
|
||||
<div className={styles.working} role="status">
|
||||
<Spinner size={12} />
|
||||
{subagent.status === "needsInput" ? (
|
||||
<T>Waiting for your answer…</T>
|
||||
) : (
|
||||
<WorkingLabel turn={entries ?? []} seed={subagent.startedMs ?? 0} />
|
||||
)}
|
||||
{subagent.status === "needsInput" ? <T>Waiting for your answer…</T> : <WorkingLabel turn={entries ?? []} />}
|
||||
{subagent.startedMs != null && <Elapsed since={subagent.startedMs} />}
|
||||
</div>
|
||||
);
|
||||
@@ -78,56 +63,15 @@ export function WorkingRow({
|
||||
) : task.status === "starting" ? (
|
||||
<T>Starting the agent…</T>
|
||||
) : (
|
||||
<WorkingLabel turn={entries?.slice(userAt + 1) ?? []} seed={lastUser?.sentMs ?? 0} />
|
||||
<WorkingLabel turn={entries?.slice(userAt + 1) ?? []} />
|
||||
)}
|
||||
{lastUser?.sentMs != null && !lastUser.doneMs && <Elapsed since={lastUser.sentMs} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* What the agent is doing, said by the activity's playful words in turns (the user's own, else the
|
||||
* built-in ones) from the start, or once it has reported nothing new for the user's quiet time;
|
||||
* screen readers hear only the fact. A word stays its full time while it still fits what the agent
|
||||
* does, and a little while when it no longer does, so the row never flickers.
|
||||
*/
|
||||
function WorkingLabel({ turn, seed }: { turn: AgentEntry[]; seed: number }) {
|
||||
/** What the agent is doing, from the turn's latest output. */
|
||||
function WorkingLabel({ turn }: { turn: AgentEntry[] }) {
|
||||
const tx = useTx();
|
||||
const { playfulStatus, playfulAfterSeconds, playfulWords } = useAgentSettings();
|
||||
const now = useNow(1000);
|
||||
const key = progressKey(turn);
|
||||
const [progress, setProgress] = useState({ key, at: now });
|
||||
if (progress.key !== key) setProgress({ key, at: now });
|
||||
// The word on screen, and how many the turn has shown, so the next one continues the order.
|
||||
const [playful, setPlayful] = useState<{ shown: number; word: PlayfulWord | null }>({ shown: 0, word: null });
|
||||
const activity = activityOf(turn);
|
||||
const kind = activity ?? "working";
|
||||
const fact = tx(ACTIVITY_STATUS[kind]);
|
||||
const own = playfulWords[kind];
|
||||
const words = own ?? PLAYFUL_WORDS[kind];
|
||||
const due = words.length > 0 && (!activity || now - progress.at >= playfulAfterSeconds * 1000);
|
||||
const current = playful.word;
|
||||
const fits = due && current?.kind === kind;
|
||||
const stays = current && playfulStatus && now - current.since < (fits ? PLAYFUL_WORD_MS : PLAYFUL_MIN_MS);
|
||||
let next = playful;
|
||||
if (!stays && playfulStatus && due) {
|
||||
const text = words[playfulIndex(words.length, seed, playful.shown)]!;
|
||||
next = { shown: playful.shown + 1, word: { text, kind, own: !!own, since: now } };
|
||||
} else if (!stays && current) next = { shown: playful.shown, word: null };
|
||||
if (next !== playful) setPlayful(next);
|
||||
if (!next.word) return fact;
|
||||
return (
|
||||
<>
|
||||
<span aria-hidden>{next.word.own ? next.word.text : tx(next.word.text)}</span>
|
||||
<span className={styles.srOnly}>{fact}</span>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** A playful word for `kind` on screen since `since`: the user's own as written, else a built-in one to translate. */
|
||||
interface PlayfulWord {
|
||||
text: string;
|
||||
kind: Activity;
|
||||
own: boolean;
|
||||
since: number;
|
||||
return tx(ACTIVITY_STATUS[activityOf(turn) ?? "working"]);
|
||||
}
|
||||
@@ -24,7 +24,6 @@ import { useChangesOptions } from "./changesOptions";
|
||||
import { taskActions } from "./taskActions";
|
||||
import { replyActions } from "./replyActions";
|
||||
import { focusedSession } from "./sessionFocus";
|
||||
import { PLAYFUL_MIN_MS, PLAYFUL_WORD_MS, PLAYFUL_WORDS } from "./workingStatus";
|
||||
import styles from "./Session.module.css";
|
||||
import chipStyles from "./ReferenceChip.module.css";
|
||||
import { caretOf, textOf, typeIn } from "./composerTesting";
|
||||
@@ -517,108 +516,18 @@ describe("working status", () => {
|
||||
}),
|
||||
});
|
||||
};
|
||||
const playful = (status: HTMLElement) => status.querySelector("[aria-hidden]")?.textContent ?? null;
|
||||
const playfulOn = (agents: object = {}) =>
|
||||
useProject.setState({ settings: { agents: { playfulStatus: true, ...agents } } as never });
|
||||
|
||||
it("says plainly what the agent does by default", async () => {
|
||||
vi.useFakeTimers();
|
||||
running([tool("one", { status: "running" })]);
|
||||
render(<SessionEditor input={input("A")} />);
|
||||
await act(async () => {});
|
||||
await act(() => vi.advanceTimersByTimeAsync(PLAYFUL_WORD_MS * 2));
|
||||
const status = stream().querySelector<HTMLElement>(`.${styles.working}`)!;
|
||||
expect(playful(status)).toBeNull();
|
||||
expect(status).toHaveTextContent("Reading…");
|
||||
});
|
||||
|
||||
it("is playful from the start, holds each word while the work goes on, and turns to the new work's words", async () => {
|
||||
vi.useFakeTimers();
|
||||
playfulOn();
|
||||
running([tool("one", { status: "running" })]);
|
||||
render(<SessionEditor input={input("A")} />);
|
||||
await act(async () => {});
|
||||
const status = stream().querySelector<HTMLElement>(`.${styles.working}`)!;
|
||||
const word = playful(status);
|
||||
expect(PLAYFUL_WORDS.reading).toContain(word);
|
||||
// Screen readers still hear the fact.
|
||||
expect(status.querySelector(`.${styles.srOnly}`)).toHaveTextContent("Reading…");
|
||||
|
||||
// More of the same work keeps the word its full time.
|
||||
running([tool("one", { status: "running" }), tool("two", { status: "running" })]);
|
||||
await act(() => vi.advanceTimersByTimeAsync(PLAYFUL_WORD_MS - 1000));
|
||||
expect(playful(status)).toBe(word);
|
||||
await act(() => vi.advanceTimersByTimeAsync(1000));
|
||||
const second = playful(status);
|
||||
expect(PLAYFUL_WORDS.reading.filter((w) => w !== word)).toContain(second);
|
||||
|
||||
// New work leaves the word a moment, then says the new work playfully too.
|
||||
running([tool("one", { status: "running" }), { type: "agent", text: "Found it" }]);
|
||||
await act(() => vi.advanceTimersByTimeAsync(1000));
|
||||
expect(playful(status)).toBe(second);
|
||||
await act(() => vi.advanceTimersByTimeAsync(PLAYFUL_MIN_MS - 1000));
|
||||
expect(PLAYFUL_WORDS.writing).toContain(playful(status));
|
||||
expect(status.querySelector(`.${styles.srOnly}`)).toHaveTextContent("Writing…");
|
||||
});
|
||||
|
||||
it("with a quiet time, is factual until the agent reports nothing new for it, and again on progress", async () => {
|
||||
vi.useFakeTimers();
|
||||
playfulOn({ playfulAfterSeconds: 10 });
|
||||
it("says what the agent does", async () => {
|
||||
running([tool("one", { status: "running" })]);
|
||||
render(<SessionEditor input={input("A")} />);
|
||||
await act(async () => {});
|
||||
const status = stream().querySelector<HTMLElement>(`.${styles.working}`)!;
|
||||
expect(status).toHaveTextContent("Reading…");
|
||||
expect(playful(status)).toBeNull();
|
||||
|
||||
await act(() => vi.advanceTimersByTimeAsync(9000));
|
||||
expect(playful(status)).toBeNull();
|
||||
await act(() => vi.advanceTimersByTimeAsync(1000));
|
||||
const word = playful(status);
|
||||
expect(PLAYFUL_WORDS.reading).toContain(word);
|
||||
|
||||
// Progress right after a word appeared leaves it a moment before the fact returns.
|
||||
running([tool("one", { status: "running" }), { type: "agent", text: "Found it" }]);
|
||||
await act(() => vi.advanceTimersByTimeAsync(1000));
|
||||
expect(playful(status)).toBe(word);
|
||||
await act(() => vi.advanceTimersByTimeAsync(PLAYFUL_MIN_MS - 1000));
|
||||
expect(playful(status)).toBeNull();
|
||||
await act(async () => {});
|
||||
expect(status).toHaveTextContent("Writing…");
|
||||
});
|
||||
|
||||
it("keeps each word its full time however soon the status turns playful", async () => {
|
||||
vi.useFakeTimers();
|
||||
playfulOn({ playfulAfterSeconds: 1 });
|
||||
running([tool("one", { status: "running" })]);
|
||||
render(<SessionEditor input={input("A")} />);
|
||||
await act(async () => {});
|
||||
const status = stream().querySelector<HTMLElement>(`.${styles.working}`)!;
|
||||
await act(() => vi.advanceTimersByTimeAsync(1000));
|
||||
const word = playful(status);
|
||||
expect(PLAYFUL_WORDS.reading).toContain(word);
|
||||
await act(() => vi.advanceTimersByTimeAsync(PLAYFUL_WORD_MS - 1000));
|
||||
expect(playful(status)).toBe(word);
|
||||
await act(() => vi.advanceTimersByTimeAsync(1000));
|
||||
expect(PLAYFUL_WORDS.reading.filter((w) => w !== word)).toContain(playful(status));
|
||||
});
|
||||
|
||||
it("shows the user's own words of the activity, and none where they left the list empty", async () => {
|
||||
vi.useFakeTimers();
|
||||
playfulOn({ playfulWords: { reading: ["Squinting really hard…"], working: [] } });
|
||||
running([]);
|
||||
render(<SessionEditor input={input("A")} />);
|
||||
await act(async () => {});
|
||||
const status = stream().querySelector<HTMLElement>(`.${styles.working}`)!;
|
||||
// Nothing reported yet is `working`, whose list the user emptied.
|
||||
expect(playful(status)).toBeNull();
|
||||
expect(status).toHaveTextContent("Working…");
|
||||
|
||||
running([tool("one", { status: "running" })]);
|
||||
await act(() => vi.advanceTimersByTimeAsync(1000));
|
||||
expect(playful(status)).toBe("Squinting really hard…");
|
||||
await act(() => vi.advanceTimersByTimeAsync(PLAYFUL_WORD_MS));
|
||||
expect(playful(status)).toBe("Squinting really hard…");
|
||||
});
|
||||
});
|
||||
|
||||
describe("opened runs", () => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { lazyComponent } from "@/ui";
|
||||
import { registerSettingsPages } from "@/workbench/contributions";
|
||||
import { AGENTS_GROUP, MCP_PAGE, POLICY_PAGE, REGISTRY_PAGE, WORKING_STATUS_PAGE } from "./model";
|
||||
import { AGENTS_GROUP, MCP_PAGE, POLICY_PAGE, REGISTRY_PAGE } from "./model";
|
||||
|
||||
/** Settings › Agents › Coding Agents and Settings › Agents › External MCP Servers (also used by the Settings window). */
|
||||
export function activateSettingsPages(): () => void {
|
||||
@@ -14,15 +14,6 @@ export function activateSettingsPages(): () => void {
|
||||
keywords: ["agent", "acp", "registry", "install", "update", "coding agent"],
|
||||
component: lazyComponent(() => import("./AgentRegistryPage").then((m) => m.AgentRegistryPage)),
|
||||
},
|
||||
{
|
||||
id: WORKING_STATUS_PAGE,
|
||||
title: "Working Status",
|
||||
group: AGENTS_GROUP,
|
||||
// After Chat.
|
||||
order: 465,
|
||||
keywords: ["agent", "status", "playful", "words", "working", "spinner", "fun", "delay", "seconds"],
|
||||
component: lazyComponent(() => import("./WorkingStatusPage").then((m) => m.WorkingStatusPage)),
|
||||
},
|
||||
{
|
||||
id: MCP_PAGE,
|
||||
title: "External MCP Servers",
|
||||
|
||||
@@ -1,32 +1,22 @@
|
||||
/**
|
||||
* The label of the row under a conversation while the agent works: what the turn's latest
|
||||
* output says it is doing, and playful words while it reports nothing new (or nothing yet).
|
||||
*/
|
||||
/** The label of the row under a conversation while the agent works: what the turn's latest output says it is doing. */
|
||||
import type { AgentEntry } from "@/bindings";
|
||||
import { subagentWorking } from "./model";
|
||||
|
||||
/** How long one playful word stays while the agent still reports nothing new. */
|
||||
export const PLAYFUL_WORD_MS = 8_000;
|
||||
/** How long a playful word stays at least, even when the agent reports something new meanwhile. */
|
||||
export const PLAYFUL_MIN_MS = 3_000;
|
||||
|
||||
/** What the agent can be doing, as the status tells it; `working` covers the rest. */
|
||||
export const ACTIVITIES = [
|
||||
"working",
|
||||
"thinking",
|
||||
"writing",
|
||||
"reading",
|
||||
"editing",
|
||||
"deleting",
|
||||
"moving",
|
||||
"searching",
|
||||
"running",
|
||||
"fetching",
|
||||
"subagent",
|
||||
] as const;
|
||||
export type Activity = (typeof ACTIVITIES)[number];
|
||||
type Activity =
|
||||
| "working"
|
||||
| "thinking"
|
||||
| "writing"
|
||||
| "reading"
|
||||
| "editing"
|
||||
| "deleting"
|
||||
| "moving"
|
||||
| "searching"
|
||||
| "running"
|
||||
| "fetching"
|
||||
| "subagent";
|
||||
|
||||
/** The factual status of each activity, also what screen readers hear while it is playful. */
|
||||
/** The status of each activity. */
|
||||
export const ACTIVITY_STATUS: Record<Activity, string> = {
|
||||
working: "Working…",
|
||||
thinking: "Thinking…",
|
||||
@@ -41,59 +31,6 @@ export const ACTIVITY_STATUS: Record<Activity, string> = {
|
||||
subagent: "Running a subagent…",
|
||||
};
|
||||
|
||||
/** The built-in playful words of each activity, until the user writes their own. */
|
||||
export const PLAYFUL_WORDS: Record<Activity, readonly string[]> = {
|
||||
working: [
|
||||
"Untangling imports…",
|
||||
"Explaining it to the rubber duck…",
|
||||
"Herding semicolons…",
|
||||
"Rebasing onto reality…",
|
||||
"Measuring twice…",
|
||||
"Sharpening the pencils…",
|
||||
"Invalidating a cache…",
|
||||
],
|
||||
thinking: [
|
||||
"Refactoring a hunch…",
|
||||
"Garbage-collecting thoughts…",
|
||||
"Compiling a plan…",
|
||||
"Caching an insight…",
|
||||
"Bisecting the problem…",
|
||||
"Naming things…",
|
||||
],
|
||||
writing: [
|
||||
"Counting brackets…",
|
||||
"Settling tabs versus spaces…",
|
||||
"Choosing words carefully…",
|
||||
"Polishing the prose…",
|
||||
"Drafting, redrafting…",
|
||||
],
|
||||
reading: [
|
||||
"Reading the fine manual…",
|
||||
"Following the breadcrumbs…",
|
||||
"Walking the call stack…",
|
||||
"Reading between the lines…",
|
||||
"Skimming the source…",
|
||||
],
|
||||
editing: [
|
||||
"Squinting at the diff…",
|
||||
"Negotiating with the borrow checker…",
|
||||
"Asking the linter nicely…",
|
||||
"Nudging a semicolon…",
|
||||
"Moving code around gently…",
|
||||
],
|
||||
deleting: ["Tidying up…", "Taking out the trash…", "Pruning dead code…", "Saying goodbye…"],
|
||||
moving: ["Rearranging the furniture…", "Packing boxes…", "Finding a better home…"],
|
||||
searching: ["Grepping the void…", "Chasing a null pointer…", "Looking under the couch…", "Searching high and low…"],
|
||||
running: [
|
||||
"Warming up the compiler…",
|
||||
"Pressing Enter with confidence…",
|
||||
"Watching the logs scroll…",
|
||||
"Waiting on the shell…",
|
||||
],
|
||||
fetching: ["Waiting on the network…", "Downloading the internet…", "Following links…"],
|
||||
subagent: ["Delegating…", "Consulting a colleague…", "Calling in reinforcements…", "Holding a quick stand-up…"],
|
||||
};
|
||||
|
||||
const TOOL_ACTIVITY: Record<string, Activity> = {
|
||||
read: "reading",
|
||||
edit: "editing",
|
||||
@@ -124,35 +61,3 @@ export function activityOf(turn: readonly AgentEntry[]): Activity | null {
|
||||
return "working";
|
||||
}
|
||||
}
|
||||
|
||||
/** Changes whenever the agent reports something new in the turn: an entry, more text, a tool's progress. */
|
||||
export function progressKey(turn: readonly AgentEntry[]): string {
|
||||
const last = turn.at(-1);
|
||||
const detail =
|
||||
last?.type === "agent" || last?.type === "thought"
|
||||
? last.text.length
|
||||
: last?.type === "tool"
|
||||
? `${last.status}:${last.output?.length ?? 0}`
|
||||
: last?.type === "subagent"
|
||||
? last.status
|
||||
: "";
|
||||
return `${turn.length}:${last?.type ?? ""}:${detail}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Which of `count` playful words is the `n`th to show in the turn that started at `seed`. Each turn
|
||||
* goes through every word in an order of its own.
|
||||
*/
|
||||
export function playfulIndex(count: number, seed: number, n: number): number {
|
||||
const order = Array.from({ length: count }, (_, i) => i);
|
||||
let state = seed >>> 0;
|
||||
for (let i = order.length - 1; i > 0; i--) {
|
||||
// mulberry32
|
||||
state = (state + 0x6d2b79f5) >>> 0;
|
||||
let r = Math.imul(state ^ (state >>> 15), state | 1);
|
||||
r ^= r + Math.imul(r ^ (r >>> 7), r | 61);
|
||||
const j = ((r ^ (r >>> 14)) >>> 0) % (i + 1);
|
||||
[order[i], order[j]] = [order[j]!, order[i]!];
|
||||
}
|
||||
return order[n % count]!;
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { fireEvent, render, screen, within } from "@testing-library/react";
|
||||
import { SettingsFormContext } from "@/workbench/contributions";
|
||||
import { useSettingsFormFor } from "@/features/settings/components/context";
|
||||
import { closeSettings, openSettings, stagedValue, useSettingsDialog } from "@/features/settings/model/staging";
|
||||
import { WORKING_STATUS_PAGE } from "./model";
|
||||
import { WorkingStatusPage as Page } from "./WorkingStatusPage";
|
||||
import { PLAYFUL_WORDS } from "./workingStatus";
|
||||
|
||||
function WorkingStatusPage() {
|
||||
const form = useSettingsFormFor(WORKING_STATUS_PAGE, "global");
|
||||
return (
|
||||
<SettingsFormContext.Provider value={form}>
|
||||
<Page />
|
||||
</SettingsFormContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
const staged = () => stagedValue(useSettingsDialog.getState(), "global", "agents.playfulWords");
|
||||
const words = () =>
|
||||
within(screen.getByRole("list", { name: "Playful words" }))
|
||||
.queryAllByRole("listitem")
|
||||
.map((item) => item.textContent);
|
||||
/** The page with playful words turned on, so its word controls are enabled. */
|
||||
function renderOn() {
|
||||
render(<WorkingStatusPage />);
|
||||
fireEvent.click(screen.getByRole("checkbox", { name: "Playful words while the agent works" }));
|
||||
}
|
||||
|
||||
describe("Working Status settings", () => {
|
||||
beforeEach(() => openSettings(WORKING_STATUS_PAGE));
|
||||
afterEach(() => closeSettings());
|
||||
|
||||
it("is off by default, and turning it on enables the words", () => {
|
||||
render(<WorkingStatusPage />);
|
||||
const toggle = screen.getByRole("checkbox", { name: "Playful words while the agent works" });
|
||||
expect(toggle).not.toBeChecked();
|
||||
expect(screen.getByRole("textbox", { name: "New playful word" })).toBeDisabled();
|
||||
fireEvent.click(toggle);
|
||||
expect(stagedValue(useSettingsDialog.getState(), "global", "agents.playfulStatus")).toBe(true);
|
||||
expect(screen.getByRole("textbox", { name: "New playful word" })).toBeEnabled();
|
||||
});
|
||||
|
||||
it("turns the built-in words into the user's own on the first edit, and restores them", () => {
|
||||
renderOn();
|
||||
const builtIn = [...PLAYFUL_WORDS.working];
|
||||
expect(words()).toEqual(builtIn);
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: `Remove ${builtIn[0]}` }));
|
||||
const input = screen.getByRole("textbox", { name: "New playful word" });
|
||||
fireEvent.change(input, { target: { value: " Reticulating splines… " } });
|
||||
// Enter adds the word and is not left to press the Settings dialog's OK.
|
||||
expect(fireEvent.keyDown(input, { key: "Enter" })).toBe(false);
|
||||
const own = [...builtIn.slice(1), "Reticulating splines…"];
|
||||
expect(words()).toEqual(own);
|
||||
expect(staged()).toEqual({ working: own });
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Restore Built-in Words" }));
|
||||
expect(staged()).toEqual({});
|
||||
expect(words()).toEqual(builtIn);
|
||||
});
|
||||
|
||||
it("keeps an emptied list, which leaves the status factual", () => {
|
||||
renderOn();
|
||||
for (const word of PLAYFUL_WORDS.working) fireEvent.click(screen.getByRole("button", { name: `Remove ${word}` }));
|
||||
expect(staged()).toEqual({ working: [] });
|
||||
expect(screen.getByText("No playful words: the status stays factual")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("saves the quiet time while the text is a valid number, and drops invalid text on blur", () => {
|
||||
renderOn();
|
||||
const after = () => stagedValue(useSettingsDialog.getState(), "global", "agents.playfulAfterSeconds");
|
||||
const seconds = screen.getByRole("textbox", { name: "Start after the agent reports nothing new for" });
|
||||
expect(seconds).toHaveValue("0");
|
||||
fireEvent.change(seconds, { target: { value: "25" } });
|
||||
expect(after()).toBe(25);
|
||||
fireEvent.change(seconds, { target: { value: "601" } });
|
||||
expect(seconds).toHaveAttribute("aria-invalid", "true");
|
||||
expect(after()).toBe(25);
|
||||
fireEvent.blur(seconds);
|
||||
expect(seconds).toHaveValue("25");
|
||||
});
|
||||
});
|
||||
@@ -10,18 +10,18 @@
|
||||
background: none;
|
||||
}
|
||||
.toolbar {
|
||||
height: 32px;
|
||||
min-height: var(--h-header);
|
||||
flex: none;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: var(--space-0-5) var(--space-2);
|
||||
padding: var(--space-0-5) var(--space-1-5);
|
||||
}
|
||||
.toolbarGroup {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-0-5);
|
||||
padding: 0 6px;
|
||||
}
|
||||
.sep {
|
||||
width: 1px;
|
||||
height: 16px;
|
||||
margin: 0 4px;
|
||||
background: var(--border);
|
||||
}
|
||||
.note {
|
||||
flex: none;
|
||||
@@ -29,6 +29,7 @@
|
||||
font-size: var(--fs-small);
|
||||
font-style: italic;
|
||||
color: var(--fg-subtle);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.body {
|
||||
flex: 1;
|
||||
@@ -49,17 +50,12 @@
|
||||
white-space: nowrap;
|
||||
}
|
||||
.name {
|
||||
color: var(--fg);
|
||||
}
|
||||
.detail {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
color: var(--fg-subtle);
|
||||
color: var(--fg-strong);
|
||||
}
|
||||
.muted {
|
||||
flex: none;
|
||||
color: var(--fg-subtle);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
.error {
|
||||
flex: none;
|
||||
|
||||
@@ -106,35 +106,37 @@ function HierarchyToolbar() {
|
||||
const autoscroll = useHierarchyOptions((s) => s.autoscroll);
|
||||
return (
|
||||
<div className={styles.toolbar} role="toolbar" aria-label={tx("Hierarchy actions")}>
|
||||
<IconButton
|
||||
icon="arrow-up"
|
||||
size="small"
|
||||
iconSize={16}
|
||||
title={tx`${directionLabel(mode, "incoming")} Hierarchy`}
|
||||
pressed={direction === "incoming"}
|
||||
onClick={() => setDirection("incoming")}
|
||||
/>
|
||||
<IconButton
|
||||
icon="arrow-down"
|
||||
size="small"
|
||||
iconSize={16}
|
||||
title={tx`${directionLabel(mode, "outgoing")} Hierarchy`}
|
||||
pressed={direction === "outgoing"}
|
||||
onClick={() => setDirection("outgoing")}
|
||||
/>
|
||||
<span className={styles.sep} />
|
||||
<div className={styles.toolbarGroup}>
|
||||
<IconButton
|
||||
icon="arrow-up"
|
||||
size="small"
|
||||
iconSize={16}
|
||||
title={tx`${directionLabel(mode, "incoming")} Hierarchy`}
|
||||
pressed={direction === "incoming"}
|
||||
onClick={() => setDirection("incoming")}
|
||||
/>
|
||||
<IconButton
|
||||
icon="arrow-down"
|
||||
size="small"
|
||||
iconSize={16}
|
||||
title={tx`${directionLabel(mode, "outgoing")} Hierarchy`}
|
||||
pressed={direction === "outgoing"}
|
||||
onClick={() => setDirection("outgoing")}
|
||||
/>
|
||||
</div>
|
||||
<IconButton icon="refresh" size="small" iconSize={16} title="Refresh" onClick={refreshHierarchy} />
|
||||
<span className={styles.sep} />
|
||||
<IconButton icon="arrow-up" action="navigate.prevOccurrence" size="small" iconSize={16} />
|
||||
<IconButton icon="arrow-down" action="navigate.nextOccurrence" size="small" iconSize={16} />
|
||||
<IconButton
|
||||
icon="autoscroll-to-source"
|
||||
size="small"
|
||||
iconSize={16}
|
||||
title="Autoscroll to Source"
|
||||
pressed={autoscroll}
|
||||
onClick={() => useHierarchyOptions.setState({ autoscroll: !autoscroll })}
|
||||
/>
|
||||
<div className={styles.toolbarGroup}>
|
||||
<IconButton icon="arrow-up" action="navigate.prevOccurrence" size="small" iconSize={16} />
|
||||
<IconButton icon="arrow-down" action="navigate.nextOccurrence" size="small" iconSize={16} />
|
||||
<IconButton
|
||||
icon="autoscroll-to-source"
|
||||
size="small"
|
||||
iconSize={16}
|
||||
title="Autoscroll to Source"
|
||||
pressed={autoscroll}
|
||||
onClick={() => useHierarchyOptions.setState({ autoscroll: !autoscroll })}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -183,13 +185,9 @@ export function HierarchyView() {
|
||||
const renderNode = (n: Node, _state: TreeRowState) => {
|
||||
if (n.kind === "root") {
|
||||
return (
|
||||
<span className={styles.row}>
|
||||
<span className={styles.row} title={`${root.name}\n${relativePath(projectRoot, root.path)}:${root.line + 1}`}>
|
||||
<SymbolBadge kind={mode === "call" ? "function" : "class"} />
|
||||
<span className={styles.name}>{root.name}</span>
|
||||
{root.detail && <span className={styles.detail}>{root.detail}</span>}
|
||||
<span className={styles.muted}>
|
||||
{basename(root.path)}:{root.line + 1}
|
||||
</span>
|
||||
{loading && <Spinner size={12} />}
|
||||
{failed.has(ROOT_ID) && (
|
||||
<span className={styles.error}>
|
||||
@@ -199,35 +197,42 @@ export function HierarchyView() {
|
||||
{!loading && !failed.has(ROOT_ID) && children.get(ROOT_ID)?.length === 0 && (
|
||||
<span className={styles.muted}>{noneFoundLabel(mode, direction)}</span>
|
||||
)}
|
||||
{root.detail && <span className={styles.muted}>{root.detail}</span>}
|
||||
<span className={styles.muted}>
|
||||
{basename(root.path)}:{root.line + 1}
|
||||
</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
const { item } = n.node;
|
||||
const calls = item.fromRanges.length;
|
||||
return (
|
||||
<span className={styles.row} title={relativePath(projectRoot, item.path)}>
|
||||
<span
|
||||
className={styles.row}
|
||||
title={`${item.name}\n${relativePath(projectRoot, item.path)}:${item.selectionRange.start.line + 1}`}
|
||||
>
|
||||
<SymbolBadge kind={badgeKind(item.kind)} />
|
||||
<span className={styles.name}>{item.name}</span>
|
||||
{item.detail && <span className={styles.detail}>{item.detail}</span>}
|
||||
<span className={styles.muted}>
|
||||
{basename(item.path)}:{item.selectionRange.start.line + 1}
|
||||
</span>
|
||||
{calls > 1 && <span className={styles.muted}>{tx`(${calls} calls)`}</span>}
|
||||
{n.node.recursion && (
|
||||
<span className={styles.muted}>
|
||||
<T>recursive</T>
|
||||
</span>
|
||||
)}
|
||||
{notes.has(n.id) && (
|
||||
<span className={styles.muted} title={notes.get(n.id)}>
|
||||
{notes.get(n.id)}
|
||||
</span>
|
||||
)}
|
||||
{failed.has(n.id) && (
|
||||
<span className={styles.error}>
|
||||
<T>failed to load</T>
|
||||
</span>
|
||||
)}
|
||||
{item.detail && <span className={styles.muted}>{item.detail}</span>}
|
||||
<span className={styles.muted}>
|
||||
{basename(item.path)}:{item.selectionRange.start.line + 1}
|
||||
</span>
|
||||
{notes.has(n.id) && (
|
||||
<span className={styles.muted} title={notes.get(n.id)}>
|
||||
{notes.get(n.id)}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
};
|
||||
@@ -244,6 +249,7 @@ export function HierarchyView() {
|
||||
<Tree<Node>
|
||||
key={generation}
|
||||
aria-label={mode === "call" ? "Call hierarchy" : "Type hierarchy"}
|
||||
horizontalScroll
|
||||
roots={roots}
|
||||
getKey={(n) => n.id}
|
||||
getLabel={(n) => (n.kind === "root" ? root.name : n.node.item.name)}
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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}`;
|
||||
|
||||
@@ -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) });
|
||||
|
||||
@@ -37,7 +37,7 @@
|
||||
flex: none;
|
||||
align-items: center;
|
||||
}
|
||||
.stack > * + * {
|
||||
.stack > :where(:not(:first-child)) {
|
||||
margin-left: calc(var(--overlap) * -1);
|
||||
}
|
||||
.stack > .ringed + .ringed {
|
||||
|
||||
@@ -3,23 +3,21 @@
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
height: 100%;
|
||||
min-height: 420px;
|
||||
min-height: 0;
|
||||
}
|
||||
.topBar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: var(--space-1-5);
|
||||
min-width: 0;
|
||||
}
|
||||
.side {
|
||||
display: flex;
|
||||
.page > .topBar {
|
||||
flex: none;
|
||||
flex-direction: column;
|
||||
width: clamp(320px, 42%, 480px);
|
||||
min-height: 0;
|
||||
border-right: 1px solid var(--border);
|
||||
padding: 0 var(--space-2) var(--space-1);
|
||||
}
|
||||
.sourceTabs {
|
||||
flex: none;
|
||||
border-bottom: 0;
|
||||
}
|
||||
.tabCount {
|
||||
@@ -37,13 +35,14 @@
|
||||
.searchRow {
|
||||
display: flex;
|
||||
flex: none;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
padding: 8px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.searchField {
|
||||
flex: 1;
|
||||
flex: 1 1 132px;
|
||||
min-width: 0;
|
||||
}
|
||||
.spacer {
|
||||
@@ -58,8 +57,6 @@
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.body {
|
||||
display: flex;
|
||||
min-width: 640px;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
border-top: 1px solid var(--border);
|
||||
@@ -237,11 +234,14 @@
|
||||
.details {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
padding: 16px 20px 20px;
|
||||
min-height: 0;
|
||||
padding: var(--space-4);
|
||||
overflow: auto;
|
||||
}
|
||||
.detailsEmpty {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow: auto;
|
||||
}
|
||||
/* Tags, name, vendor, then the actions with the version. */
|
||||
.header {
|
||||
@@ -258,6 +258,7 @@
|
||||
color: var(--fg);
|
||||
font: inherit;
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.titleLine {
|
||||
display: flex;
|
||||
@@ -273,15 +274,19 @@
|
||||
.title {
|
||||
margin: 0;
|
||||
color: var(--fg-strong);
|
||||
font-size: var(--fs-input-large);
|
||||
font-size: 1.375em;
|
||||
font-weight: 600;
|
||||
line-height: 1.3;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.version {
|
||||
color: var(--fg-muted);
|
||||
font-size: var(--fs-small);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.authors {
|
||||
color: var(--fg-secondary);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.headerActions {
|
||||
display: flex;
|
||||
@@ -298,6 +303,7 @@
|
||||
margin: 10px 0 0;
|
||||
max-width: 640px;
|
||||
color: var(--fg);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.details .error {
|
||||
margin-top: 10px;
|
||||
@@ -434,6 +440,7 @@
|
||||
|
||||
.consentNotice {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: var(--space-3);
|
||||
justify-content: space-between;
|
||||
@@ -444,8 +451,7 @@
|
||||
}
|
||||
|
||||
.categorySelect {
|
||||
flex: none;
|
||||
width: 150px;
|
||||
flex: 0 1 150px;
|
||||
}
|
||||
.ownIcon {
|
||||
background: transparent;
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
* There is no network repository: Available lists the plugin packages
|
||||
* available locally (`plugin_catalog`) and installs them from disk.
|
||||
*/
|
||||
import { useEffect, useMemo, useState, type MouseEvent, type ReactNode } from "react";
|
||||
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type MouseEvent, type ReactNode } from "react";
|
||||
import clsx from "clsx";
|
||||
import type {
|
||||
CapabilityInfo,
|
||||
@@ -27,6 +27,9 @@ import {
|
||||
SearchField,
|
||||
Select,
|
||||
Spinner,
|
||||
SplitGroup,
|
||||
SplitHandle,
|
||||
SplitPanel,
|
||||
Tabs,
|
||||
showContextMenu,
|
||||
type MenuItem,
|
||||
@@ -1309,6 +1312,19 @@ export function PluginsPage({ initialTab = "marketplace" }: { initialTab?: Tab }
|
||||
const [query, setQuery] = useState("");
|
||||
const [selectedId, setSelectedId] = useState<string | null>(null);
|
||||
const [selectedCatalogId, setSelectedCatalogId] = useState<string | null>(null);
|
||||
const pageRef = useRef<HTMLDivElement>(null);
|
||||
const [stacked, setStacked] = useState(false);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const page = pageRef.current;
|
||||
if (!page) return;
|
||||
const measure = () => setStacked(page.clientWidth < 600);
|
||||
measure();
|
||||
if (typeof ResizeObserver === "undefined") return;
|
||||
const observer = new ResizeObserver(measure);
|
||||
observer.observe(page);
|
||||
return () => observer.disconnect();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
void refreshPlugins();
|
||||
@@ -1403,7 +1419,7 @@ export function PluginsPage({ initialTab = "marketplace" }: { initialTab?: Tab }
|
||||
|
||||
const headerSlot = useSettingsHeaderSlot();
|
||||
const header = (
|
||||
<>
|
||||
<div className={styles.topBar}>
|
||||
<Tabs
|
||||
variant="compact"
|
||||
className={styles.sourceTabs}
|
||||
@@ -1421,12 +1437,12 @@ export function PluginsPage({ initialTab = "marketplace" }: { initialTab?: Tab }
|
||||
/>
|
||||
{(loading || installing) && <Spinner size={14} label={installing ? "Installing plugin" : "Loading plugins"} />}
|
||||
<IconButton icon="settings" title="Manage Plugins" aria-haspopup="menu" onClick={openGear} />
|
||||
</>
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className={styles.page}>
|
||||
{headerSlot ? createPortal(header, headerSlot) : <div className={styles.topBar}>{header}</div>}
|
||||
<div ref={pageRef} className={styles.page}>
|
||||
{headerSlot && !stacked ? createPortal(header, headerSlot) : header}
|
||||
|
||||
{error && (
|
||||
<div className={styles.error} role="alert">
|
||||
@@ -1434,8 +1450,13 @@ export function PluginsPage({ initialTab = "marketplace" }: { initialTab?: Tab }
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className={styles.body}>
|
||||
<div className={styles.side}>
|
||||
<SplitGroup
|
||||
id="plugin-panes"
|
||||
className={styles.body}
|
||||
orientation={stacked ? "vertical" : "horizontal"}
|
||||
storageKey={`openidea.settings.plugins.layout.${stacked ? "stacked" : "sideBySide"}`}
|
||||
>
|
||||
<SplitPanel id="plugin-list" defaultSize="45%" minSize={stacked ? "28%" : "240px"}>
|
||||
<div className={styles.searchRow}>
|
||||
<SearchField
|
||||
className={styles.searchField}
|
||||
@@ -1527,39 +1548,41 @@ export function PluginsPage({ initialTab = "marketplace" }: { initialTab?: Tab }
|
||||
{catalogError && <li className={clsx(styles.listEmpty, styles.errorText)}>{catalogError}</li>}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{tab === "installed" ? (
|
||||
selected ? (
|
||||
<InstalledDetails key={selected.id} plugin={selected} />
|
||||
</SplitPanel>
|
||||
<SplitHandle aria-label={tx("Resize plugin panes")} />
|
||||
<SplitPanel id="plugin-details" defaultSize="55%" minSize={stacked ? "35%" : "320px"}>
|
||||
{tab === "installed" ? (
|
||||
selected ? (
|
||||
<InstalledDetails key={selected.id} plugin={selected} />
|
||||
) : (
|
||||
<EmptyState className={styles.detailsEmpty} title={loaded ? "No plugin selected" : "Loading…"}>
|
||||
<T>Plugins are folders with a</T> <code>plugin.toml</code>
|
||||
<T>. Use the gear menu to install one from disk, or put dev plugins in</T>{" "}
|
||||
<code>.openidea/plugins/</code> <T>inside your project.</T>
|
||||
</EmptyState>
|
||||
)
|
||||
) : selectedMarket ? (
|
||||
<MarketDetails
|
||||
key={`market:${selectedMarket.id}`}
|
||||
entry={selectedMarket}
|
||||
suggestedBy={suggestions.get(selectedMarket.id)}
|
||||
onInstalled={(id) => {
|
||||
setTab("installed");
|
||||
setSelectedId(id);
|
||||
}}
|
||||
/>
|
||||
) : selectedEntry ? (
|
||||
<CatalogDetails key={selectedEntry.id} entry={selectedEntry} />
|
||||
) : marketUrl ? (
|
||||
<EmptyState className={styles.detailsEmpty} title="No plugin selected" />
|
||||
) : (
|
||||
<EmptyState className={styles.detailsEmpty} title={loaded ? "No plugin selected" : "Loading…"}>
|
||||
<T>Plugins are folders with a</T> <code>plugin.toml</code>
|
||||
<T>. Use the gear menu to install one from disk, or put dev plugins in</T> <code>.openidea/plugins/</code>{" "}
|
||||
<T>inside your project.</T>
|
||||
<EmptyState className={styles.detailsEmpty} title={NO_REPOSITORY}>
|
||||
<T>Install a plugin folder with</T> <code>plugin.toml</code>{" "}
|
||||
<T>via the gear menu › Install Plugin from Disk….</T>
|
||||
</EmptyState>
|
||||
)
|
||||
) : selectedMarket ? (
|
||||
<MarketDetails
|
||||
key={`market:${selectedMarket.id}`}
|
||||
entry={selectedMarket}
|
||||
suggestedBy={suggestions.get(selectedMarket.id)}
|
||||
onInstalled={(id) => {
|
||||
setTab("installed");
|
||||
setSelectedId(id);
|
||||
}}
|
||||
/>
|
||||
) : selectedEntry ? (
|
||||
<CatalogDetails key={selectedEntry.id} entry={selectedEntry} />
|
||||
) : marketUrl ? (
|
||||
<EmptyState className={styles.detailsEmpty} title="No plugin selected" />
|
||||
) : (
|
||||
<EmptyState className={styles.detailsEmpty} title={NO_REPOSITORY}>
|
||||
<T>Install a plugin folder with</T> <code>plugin.toml</code>{" "}
|
||||
<T>via the gear menu › Install Plugin from Disk….</T>
|
||||
</EmptyState>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</SplitPanel>
|
||||
</SplitGroup>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -953,7 +953,8 @@ describe("PluginsPage", () => {
|
||||
await user.click(screen.getByRole("button", { name: "Apply theme Harbor Night" }));
|
||||
await waitFor(() => expect(screen.getByRole("button", { name: "Use Default Theme" })).toBeInTheDocument());
|
||||
|
||||
await user.type(screen.getByLabelText("Filter plugins"), "toy");
|
||||
screen.getByLabelText("Filter plugins").focus();
|
||||
await user.keyboard("toy");
|
||||
await waitFor(() => expect(within(list).getAllByRole("listitem")).toHaveLength(1));
|
||||
expect(screen.getByRole("heading", { level: 2 })).toHaveTextContent("Toy Language");
|
||||
expect(screen.getByText("Toy (.toy)")).toBeInTheDocument();
|
||||
|
||||
@@ -115,7 +115,7 @@
|
||||
flex: 1 1 50%;
|
||||
min-width: 0;
|
||||
}
|
||||
.body > * + * {
|
||||
.body > :where(:not(:first-child)) {
|
||||
border-left: 1px solid var(--border);
|
||||
}
|
||||
.hidden {
|
||||
|
||||
@@ -107,6 +107,9 @@ type ResolvedNode = Exclude<MemNode, { kind: "symlink" }>;
|
||||
|
||||
const err = (kind: "notFound" | "alreadyExists" | "invalidInput", message: string) => new IpcError({ kind, message });
|
||||
|
||||
/** Created once: building a collator costs more than sorting a small folder with it. */
|
||||
const naturalOrder = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" });
|
||||
|
||||
/** The tree's own notion (see `isDirEntry`): a folder, or a link to one. */
|
||||
const isFolder = (e: FileEntry) => e.kind === "dir" || (e.kind === "symlink" && e.size === 0);
|
||||
|
||||
@@ -161,13 +164,14 @@ export class MemoryFs implements ProjectFs {
|
||||
const { path, node } = this.resolve(at);
|
||||
if (!node) throw err("notFound", `${path} not found`);
|
||||
if (node.kind !== "dir") throw err("invalidInput", `${at} is not a directory`);
|
||||
const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" });
|
||||
// A child is excluded when its folder is, or when it is itself an excluded path.
|
||||
const inExcluded = [...this.ignored].some((i) => path === i || isInside(path, i));
|
||||
return (
|
||||
this.childrenOf(path)
|
||||
.map((p) => {
|
||||
const c = this.nodes.get(p)!;
|
||||
const name = nameOf(p);
|
||||
const excluded = [...this.ignored].some((i) => p === i || isInside(p, i));
|
||||
const excluded = inExcluded || this.ignored.has(p);
|
||||
if (c.kind === "symlink") {
|
||||
const t = this.resolve(p);
|
||||
return {
|
||||
@@ -195,7 +199,7 @@ export class MemoryFs implements ProjectFs {
|
||||
} satisfies FileEntry;
|
||||
})
|
||||
// Folders first, counting a link to a folder as a folder (the backend's ordering).
|
||||
.sort((a, b) => Number(isFolder(b)) - Number(isFolder(a)) || collator.compare(a.name, b.name))
|
||||
.sort((a, b) => Number(isFolder(b)) - Number(isFolder(a)) || naturalOrder.compare(a.name, b.name))
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -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() }]
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -11,9 +11,6 @@ describe("agent chat settings", () => {
|
||||
foldTurns: true,
|
||||
smoothText: true,
|
||||
fitWindowWidth: false,
|
||||
playfulStatus: false,
|
||||
playfulAfterSeconds: 0,
|
||||
playfulWords: {},
|
||||
thinking: "auto",
|
||||
toolCalls: "grouped",
|
||||
expandToolOutput: false,
|
||||
@@ -55,20 +52,4 @@ describe("agent chat settings", () => {
|
||||
});
|
||||
expect(validateSettings({ agents: { newTaskApprovals: "never" } }).agents.newTaskApprovals).toBe("bypass");
|
||||
});
|
||||
|
||||
it("keeps the user's playful words by activity, an emptied list included", () => {
|
||||
const stored = validateSettings({
|
||||
agents: { playfulWords: { reading: ["Squinting…", " ", 3], working: [], editing: "nope" } },
|
||||
}).agents;
|
||||
expect(stored.playfulWords).toEqual({ reading: ["Squinting…"], working: [] });
|
||||
});
|
||||
|
||||
it("keeps the playful quiet time in whole seconds within its range", () => {
|
||||
const after = (v: unknown) => validateSettings({ agents: { playfulAfterSeconds: v } }).agents.playfulAfterSeconds;
|
||||
expect(after(0)).toBe(0);
|
||||
expect(after(2.6)).toBe(3);
|
||||
expect(after(-5)).toBe(0);
|
||||
expect(after(100_000)).toBe(600);
|
||||
expect(after("soon")).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -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,15 +1,26 @@
|
||||
.page {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-2);
|
||||
height: 100%;
|
||||
min-height: 420px;
|
||||
min-height: 0;
|
||||
min-width: 0;
|
||||
}
|
||||
.presetRow {
|
||||
.presetRow,
|
||||
.toolbar {
|
||||
display: flex;
|
||||
flex: none;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-1) var(--space-2);
|
||||
}
|
||||
.presetGroup {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
min-height: 30px;
|
||||
margin-bottom: 6px;
|
||||
flex: 0 1 328px;
|
||||
min-width: 0;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
.presetLabel {
|
||||
flex: none;
|
||||
@@ -17,7 +28,7 @@
|
||||
color: var(--fg);
|
||||
}
|
||||
.presetSelect {
|
||||
min-width: 220px;
|
||||
flex: 1;
|
||||
}
|
||||
.spacer {
|
||||
flex: 1;
|
||||
@@ -25,37 +36,44 @@
|
||||
.modifiedNote {
|
||||
color: var(--fg-subtle);
|
||||
font-size: var(--fs-small);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.toolbar {
|
||||
.treeActions,
|
||||
.filterGroup {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-0-5);
|
||||
margin-bottom: 6px;
|
||||
gap: var(--space-1);
|
||||
}
|
||||
.search {
|
||||
flex: 1;
|
||||
max-width: 360px;
|
||||
margin-right: 4px;
|
||||
.treeActions {
|
||||
flex: none;
|
||||
}
|
||||
.filterGroup {
|
||||
flex: 1 1 300px;
|
||||
min-width: 0;
|
||||
max-width: 392px;
|
||||
}
|
||||
.search,
|
||||
.shortcutFilter {
|
||||
flex: 1;
|
||||
max-width: 360px;
|
||||
min-width: 0;
|
||||
}
|
||||
.shortcutFilter {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-0-5);
|
||||
height: var(--h-control);
|
||||
margin-right: 4px;
|
||||
padding: 0 2px 0 8px;
|
||||
border-radius: var(--radius-small);
|
||||
box-shadow: inset 0 0 0 1px var(--border-strong);
|
||||
gap: var(--space-1);
|
||||
height: var(--h-field);
|
||||
padding: 0 var(--space-1) 0 var(--space-2);
|
||||
background: var(--bg-field);
|
||||
border-radius: var(--radius-control);
|
||||
box-shadow: inset 0 0 0 1px var(--border-button);
|
||||
}
|
||||
.shortcutFilter:focus-within {
|
||||
box-shadow: inset 0 0 0 1px var(--accent);
|
||||
box-shadow: inset 0 0 0 1px var(--focus-ring);
|
||||
}
|
||||
.leading {
|
||||
flex: none;
|
||||
color: var(--fg-subtle);
|
||||
margin-right: 4px;
|
||||
}
|
||||
.filterRecorder {
|
||||
flex: 1;
|
||||
@@ -67,6 +85,11 @@
|
||||
box-shadow: none;
|
||||
outline: none;
|
||||
}
|
||||
.filterRecorder > span {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.treeWrap {
|
||||
flex: 1;
|
||||
@@ -75,7 +98,7 @@
|
||||
flex-direction: column;
|
||||
border-radius: var(--radius-small);
|
||||
box-shadow: inset 0 0 0 1px var(--border);
|
||||
padding: 2px 0;
|
||||
padding-block: var(--space-0-5);
|
||||
}
|
||||
.empty {
|
||||
padding: 8px 12px;
|
||||
@@ -97,26 +120,21 @@
|
||||
}
|
||||
.actionIcon {
|
||||
display: inline-flex;
|
||||
flex: none;
|
||||
width: 14px;
|
||||
color: var(--fg-subtle);
|
||||
}
|
||||
.actionTitle {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
flex: 1 0 auto;
|
||||
}
|
||||
.modified {
|
||||
color: var(--accent);
|
||||
}
|
||||
.bindings {
|
||||
display: inline-flex;
|
||||
gap: var(--space-1);
|
||||
padding-right: 10px;
|
||||
}
|
||||
.kbd {
|
||||
color: var(--fg-muted);
|
||||
flex: none;
|
||||
gap: var(--space-2);
|
||||
padding-inline: var(--space-2);
|
||||
}
|
||||
|
||||
/* recorder */
|
||||
@@ -221,12 +239,6 @@
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
|
||||
.toolbarSep {
|
||||
width: 1px;
|
||||
height: 16px;
|
||||
margin: 0 4px;
|
||||
background: var(--border);
|
||||
}
|
||||
.conflictsLabel {
|
||||
color: var(--fg);
|
||||
padding-top: 4px;
|
||||
|
||||
@@ -373,26 +373,27 @@ export function KeymapPage() {
|
||||
return (
|
||||
<div className={styles.page}>
|
||||
<div className={styles.presetRow}>
|
||||
<span className={styles.presetLabel}>
|
||||
<SearchLabel text="Keymap:" />
|
||||
</span>
|
||||
<Select
|
||||
value={selectedId}
|
||||
aria-label="Keymap"
|
||||
className={styles.presetSelect}
|
||||
options={keymapOptions}
|
||||
onChange={selectKeymap}
|
||||
/>
|
||||
<IconButton
|
||||
ref={gearRef}
|
||||
icon="settings"
|
||||
title="Show Scheme Actions"
|
||||
onClick={() => {
|
||||
const r = gearRef.current?.getBoundingClientRect();
|
||||
showContextMenu(r ? { x: r.left, y: r.bottom + 2 } : { x: 0, y: 0 }, gearMenu());
|
||||
}}
|
||||
/>
|
||||
<span className={styles.spacer} />
|
||||
<div className={styles.presetGroup}>
|
||||
<span className={styles.presetLabel}>
|
||||
<SearchLabel text="Keymap:" />
|
||||
</span>
|
||||
<Select
|
||||
value={selectedId}
|
||||
aria-label="Keymap"
|
||||
className={styles.presetSelect}
|
||||
options={keymapOptions}
|
||||
onChange={selectKeymap}
|
||||
/>
|
||||
<IconButton
|
||||
ref={gearRef}
|
||||
icon="settings"
|
||||
title="Show Scheme Actions"
|
||||
onClick={() => {
|
||||
const r = gearRef.current?.getBoundingClientRect();
|
||||
showContextMenu(r ? { x: r.left, y: r.bottom + 2 } : { x: 0, y: 0 }, gearMenu());
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
{overrideCount > 0 && (
|
||||
<span className={styles.modifiedNote}>
|
||||
{overrideCount === 1 ? tx`${overrideCount} modified action` : tx`${overrideCount} modified actions`}
|
||||
@@ -401,68 +402,71 @@ export function KeymapPage() {
|
||||
</div>
|
||||
|
||||
<div className={styles.toolbar}>
|
||||
{byShortcut ? (
|
||||
<div className={styles.shortcutFilter}>
|
||||
<Icon name="keyboard" size={14} className={styles.leading} />
|
||||
<StrokeRecorder
|
||||
autoFocus
|
||||
chord
|
||||
value={shortcut}
|
||||
onChange={setShortcut}
|
||||
placeholder="Press a shortcut to find actions"
|
||||
aria-label="Find actions by shortcut"
|
||||
className={styles.filterRecorder}
|
||||
/>
|
||||
{shortcut && (
|
||||
<IconButton icon="close" title="Clear" size="small" iconSize={12} onClick={() => setShortcut("")} />
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<SearchField
|
||||
className={styles.search}
|
||||
value={query}
|
||||
onChange={setQuery}
|
||||
placeholder="Search actions"
|
||||
aria-label="Search actions"
|
||||
<div className={styles.treeActions}>
|
||||
<IconButton icon="expand-all" title="Expand All" onClick={() => setCollapsed(new Set())} />
|
||||
<IconButton icon="collapse-all" title="Collapse All" onClick={() => setCollapsed(new Set(allGroups))} />
|
||||
<IconButton
|
||||
icon="plus"
|
||||
title="Add Keyboard Shortcut"
|
||||
disabled={!leadAction}
|
||||
onClick={() => {
|
||||
if (!leadAction) return;
|
||||
setRecordMouse(false);
|
||||
setRecordFor(leadAction);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
<IconButton
|
||||
icon="keyboard"
|
||||
title="Find Actions by Shortcut"
|
||||
pressed={byShortcut}
|
||||
onClick={() => {
|
||||
setByShortcut((v) => !v);
|
||||
setShortcut("");
|
||||
}}
|
||||
/>
|
||||
<IconButton
|
||||
icon="filter"
|
||||
title="Clear Filtering"
|
||||
disabled={!filtering}
|
||||
onClick={() => {
|
||||
setQuery("");
|
||||
setShortcut("");
|
||||
}}
|
||||
/>
|
||||
<span className={styles.toolbarSep} aria-hidden />
|
||||
<IconButton icon="expand-all" title="Expand All" onClick={() => setCollapsed(new Set())} />
|
||||
<IconButton icon="collapse-all" title="Collapse All" onClick={() => setCollapsed(new Set(allGroups))} />
|
||||
<span className={styles.spacer} />
|
||||
<IconButton
|
||||
icon="plus"
|
||||
title="Add Keyboard Shortcut"
|
||||
disabled={!leadAction}
|
||||
onClick={() => {
|
||||
if (!leadAction) return;
|
||||
setRecordMouse(false);
|
||||
setRecordFor(leadAction);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div className={styles.filterGroup}>
|
||||
{byShortcut ? (
|
||||
<div className={styles.shortcutFilter}>
|
||||
<Icon name="keyboard" size={14} className={styles.leading} />
|
||||
<StrokeRecorder
|
||||
autoFocus
|
||||
chord
|
||||
value={shortcut}
|
||||
onChange={setShortcut}
|
||||
placeholder="Press a shortcut to find actions"
|
||||
aria-label="Find actions by shortcut"
|
||||
className={styles.filterRecorder}
|
||||
/>
|
||||
{shortcut && (
|
||||
<IconButton icon="close" title="Clear" size="small" iconSize={12} onClick={() => setShortcut("")} />
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<SearchField
|
||||
className={styles.search}
|
||||
value={query}
|
||||
onChange={setQuery}
|
||||
placeholder="Search actions"
|
||||
aria-label="Search actions"
|
||||
/>
|
||||
)}
|
||||
<IconButton
|
||||
icon="keyboard"
|
||||
title="Find Actions by Shortcut"
|
||||
pressed={byShortcut}
|
||||
onClick={() => {
|
||||
setByShortcut((v) => !v);
|
||||
setShortcut("");
|
||||
}}
|
||||
/>
|
||||
<IconButton
|
||||
icon="filter"
|
||||
title="Clear Filtering"
|
||||
disabled={!filtering}
|
||||
onClick={() => {
|
||||
setQuery("");
|
||||
setShortcut("");
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className={styles.treeWrap}>
|
||||
<Tree<KNode>
|
||||
aria-label="Actions"
|
||||
horizontalScroll
|
||||
roots={roots}
|
||||
getKey={(n) => n.key}
|
||||
getLabel={(n) => (n.kind === "group" ? n.name : n.action.title)}
|
||||
@@ -507,7 +511,7 @@ export function KeymapPage() {
|
||||
<span className={styles.catName}>{n.name}</span>
|
||||
</span>
|
||||
) : (
|
||||
<span className={styles.actionRow}>
|
||||
<span className={styles.actionRow} title={n.action.title}>
|
||||
<span className={styles.actionIcon}>{n.action.icon && <Icon name={n.action.icon} size={14} />}</span>
|
||||
<HighlightedText
|
||||
className={clsx(styles.actionTitle, n.modified && styles.modified)}
|
||||
@@ -517,7 +521,7 @@ export function KeymapPage() {
|
||||
/>
|
||||
<span className={styles.bindings}>
|
||||
{n.bindings.map((b) => (
|
||||
<Kbd key={b} binding={b} className={styles.kbd} />
|
||||
<Kbd key={b} binding={b} />
|
||||
))}
|
||||
</span>
|
||||
</span>
|
||||
|
||||
@@ -41,7 +41,6 @@ import {
|
||||
type NotificationsValid,
|
||||
} from "./behaviorSchema";
|
||||
import { isThemeChoiceId, type ThemeChoiceId } from "@/platform/themes";
|
||||
import { PLAYFUL_AFTER_LIMITS } from "@/platform/agentStatus";
|
||||
|
||||
/** Agents › IDE MCP Server › Port: its default (`ide-core::settings::DEFAULT_MCP_PORT`) and range. */
|
||||
export const DEFAULT_MCP_PORT = 26371;
|
||||
@@ -238,9 +237,6 @@ export const DEFAULT_SETTINGS: ValidSettings = {
|
||||
foldTurns: true,
|
||||
smoothText: true,
|
||||
fitWindowWidth: false,
|
||||
playfulStatus: false,
|
||||
playfulAfterSeconds: 0,
|
||||
playfulWords: {},
|
||||
thinking: "auto",
|
||||
toolCalls: "grouped",
|
||||
expandToolOutput: false,
|
||||
@@ -291,15 +287,6 @@ function agentDefaults(v: unknown): Record<string, Record<string, string>> {
|
||||
return Object.fromEntries(Object.entries(obj(v)).map(([agent, options]) => [agent, stringMap(options)]));
|
||||
}
|
||||
|
||||
/** Activity → the user's playful words; a list, even an empty one, stands for that activity. */
|
||||
function playfulWords(v: unknown): Record<string, string[]> {
|
||||
return Object.fromEntries(
|
||||
Object.entries(obj(v))
|
||||
.filter(([, words]) => Array.isArray(words))
|
||||
.map(([activity, words]) => [activity, stringList(words)]),
|
||||
);
|
||||
}
|
||||
|
||||
function agentMcpServers(v: unknown): Required<AgentSettings>["mcpServers"] {
|
||||
const out: Required<AgentSettings>["mcpServers"] = {};
|
||||
for (const [name, raw] of Object.entries(obj(v))) {
|
||||
@@ -453,9 +440,6 @@ export function validateSettings(raw: Settings | unknown): ValidSettings {
|
||||
foldTurns: bool(agents.foldTurns, d.agents.foldTurns),
|
||||
smoothText: bool(agents.smoothText, d.agents.smoothText),
|
||||
fitWindowWidth: bool(agents.fitWindowWidth, d.agents.fitWindowWidth),
|
||||
playfulStatus: bool(agents.playfulStatus, d.agents.playfulStatus),
|
||||
playfulAfterSeconds: num(agents.playfulAfterSeconds, d.agents.playfulAfterSeconds, PLAYFUL_AFTER_LIMITS, true),
|
||||
playfulWords: playfulWords(agents.playfulWords),
|
||||
thinking: oneOf(agents.thinking, ["auto", "expanded", "collapsed"] as const, d.agents.thinking),
|
||||
toolCalls: oneOf(agents.toolCalls, ["grouped", "each"] as const, d.agents.toolCalls),
|
||||
expandToolOutput: bool(agents.expandToolOutput, d.agents.expandToolOutput),
|
||||
|
||||
@@ -2,21 +2,30 @@
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
min-width: 0;
|
||||
min-height: 420px;
|
||||
}
|
||||
.profileRow {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
gap: var(--space-1) var(--space-3);
|
||||
min-height: 30px;
|
||||
margin-bottom: 8px;
|
||||
margin-bottom: var(--space-2);
|
||||
}
|
||||
.profileSelect {
|
||||
min-width: 220px;
|
||||
.profileControls {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
max-width: 100%;
|
||||
min-width: 0;
|
||||
}
|
||||
.profileRow > span {
|
||||
.profileControls > span {
|
||||
flex: none;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.profileControls > .profileSelect {
|
||||
width: 220px;
|
||||
min-width: 0;
|
||||
}
|
||||
.toolbar {
|
||||
display: flex;
|
||||
@@ -26,24 +35,19 @@
|
||||
}
|
||||
.search {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
max-width: 320px;
|
||||
margin-right: 4px;
|
||||
margin-right: var(--space-1);
|
||||
}
|
||||
.split {
|
||||
flex: 1;
|
||||
min-width: 520px;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
gap: var(--space-3);
|
||||
min-width: 0;
|
||||
}
|
||||
.treeWrap {
|
||||
flex: 3;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
border-radius: var(--radius-small);
|
||||
box-shadow: inset 0 0 0 1px var(--border);
|
||||
padding: 2px 0;
|
||||
padding: var(--space-0-5) 0;
|
||||
}
|
||||
.empty {
|
||||
padding: 8px 12px;
|
||||
@@ -80,13 +84,20 @@
|
||||
flex: none;
|
||||
}
|
||||
.details {
|
||||
flex: 2;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
padding: 2px 4px;
|
||||
overflow: auto;
|
||||
gap: var(--space-2);
|
||||
padding: var(--space-3);
|
||||
}
|
||||
.detailTitle {
|
||||
margin: 0;
|
||||
color: var(--fg-strong);
|
||||
font-size: var(--fs-ui);
|
||||
font-weight: 600;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.description {
|
||||
margin: 0;
|
||||
@@ -95,19 +106,34 @@
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.severityRow {
|
||||
.descriptionPane,
|
||||
.optionsPane {
|
||||
min-height: 0;
|
||||
overflow: auto;
|
||||
}
|
||||
.descriptionPane {
|
||||
padding-bottom: var(--space-2);
|
||||
}
|
||||
.optionsPane {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-2);
|
||||
padding-top: var(--space-2);
|
||||
}
|
||||
.severityRow {
|
||||
flex: none;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
padding-top: 10px;
|
||||
border-top: 1px solid var(--border);
|
||||
}
|
||||
.options {
|
||||
flex: none;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-1-5);
|
||||
margin: 0;
|
||||
padding: 10px 0 0;
|
||||
padding: var(--space-2) 0 0;
|
||||
border: none;
|
||||
border-top: 1px solid var(--border);
|
||||
min-width: 0;
|
||||
@@ -115,11 +141,12 @@
|
||||
.options legend {
|
||||
float: left;
|
||||
width: 100%;
|
||||
padding: 0 0 4px;
|
||||
padding: 0 0 var(--space-1);
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
.levelSelect {
|
||||
min-width: 160px;
|
||||
width: 160px;
|
||||
max-width: 100%;
|
||||
}
|
||||
.profileLevel {
|
||||
color: var(--fg-subtle);
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
* chosen one is in effect for the project (editor highlighting, Problems,
|
||||
* Inspect Code).
|
||||
*/
|
||||
import { useEffect, useId, useMemo, useRef, useState, type MouseEvent } from "react";
|
||||
import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState, type MouseEvent } from "react";
|
||||
import clsx from "clsx";
|
||||
import {
|
||||
BUILTIN_INSPECTIONS,
|
||||
@@ -34,6 +34,9 @@ import {
|
||||
Input,
|
||||
SearchField,
|
||||
Select,
|
||||
SplitGroup,
|
||||
SplitHandle,
|
||||
SplitPanel,
|
||||
T,
|
||||
Tree,
|
||||
showContextMenu,
|
||||
@@ -92,6 +95,19 @@ function expandableKeys(nodes: readonly InspectionNode[], out = new Set<string>(
|
||||
}
|
||||
|
||||
export function InspectionsPage() {
|
||||
const pageRef = useRef<HTMLDivElement>(null);
|
||||
const [stacked, setStacked] = useState(false);
|
||||
useLayoutEffect(() => {
|
||||
const page = pageRef.current;
|
||||
if (!page) return;
|
||||
const measure = () => setStacked(page.clientWidth < 560);
|
||||
measure();
|
||||
if (typeof ResizeObserver === "undefined") return;
|
||||
const observer = new ResizeObserver(measure);
|
||||
observer.observe(page);
|
||||
return () => observer.disconnect();
|
||||
}, []);
|
||||
|
||||
const hasProject = useProject((s) => !!s.project);
|
||||
const newProjects = useSettingsDialog((s) => s.newProjects);
|
||||
const projectAvailable = hasProject && !newProjects;
|
||||
@@ -223,20 +239,22 @@ export function InspectionsPage() {
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={styles.page}>
|
||||
<div ref={pageRef} className={styles.page}>
|
||||
<div className={styles.profileRow}>
|
||||
<span>
|
||||
<T>Profile:</T>
|
||||
</span>
|
||||
<Select
|
||||
className={styles.profileSelect}
|
||||
aria-label="Inspection profile"
|
||||
value={profileId}
|
||||
options={profileOptions}
|
||||
onChange={(v) => setChosen(v)}
|
||||
disabled={profileOptions.length < 2}
|
||||
/>
|
||||
<IconButton icon="settings" title="Profile Actions" onClick={gearMenu} />
|
||||
<div className={styles.profileControls}>
|
||||
<span>
|
||||
<T>Profile:</T>
|
||||
</span>
|
||||
<Select
|
||||
className={styles.profileSelect}
|
||||
aria-label="Inspection profile"
|
||||
value={profileId}
|
||||
options={profileOptions}
|
||||
onChange={(v) => setChosen(v)}
|
||||
disabled={profileOptions.length < 2}
|
||||
/>
|
||||
<IconButton icon="settings" title="Profile Actions" onClick={gearMenu} />
|
||||
</div>
|
||||
<span className={styles.profileLevel}>
|
||||
<T>{location.level === "project" ? "Stored in Project" : "Stored in IDE"}</T>
|
||||
</span>
|
||||
@@ -265,8 +283,16 @@ export function InspectionsPage() {
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className={styles.split}>
|
||||
<div
|
||||
<SplitGroup
|
||||
id="inspection-panes"
|
||||
className={styles.split}
|
||||
orientation={stacked ? "vertical" : "horizontal"}
|
||||
storageKey="openidea.settings.inspections.layout"
|
||||
>
|
||||
<SplitPanel
|
||||
id="inspection-tree"
|
||||
defaultSize="50%"
|
||||
minSize="35%"
|
||||
className={styles.treeWrap}
|
||||
onKeyDown={(e) => {
|
||||
// Space toggles the selected inspection, as in IDEA.
|
||||
@@ -309,9 +335,12 @@ export function InspectionsPage() {
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<Details node={selected} overrides={overrides} onChange={setOverrides} />
|
||||
</div>
|
||||
</SplitPanel>
|
||||
<SplitHandle aria-label={tx("Resize inspection panes")} />
|
||||
<SplitPanel id="inspection-details" defaultSize="50%" minSize="35%">
|
||||
<Details node={selected} overrides={overrides} onChange={setOverrides} />
|
||||
</SplitPanel>
|
||||
</SplitGroup>
|
||||
|
||||
{nameDialog && (
|
||||
<ProfileNameDialog
|
||||
@@ -435,38 +464,50 @@ function Details({
|
||||
overrides: ProfileOverrides;
|
||||
onChange: (o: ProfileOverrides) => void;
|
||||
}) {
|
||||
if (!node) {
|
||||
return (
|
||||
<div className={styles.details}>
|
||||
<p className={styles.description}>
|
||||
<T>Select an inspection to see its description and change its severity.</T>
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const id = node.id;
|
||||
const id = node?.id;
|
||||
const description = (
|
||||
<p className={styles.description}>
|
||||
<T>{node?.description ?? "Select an inspection to see its description and change its severity."}</T>
|
||||
</p>
|
||||
);
|
||||
return (
|
||||
<div className={styles.details}>
|
||||
<p className={styles.description}>
|
||||
<T>{node.description}</T>
|
||||
</p>
|
||||
{id && (
|
||||
<div className={styles.severityRow}>
|
||||
<span>
|
||||
<T>Severity:</T>
|
||||
</span>
|
||||
<Select
|
||||
className={styles.levelSelect}
|
||||
aria-label="Severity"
|
||||
value={overrides[id]?.severity ?? AS_REPORTED}
|
||||
options={LEVEL_OPTIONS}
|
||||
disabled={!isEnabled(overrides, id)}
|
||||
onChange={(v) => onChange(setLevel(overrides, id, v === AS_REPORTED ? undefined : (v as InspectionLevel)))}
|
||||
/>
|
||||
</div>
|
||||
<section className={styles.details} aria-label={tx("Inspection details")}>
|
||||
{node && (
|
||||
<h3 className={styles.detailTitle}>
|
||||
<T>{node.name}</T>
|
||||
</h3>
|
||||
)}
|
||||
{id && <InspectionOptions id={id} overrides={overrides} onChange={onChange} />}
|
||||
</div>
|
||||
{id ? (
|
||||
<SplitGroup id="inspection-rule" className={styles.split} orientation="vertical">
|
||||
<SplitPanel id="inspection-description" defaultSize="45%" minSize="25%">
|
||||
<div className={styles.descriptionPane}>{description}</div>
|
||||
</SplitPanel>
|
||||
<SplitHandle aria-label={tx("Resize inspection description")} />
|
||||
<SplitPanel id="inspection-options" defaultSize="55%" minSize="25%">
|
||||
<div className={styles.optionsPane}>
|
||||
<div className={styles.severityRow}>
|
||||
<span>
|
||||
<T>Severity:</T>
|
||||
</span>
|
||||
<Select
|
||||
className={styles.levelSelect}
|
||||
aria-label="Severity"
|
||||
value={overrides[id]?.severity ?? AS_REPORTED}
|
||||
options={LEVEL_OPTIONS}
|
||||
disabled={!isEnabled(overrides, id)}
|
||||
onChange={(v) =>
|
||||
onChange(setLevel(overrides, id, v === AS_REPORTED ? undefined : (v as InspectionLevel)))
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<InspectionOptions id={id} overrides={overrides} onChange={onChange} />
|
||||
</div>
|
||||
</SplitPanel>
|
||||
</SplitGroup>
|
||||
) : (
|
||||
<div className={styles.descriptionPane}>{description}</div>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -1,7 +1,16 @@
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { useWorkflowSettings } from "@/platform/workflowSettings";
|
||||
import { EmptyState, IconButton, SplitGroup, SplitHandle, SplitPanel, T, Tabs } from "@/ui";
|
||||
import {
|
||||
EmptyState,
|
||||
IconButton,
|
||||
SplitGroup,
|
||||
SplitHandle,
|
||||
SplitPanel,
|
||||
T,
|
||||
Tabs,
|
||||
useFrozenWhileWindowResizes,
|
||||
} from "@/ui";
|
||||
import { copySelectionOnKeyDown } from "@/ui/selectableText";
|
||||
import { spanStyle } from "@/ui/ansi";
|
||||
import clsx from "clsx";
|
||||
@@ -68,6 +77,10 @@ export function GitToolWindow() {
|
||||
const { shown } = useGitTabs();
|
||||
const available = useVcs((s) => s.available);
|
||||
const external = useGitLog((s) => s.logTabs.some((t) => t.id === s.tab && t.readOnly));
|
||||
// The log's rows, graph and branch tree are too much for WebKit to relayout at every step of a
|
||||
// window drag; they follow the window once it stops.
|
||||
const root = useRef<HTMLDivElement>(null);
|
||||
useFrozenWhileWindowResizes(root);
|
||||
if (!available && !external)
|
||||
return (
|
||||
<EmptyState title="Version control is not configured">
|
||||
@@ -76,6 +89,7 @@ export function GitToolWindow() {
|
||||
);
|
||||
return (
|
||||
<div
|
||||
ref={root}
|
||||
className={styles.root}
|
||||
role="tabpanel"
|
||||
id={`openidea-git-panel-${shown}`}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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();
|
||||
}
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -441,32 +441,110 @@
|
||||
gap: var(--space-2) var(--space-4);
|
||||
}
|
||||
/* Interactive rebase dialog. */
|
||||
.rebaseList {
|
||||
max-height: 360px;
|
||||
overflow: auto;
|
||||
margin: 0 14px;
|
||||
.rebaseDialog {
|
||||
height: min(550px, calc(100vh - 48px));
|
||||
}
|
||||
.rebasePage {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-2);
|
||||
min-height: 0;
|
||||
height: 100%;
|
||||
padding: var(--space-2) var(--space-3) var(--space-3);
|
||||
}
|
||||
.rebaseSplit {
|
||||
flex: 1;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-small);
|
||||
}
|
||||
.rebaseToolbar {
|
||||
display: flex;
|
||||
flex: none;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-1);
|
||||
padding: var(--space-1) var(--space-2);
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.rebaseList {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow: auto;
|
||||
padding: var(--space-1);
|
||||
}
|
||||
.rebaseRow {
|
||||
min-height: var(--h-row);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
padding: 2px 6px;
|
||||
white-space: nowrap;
|
||||
gap: var(--space-1);
|
||||
padding: var(--space-0-5) var(--space-2);
|
||||
border-radius: var(--radius-selection);
|
||||
}
|
||||
.rebaseRow:hover {
|
||||
background: var(--bg-hover);
|
||||
}
|
||||
.rebaseRow[data-selected] {
|
||||
background: var(--bg-selected);
|
||||
}
|
||||
.rebaseCommit {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
gap: var(--space-0-5);
|
||||
min-width: 0;
|
||||
min-height: var(--h-row);
|
||||
padding: var(--space-1) 0;
|
||||
border-radius: var(--radius-small);
|
||||
color: var(--fg-strong);
|
||||
text-align: left;
|
||||
}
|
||||
.rebaseCommit:focus-visible {
|
||||
outline: 1px solid var(--focus-ring);
|
||||
}
|
||||
.rebaseSubject {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.rebaseSubject[data-dropped] {
|
||||
text-decoration: line-through;
|
||||
}
|
||||
.rebaseAction {
|
||||
width: 120px;
|
||||
flex: none;
|
||||
width: 112px;
|
||||
flex: 0 1 112px;
|
||||
}
|
||||
.rebaseDetails {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
flex-direction: column;
|
||||
gap: var(--space-2);
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
overflow: auto;
|
||||
padding: var(--space-3);
|
||||
}
|
||||
.rebaseMetadata {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: var(--space-0-5) var(--space-2);
|
||||
color: var(--fg-subtle);
|
||||
font-size: var(--fs-small);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.rebasePreview {
|
||||
color: var(--fg-strong);
|
||||
line-height: 1.5;
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
user-select: text;
|
||||
}
|
||||
.rebaseMessage {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
width: 100%;
|
||||
min-height: calc(4 * var(--h-row));
|
||||
resize: none;
|
||||
line-height: 1.5;
|
||||
}
|
||||
/* Push dialog: the editable target branch. */
|
||||
.targetInput {
|
||||
|
||||
@@ -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"
|
||||
/>
|
||||
|
||||
@@ -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),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -3,10 +3,10 @@ import { commitRepo } from "./multiRoot";
|
||||
* Git Log history rewriting: Undo Commit, Edit Commit Message, Drop Commit and
|
||||
* Interactively Rebase from Here (IDEA's Git.Log.ContextMenu).
|
||||
*/
|
||||
import { useState } from "react";
|
||||
import { useLayoutEffect, useRef, useState } from "react";
|
||||
import type { BranchInfo, Commit, RebaseAction, RebaseEntry } from "@/bindings";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { Dialog, IconButton, Select, T } from "@/ui";
|
||||
import { Dialog, IconButton, Select, SplitGroup, SplitHandle, SplitPanel, T } from "@/ui";
|
||||
import { workflowSettings } from "@/platform/workflowSettings";
|
||||
import { ask, showError } from "@/workbench/messages";
|
||||
import { chooseTargetChangelist, moveToChangelist } from "./changelistsUi";
|
||||
@@ -426,6 +426,22 @@ function InteractiveRebaseDialog({
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const [rows, setRows] = useState<RebaseRow[]>(() => initialRows(range.commits));
|
||||
const [selectedId, setSelectedId] = useState(() => rows[0]?.commit.id);
|
||||
const pageRef = useRef<HTMLDivElement>(null);
|
||||
const [stacked, setStacked] = useState(false);
|
||||
useLayoutEffect(() => {
|
||||
const page = pageRef.current;
|
||||
if (!page) return;
|
||||
const measure = () => setStacked(page.clientWidth < 640);
|
||||
measure();
|
||||
if (typeof ResizeObserver === "undefined") return;
|
||||
const observer = new ResizeObserver(measure);
|
||||
observer.observe(page);
|
||||
return () => observer.disconnect();
|
||||
}, []);
|
||||
|
||||
const selectedIndex = rows.findIndex((r) => r.commit.id === selectedId);
|
||||
const selected = rows[selectedIndex];
|
||||
const problem = planProblem(rows);
|
||||
const noop = planIsNoop(rows, range.commits);
|
||||
const update = (i: number, patch: Partial<RebaseRow>) =>
|
||||
@@ -440,62 +456,104 @@ function InteractiveRebaseDialog({
|
||||
open
|
||||
title={rebaseTitle(range.commits.length, range.base && short(range.base))}
|
||||
onClose={onClose}
|
||||
width={720}
|
||||
footerStart={problem ? <span className={styles.error}>{problem}</span> : undefined}
|
||||
width={960}
|
||||
minWidth={360}
|
||||
minHeight={360}
|
||||
resizable="both"
|
||||
className={styles.rebaseDialog}
|
||||
buttons={[
|
||||
{ label: "Start Rebasing", role: "default", disabled: !!problem || noop, onClick: start },
|
||||
{ label: "Cancel", role: "cancel" },
|
||||
]}
|
||||
>
|
||||
<div className={styles.section}>
|
||||
<T>Commits are applied from top to bottom.</T>
|
||||
</div>
|
||||
<div className={styles.rebaseList} role="list" aria-label={tx("Commits to rebase")}>
|
||||
{rows.map((r, i) => (
|
||||
<div key={r.commit.id} className={styles.rebaseRow} role="listitem">
|
||||
<Select<RebaseAction>
|
||||
value={r.action}
|
||||
options={ACTIONS}
|
||||
aria-label={tx`Action for ${short(r.commit.id)}`}
|
||||
className={styles.rebaseAction}
|
||||
onChange={(action) => update(i, { action })}
|
||||
/>
|
||||
<span className={styles.commitHash}>{r.commit.shortId}</span>
|
||||
{r.action === "reword" ? (
|
||||
<textarea
|
||||
className={`${styles.textarea} ${styles.rebaseMessage}`}
|
||||
aria-label={`New message for ${short(r.commit.id)}`}
|
||||
rows={2}
|
||||
value={r.message}
|
||||
onChange={(e) => update(i, { message: e.target.value })}
|
||||
<div className={styles.rebasePage} ref={pageRef}>
|
||||
<SplitGroup id="rebase-panes" className={styles.rebaseSplit} orientation={stacked ? "vertical" : "horizontal"}>
|
||||
<SplitPanel id="rebase-plan" defaultSize="50%" minSize="30%">
|
||||
<div className={styles.rebaseToolbar}>
|
||||
<IconButton
|
||||
icon="arrow-up"
|
||||
size="small"
|
||||
title="Move Up"
|
||||
disabled={selectedIndex <= 0}
|
||||
onClick={() => setRows((rs) => moveRow(rs, selectedIndex, -1))}
|
||||
/>
|
||||
) : (
|
||||
<span
|
||||
className={styles.commitSubject}
|
||||
style={r.action === "drop" ? { textDecoration: "line-through" } : undefined}
|
||||
title={r.commit.message}
|
||||
>
|
||||
{r.commit.summary}
|
||||
<IconButton
|
||||
icon="arrow-down"
|
||||
size="small"
|
||||
title="Move Down"
|
||||
disabled={selectedIndex < 0 || selectedIndex === rows.length - 1}
|
||||
onClick={() => setRows((rs) => moveRow(rs, selectedIndex, 1))}
|
||||
/>
|
||||
<span className={styles.hint}>
|
||||
<T>Commits are applied from top to bottom.</T>
|
||||
</span>
|
||||
</div>
|
||||
<div className={styles.rebaseList} role="list" aria-label={tx("Commits to rebase")}>
|
||||
{rows.map((r, i) => (
|
||||
<div
|
||||
key={r.commit.id}
|
||||
className={styles.rebaseRow}
|
||||
role="listitem"
|
||||
data-selected={r.commit.id === selectedId || undefined}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
className={styles.rebaseCommit}
|
||||
aria-current={r.commit.id === selectedId || undefined}
|
||||
onClick={() => setSelectedId(r.commit.id)}
|
||||
title={r.commit.summary}
|
||||
>
|
||||
<span className={styles.rebaseSubject} data-dropped={r.action === "drop" || undefined}>
|
||||
{r.commit.summary}
|
||||
</span>
|
||||
<span className={styles.commitHash}>{r.commit.shortId}</span>
|
||||
</button>
|
||||
<Select<RebaseAction>
|
||||
value={r.action}
|
||||
options={ACTIONS}
|
||||
aria-label={tx`Action for ${short(r.commit.id)}`}
|
||||
className={styles.rebaseAction}
|
||||
onChange={(action) => {
|
||||
setSelectedId(r.commit.id);
|
||||
update(i, { action });
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</SplitPanel>
|
||||
<SplitHandle aria-label={tx("Resize rebase panes")} />
|
||||
<SplitPanel id="rebase-details" defaultSize="50%" minSize="30%">
|
||||
{selected && (
|
||||
<section className={styles.rebaseDetails} aria-label={tx("Commit details")}>
|
||||
<div className={styles.rebaseMetadata}>
|
||||
<span className={styles.commitHash}>{selected.commit.shortId}</span>
|
||||
<span>{selected.commit.author}</span>
|
||||
</div>
|
||||
{selected.action === "reword" ? (
|
||||
<textarea
|
||||
key={selected.commit.id}
|
||||
className={`${styles.textarea} ${styles.rebaseMessage}`}
|
||||
aria-label={tx`New message for ${short(selected.commit.id)}`}
|
||||
rows={5}
|
||||
value={selected.message}
|
||||
onChange={(e) => update(selectedIndex, { message: e.target.value })}
|
||||
/>
|
||||
) : (
|
||||
<div className={styles.rebasePreview}>
|
||||
{selected.commit.message.trimEnd() || selected.commit.summary}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
)}
|
||||
<IconButton
|
||||
icon="arrow-up"
|
||||
size="small"
|
||||
title="Move Up"
|
||||
disabled={i === 0}
|
||||
onClick={() => setRows((rs) => moveRow(rs, i, -1))}
|
||||
/>
|
||||
<IconButton
|
||||
icon="arrow-down"
|
||||
size="small"
|
||||
title="Move Down"
|
||||
disabled={i === rows.length - 1}
|
||||
onClick={() => setRows((rs) => moveRow(rs, i, 1))}
|
||||
/>
|
||||
</SplitPanel>
|
||||
</SplitGroup>
|
||||
{problem && (
|
||||
<div className={styles.error} role="alert">
|
||||
{tx(problem)}
|
||||
</div>
|
||||
))}
|
||||
)}
|
||||
</div>
|
||||
<div style={{ height: 12 }} />
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -1,2 +0,0 @@
|
||||
/** Settings › Agents › Working Status: seconds the agent may report nothing new before playful words show. */
|
||||
export const PLAYFUL_AFTER_LIMITS = { min: 0, max: 600 } as const;
|
||||
@@ -0,0 +1,37 @@
|
||||
import { afterEach, expect, it } from "vitest";
|
||||
import { isIgnoredName } from "./ignoredNames";
|
||||
import { useProject } from "./project";
|
||||
|
||||
const initial = useProject.getState();
|
||||
afterEach(() => useProject.setState(initial, true));
|
||||
|
||||
function withNames(ignoredNames: string[]) {
|
||||
useProject.setState({ settings: { files: { ignoredNames } } } as never);
|
||||
}
|
||||
|
||||
it("matches the defaults by exact name and by wildcard", () => {
|
||||
expect(isIgnoredName(".git")).toBe(true);
|
||||
expect(isIgnoredName("module.pyc")).toBe(true);
|
||||
expect(isIgnoredName("notes.txt~")).toBe(true);
|
||||
expect(isIgnoredName("module.py")).toBe(false);
|
||||
expect(isIgnoredName("pyc")).toBe(false);
|
||||
});
|
||||
|
||||
it("anchors every wildcard and keeps other pattern characters literal", () => {
|
||||
withNames(["*.log", "build?", "a+b.(x)"]);
|
||||
expect(isIgnoredName("server.log")).toBe(true);
|
||||
expect(isIgnoredName("server.log.1")).toBe(false);
|
||||
expect(isIgnoredName("build1")).toBe(true);
|
||||
expect(isIgnoredName("build12")).toBe(false);
|
||||
expect(isIgnoredName("a+b.(x)")).toBe(true);
|
||||
expect(isIgnoredName("aab.x")).toBe(false);
|
||||
});
|
||||
|
||||
it("follows the setting when it changes, and ignores entries with a path", () => {
|
||||
withNames(["dist", "out/*"]);
|
||||
expect(isIgnoredName("dist")).toBe(true);
|
||||
expect(isIgnoredName(".git")).toBe(false);
|
||||
expect(isIgnoredName("out")).toBe(false);
|
||||
withNames([]);
|
||||
expect(isIgnoredName("dist")).toBe(false);
|
||||
});
|
||||
@@ -23,28 +23,40 @@ export const DEFAULT_IGNORED_NAMES: readonly string[] = [
|
||||
"desktop.ini",
|
||||
];
|
||||
|
||||
let cached: { names: readonly string[]; exact: Set<string>; wildcards: RegExp[] } | null = null;
|
||||
interface Compiled {
|
||||
names: readonly string[];
|
||||
exact: Set<string>;
|
||||
suffixes: string[];
|
||||
wildcards: RegExp | null;
|
||||
}
|
||||
|
||||
function compile(names: readonly string[]) {
|
||||
let cached: Compiled | null = null;
|
||||
|
||||
function compile(names: readonly string[]): Compiled {
|
||||
const exact = new Set<string>();
|
||||
const wildcards: RegExp[] = [];
|
||||
const suffixes: string[] = [];
|
||||
const patterns: string[] = [];
|
||||
for (const raw of names) {
|
||||
const n = raw.trim();
|
||||
if (!n || n.includes("/")) continue;
|
||||
if (!/[*?]/.test(n)) exact.add(n);
|
||||
// `*.pyc` (every default pattern): a suffix test, without a regex that retries `.*` at each position.
|
||||
else if (/^\*[^*?]+$/.test(n)) suffixes.push(n.slice(1));
|
||||
else {
|
||||
const body = n
|
||||
.replace(/[.+^${}()|[\]\\]/g, "\\$&")
|
||||
.replace(/\*/g, ".*")
|
||||
.replace(/\?/g, ".");
|
||||
wildcards.push(new RegExp(`^${body}$`, "s"));
|
||||
patterns.push(body);
|
||||
}
|
||||
}
|
||||
return { names, exact, wildcards };
|
||||
// One alternation: a folder of thousands of entries tests each name once, not once per pattern.
|
||||
const wildcards = patterns.length ? new RegExp(`^(?:${patterns.join("|")})$`, "s") : null;
|
||||
return { names, exact, suffixes, wildcards };
|
||||
}
|
||||
|
||||
export function isIgnoredName(name: string): boolean {
|
||||
const names = useProject.getState().settings?.files?.ignoredNames ?? DEFAULT_IGNORED_NAMES;
|
||||
const m = cached?.names === names ? cached : (cached = compile(names));
|
||||
return m.exact.has(name) || m.wildcards.some((re) => re.test(name));
|
||||
return m.exact.has(name) || m.suffixes.some((s) => name.endsWith(s)) || !!m.wildcards?.test(name);
|
||||
}
|
||||
@@ -1,4 +1,7 @@
|
||||
{
|
||||
"Inspection details": "Inspection details",
|
||||
"Resize inspection panes": "Resize inspection panes",
|
||||
"Resize inspection description": "Resize inspection description",
|
||||
"Table actions": "Table actions",
|
||||
"Table pages": "Table pages",
|
||||
"Problems actions": "Problems actions",
|
||||
@@ -1986,30 +1989,6 @@
|
||||
"Previous Failed Test": "Previous Failed Test",
|
||||
"Next Failed Test": "Next Failed Test",
|
||||
"Run '{name}' with Fuzzing": "Run '{name}' with Fuzzing",
|
||||
"Untangling imports…": "Untangling imports…",
|
||||
"Counting brackets…": "Counting brackets…",
|
||||
"Herding semicolons…": "Herding semicolons…",
|
||||
"Explaining it to the rubber duck…": "Explaining it to the rubber duck…",
|
||||
"Negotiating with the borrow checker…": "Negotiating with the borrow checker…",
|
||||
"Chasing a null pointer…": "Chasing a null pointer…",
|
||||
"Bisecting the problem…": "Bisecting the problem…",
|
||||
"Reading the fine manual…": "Reading the fine manual…",
|
||||
"Refactoring a hunch…": "Refactoring a hunch…",
|
||||
"Grepping the void…": "Grepping the void…",
|
||||
"Garbage-collecting thoughts…": "Garbage-collecting thoughts…",
|
||||
"Rebasing onto reality…": "Rebasing onto reality…",
|
||||
"Compiling a plan…": "Compiling a plan…",
|
||||
"Walking the call stack…": "Walking the call stack…",
|
||||
"Warming up the compiler…": "Warming up the compiler…",
|
||||
"Settling tabs versus spaces…": "Settling tabs versus spaces…",
|
||||
"Caching an insight…": "Caching an insight…",
|
||||
"Following the breadcrumbs…": "Following the breadcrumbs…",
|
||||
"Squinting at the diff…": "Squinting at the diff…",
|
||||
"Asking the linter nicely…": "Asking the linter nicely…",
|
||||
"Measuring twice…": "Measuring twice…",
|
||||
"Sharpening the pencils…": "Sharpening the pencils…",
|
||||
"Naming things…": "Naming things…",
|
||||
"Invalidating a cache…": "Invalidating a cache…",
|
||||
"Reading…": "Reading…",
|
||||
"Editing…": "Editing…",
|
||||
"Deleting…": "Deleting…",
|
||||
@@ -2019,42 +1998,6 @@
|
||||
"Thinking…": "Thinking…",
|
||||
"Writing…": "Writing…",
|
||||
"Running a subagent…": "Running a subagent…",
|
||||
"Playful words while the agent works": "Playful words while the agent works",
|
||||
"Choosing words carefully…": "Choosing words carefully…",
|
||||
"Polishing the prose…": "Polishing the prose…",
|
||||
"Drafting, redrafting…": "Drafting, redrafting…",
|
||||
"Reading between the lines…": "Reading between the lines…",
|
||||
"Skimming the source…": "Skimming the source…",
|
||||
"Nudging a semicolon…": "Nudging a semicolon…",
|
||||
"Moving code around gently…": "Moving code around gently…",
|
||||
"Tidying up…": "Tidying up…",
|
||||
"Taking out the trash…": "Taking out the trash…",
|
||||
"Pruning dead code…": "Pruning dead code…",
|
||||
"Saying goodbye…": "Saying goodbye…",
|
||||
"Rearranging the furniture…": "Rearranging the furniture…",
|
||||
"Packing boxes…": "Packing boxes…",
|
||||
"Finding a better home…": "Finding a better home…",
|
||||
"Looking under the couch…": "Looking under the couch…",
|
||||
"Searching high and low…": "Searching high and low…",
|
||||
"Pressing Enter with confidence…": "Pressing Enter with confidence…",
|
||||
"Watching the logs scroll…": "Watching the logs scroll…",
|
||||
"Waiting on the shell…": "Waiting on the shell…",
|
||||
"Waiting on the network…": "Waiting on the network…",
|
||||
"Downloading the internet…": "Downloading the internet…",
|
||||
"Following links…": "Following links…",
|
||||
"Delegating…": "Delegating…",
|
||||
"Consulting a colleague…": "Consulting a colleague…",
|
||||
"Calling in reinforcements…": "Calling in reinforcements…",
|
||||
"Holding a quick stand-up…": "Holding a quick stand-up…",
|
||||
"Working Status": "Working Status",
|
||||
"While the agent works, the line under the conversation says what it is doing. With playful words on, words for what it does take turns there instead, from the start or once it reports nothing new for a while; screen readers still hear the plain status.": "While the agent works, the line under the conversation says what it is doing. With playful words on, words for what it does take turns there instead, from the start or once it reports nothing new for a while; screen readers still hear the plain status.",
|
||||
"Start after the agent reports nothing new for": "Start after the agent reports nothing new for",
|
||||
"While the status says": "While the status says",
|
||||
"Playful words": "Playful words",
|
||||
"No playful words: the status stays factual": "No playful words: the status stays factual",
|
||||
"e.g. Reticulating splines…": "e.g. Reticulating splines…",
|
||||
"New playful word": "New playful word",
|
||||
"Restore Built-in Words": "Restore Built-in Words",
|
||||
"None — type the Engine API URL below": "None — type the Engine API URL below",
|
||||
"Open in Right Split": "Open in Right Split",
|
||||
"Enable staging area": "Enable staging area",
|
||||
@@ -2567,6 +2510,7 @@
|
||||
"Load Maven Project": "Load Maven Project",
|
||||
"Skip": "Skip",
|
||||
"Resize Markdown preview": "Resize Markdown preview",
|
||||
"Resize plugin panes": "Resize plugin panes",
|
||||
"Run a Python script or module": "Run a Python script or module",
|
||||
"Replace every occurrence of '{pattern}' with '{replacement}' in the scope? The search hit its limit, so it runs again to find the occurrences not listed.": "Replace every occurrence of '{pattern}' with '{replacement}' in the scope? The search hit its limit, so it runs again to find the occurrences not listed.",
|
||||
"Server default": "Server default",
|
||||
@@ -2750,10 +2694,18 @@
|
||||
"Cannot move a folder into itself": "Cannot move a folder into itself",
|
||||
"Already in this directory": "Already in this directory",
|
||||
"Resize left merge pane": "Resize left merge pane",
|
||||
"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"
|
||||
}
|
||||
@@ -1,4 +1,7 @@
|
||||
{
|
||||
"Inspection details": "检查详情",
|
||||
"Resize inspection panes": "调整检查窗格大小",
|
||||
"Resize inspection description": "调整检查说明窗格大小",
|
||||
"Table actions": "表数据操作",
|
||||
"Table pages": "表数据分页",
|
||||
"Problems actions": "问题操作",
|
||||
@@ -2752,6 +2755,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": "全部显示",
|
||||
@@ -3343,6 +3349,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": "没有打开的文件",
|
||||
@@ -5047,6 +5054,7 @@
|
||||
"Drop {count} commits from the current branch? Their changes are removed.": "是否从当前分支丢弃 {count} 个提交?它们的更改将被移除。",
|
||||
"Drop commit {id} “{summary}” from the current branch? Its changes are removed.": "是否从当前分支丢弃提交 {id}“{summary}”?其更改将被移除。",
|
||||
"Action for {id}": "{id} 的操作",
|
||||
"New message for {id}": "{id} 的新提交消息",
|
||||
"Rebasing {n} commit onto {onto}": "正在将 {n} 个提交变基到 {onto}",
|
||||
"Rebasing {n} commits onto {onto}": "正在将 {n} 个提交变基到 {onto}",
|
||||
"Rebasing {n} commit from the root": "正在从根变基 {n} 个提交",
|
||||
@@ -8392,56 +8400,6 @@
|
||||
"Previous Failed Test": "上一个失败的测试",
|
||||
"Next Failed Test": "下一个失败的测试",
|
||||
"Run '{name}' with Fuzzing": "使用模糊测试运行 '{name}'",
|
||||
"Untangling imports…": "正在理顺 import…",
|
||||
"Counting brackets…": "正在数括号…",
|
||||
"Herding semicolons…": "正在清点分号…",
|
||||
"Explaining it to the rubber duck…": "正在讲给小黄鸭听…",
|
||||
"Negotiating with the borrow checker…": "正在和借用检查器讲道理…",
|
||||
"Chasing a null pointer…": "正在追捕空指针…",
|
||||
"Bisecting the problem…": "正在二分排查…",
|
||||
"Reading the fine manual…": "正在认真读文档…",
|
||||
"Refactoring a hunch…": "正在重构一个直觉…",
|
||||
"Grepping the void…": "正在 grep 虚空…",
|
||||
"Garbage-collecting thoughts…": "正在回收思绪…",
|
||||
"Rebasing onto reality…": "正在变基到现实…",
|
||||
"Compiling a plan…": "正在编译计划…",
|
||||
"Walking the call stack…": "正在顺着调用栈往上爬…",
|
||||
"Warming up the compiler…": "正在预热编译器…",
|
||||
"Settling tabs versus spaces…": "正在调停 Tab 与空格之争…",
|
||||
"Caching an insight…": "正在缓存灵感…",
|
||||
"Following the breadcrumbs…": "正在顺藤摸瓜…",
|
||||
"Squinting at the diff…": "正在眯眼看 diff…",
|
||||
"Asking the linter nicely…": "正在好言相劝 linter…",
|
||||
"Measuring twice…": "正在三思而后行…",
|
||||
"Sharpening the pencils…": "正在削铅笔…",
|
||||
"Naming things…": "正在给变量起名…",
|
||||
"Invalidating a cache…": "正在让缓存失效…",
|
||||
"Choosing words carefully…": "正在斟酌用词…",
|
||||
"Polishing the prose…": "正在润色文字…",
|
||||
"Drafting, redrafting…": "正在打草稿,再打草稿…",
|
||||
"Reading between the lines…": "正在读出言外之意…",
|
||||
"Skimming the source…": "正在速读源码…",
|
||||
"Nudging a semicolon…": "正在挪动一个分号…",
|
||||
"Moving code around gently…": "正在轻轻挪动代码…",
|
||||
"Tidying up…": "正在收拾…",
|
||||
"Taking out the trash…": "正在倒垃圾…",
|
||||
"Pruning dead code…": "正在修剪死代码…",
|
||||
"Saying goodbye…": "正在挥手告别…",
|
||||
"Rearranging the furniture…": "正在重新摆放家具…",
|
||||
"Packing boxes…": "正在打包纸箱…",
|
||||
"Finding a better home…": "正在找个更好的家…",
|
||||
"Looking under the couch…": "正在沙发底下找…",
|
||||
"Searching high and low…": "正在上天入地地找…",
|
||||
"Pressing Enter with confidence…": "正在自信地按下回车…",
|
||||
"Watching the logs scroll…": "正在看日志滚动…",
|
||||
"Waiting on the shell…": "正在等 shell 回话…",
|
||||
"Waiting on the network…": "正在等网络…",
|
||||
"Downloading the internet…": "正在下载整个互联网…",
|
||||
"Following links…": "正在顺着链接走…",
|
||||
"Delegating…": "正在分派任务…",
|
||||
"Consulting a colleague…": "正在请教同事…",
|
||||
"Calling in reinforcements…": "正在呼叫增援…",
|
||||
"Holding a quick stand-up…": "正在开个简短站会…",
|
||||
"Reading…": "正在读取…",
|
||||
"Editing…": "正在编辑…",
|
||||
"Deleting…": "正在删除…",
|
||||
@@ -8451,16 +8409,6 @@
|
||||
"Thinking…": "正在思考…",
|
||||
"Writing…": "正在输出…",
|
||||
"Running a subagent…": "子 agent 正在运行…",
|
||||
"Playful words while the agent works": "agent 工作时显示趣味文字",
|
||||
"Working Status": "工作状态",
|
||||
"While the agent works, the line under the conversation says what it is doing. With playful words on, words for what it does take turns there instead, from the start or once it reports nothing new for a while; screen readers still hear the plain status.": "agent 工作时,对话下方的状态行显示它正在做什么。开启趣味文字后,这里会改为轮换显示与当前工作相关的趣味文字,可以从一开始就显示,也可以在它一段时间没有新进展后才显示;屏幕阅读器读出的仍是实际状态。",
|
||||
"Start after the agent reports nothing new for": "在 agent 无新进展超过",
|
||||
"While the status says": "当状态为",
|
||||
"Playful words": "趣味文字",
|
||||
"No playful words: the status stays factual": "没有趣味文字:状态只显示实际进展",
|
||||
"e.g. Reticulating splines…": "例如:正在网格化样条曲线…",
|
||||
"New playful word": "新的趣味文字",
|
||||
"Restore Built-in Words": "恢复内置文字",
|
||||
"None — type the Engine API URL below": "无(在下方输入 Engine API URL)",
|
||||
"Open in Right Split": "在右侧拆分中打开",
|
||||
"Enable staging area": "启用暂存区",
|
||||
@@ -8946,6 +8894,7 @@
|
||||
"This Maven project is not loaded": "此 Maven 项目尚未加载",
|
||||
"Load Maven Project": "加载 Maven 项目",
|
||||
"Resize Markdown preview": "调整 Markdown 预览宽度",
|
||||
"Resize plugin panes": "调整插件列表与详情区域大小",
|
||||
"Server default": "服务器默认值",
|
||||
"New Database": "新建数据库",
|
||||
"Owner:": "所有者:",
|
||||
@@ -9119,8 +9068,11 @@
|
||||
"Cannot move a folder into itself": "不能将文件夹移动到自身目录中",
|
||||
"Already in this directory": "已在此目录中",
|
||||
"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": "移除所有监视"
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
// @vitest-environment node
|
||||
/**
|
||||
* Selectors that make Chromium restyle whole subtrees on unrelated DOM changes. Blink checks a
|
||||
* selector whose last part is universal (`*`, or only pseudo-classes) against every element, so:
|
||||
*
|
||||
* - `x > * + *` / `x ~ *` flags every parent as having children styled by their siblings, and any
|
||||
* insertion then restyles the next sibling's whole subtree (an editor scroll inserts lines and
|
||||
* gutters every frame);
|
||||
* - `:focus *` / `:hover ::selection` makes every focus or hover change restyle the subtree of the
|
||||
* element it happens on, wherever that element is;
|
||||
* - `x:not(:focus-within) .y` makes WebKit restyle the whole window on every focus change (write the
|
||||
* default style for `x .y` and override it with `x:focus-within .y`).
|
||||
*
|
||||
* Name the element instead (`x > :not(:first-child)`, `x > .item + .item`, `x:focus .label`).
|
||||
*/
|
||||
import { readdirSync, readFileSync } from "node:fs";
|
||||
import { join, resolve } from "node:path";
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
const SRC = resolve(import.meta.dirname, "..");
|
||||
|
||||
function stylesheets(dir: string): string[] {
|
||||
return readdirSync(dir, { withFileTypes: true }).flatMap((e) => {
|
||||
const path = join(dir, e.name);
|
||||
if (e.isDirectory()) return stylesheets(path);
|
||||
return e.name.endsWith(".css") ? [path] : [];
|
||||
});
|
||||
}
|
||||
|
||||
/** A compound selector with no type, class, id or attribute: `*`, `:not(…)`, `::selection`. */
|
||||
const UNIVERSAL = String.raw`(?:\*|(?=:))(?::{1,2}[\w-]+(?:\([^)]*\))?)*`;
|
||||
const SIBLING = new RegExp(String.raw`[+~]\s*${UNIVERSAL}\s*$`);
|
||||
const STATE_DESCENDANT = new RegExp(
|
||||
String.raw`:(?:focus|focus-within|focus-visible|hover|active)[^\s>+~]*[\s>]+${UNIVERSAL}\s*$`,
|
||||
);
|
||||
const NEGATED_STATE = /:not\(:(?:focus|focus-within|focus-visible|hover|active)\)[^\s>+~]*[\s>+~]/;
|
||||
|
||||
it("no selector restyles whole subtrees on sibling insertions or focus changes", () => {
|
||||
const costly: string[] = [];
|
||||
for (const path of stylesheets(SRC)) {
|
||||
const css = readFileSync(path, "utf8").replace(/\/\*[\s\S]*?\*\//g, "");
|
||||
for (const prelude of css.matchAll(/([^{};]+)\{/g)) {
|
||||
const text = prelude[1]!.trim();
|
||||
if (text.startsWith("@")) continue;
|
||||
for (const selector of text.split(/,(?![^(]*\))/)) {
|
||||
const s = selector.trim().replace(/:global\(([^)]*)\)/g, "$1");
|
||||
// Combinators inside `:has(…)` relate other elements, not this one's ancestors.
|
||||
const outer = s.replace(/:has\((?:[^()]|\([^()]*\))*\)/g, "");
|
||||
if (SIBLING.test(s) || STATE_DESCENDANT.test(s) || NEGATED_STATE.test(outer))
|
||||
costly.push(`${path.slice(SRC.length + 1)}: ${s}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
expect(costly).toEqual([]);
|
||||
});
|
||||
@@ -58,10 +58,14 @@
|
||||
.active:hover {
|
||||
background: var(--bg-tree-selected);
|
||||
}
|
||||
/* A focusable list that lost focus shows the inactive selection, like IDEA's JList. */
|
||||
.list[tabindex="0"]:not(:focus-within) .active {
|
||||
/* A focusable list shows the inactive selection until it holds focus. Not `:not(:focus-within)`:
|
||||
WebKit then restyles the whole window on every focus change. */
|
||||
.list[tabindex="0"] .active {
|
||||
background: var(--bg-tree-selected-inactive);
|
||||
}
|
||||
.list[tabindex="0"]:focus-within .active {
|
||||
background: var(--bg-tree-selected);
|
||||
}
|
||||
.section {
|
||||
padding: 0 8px;
|
||||
color: var(--fg-muted);
|
||||
|
||||
@@ -2,11 +2,26 @@
|
||||
import { iconMarkupOrFallback, type IconName } from "./icons";
|
||||
import spinnerStyles from "./Spinner.module.css";
|
||||
|
||||
/** Parsed markup, cloned into each node: widgets rebuild the same few icons on every render. */
|
||||
const parsed = new Map<string, HTMLElement>();
|
||||
|
||||
export function iconNode(name: IconName | (string & {}), size = 16, className?: string): HTMLElement {
|
||||
const span = document.createElement("span");
|
||||
span.className = className ? `cm-openidea-icon ${className}` : "cm-openidea-icon";
|
||||
span.setAttribute("aria-hidden", "true");
|
||||
span.innerHTML = iconMarkupOrFallback(name, size);
|
||||
const markup = iconMarkupOrFallback(name, size);
|
||||
// Markup with ids is unique to this node (ids are never shared): nothing to reuse.
|
||||
if (markup.includes('id="')) {
|
||||
span.innerHTML = markup;
|
||||
return span;
|
||||
}
|
||||
let source = parsed.get(markup);
|
||||
if (!source) {
|
||||
source = document.createElement("span");
|
||||
source.innerHTML = markup;
|
||||
parsed.set(markup, source);
|
||||
}
|
||||
span.append(...Array.from(source.childNodes, (n) => n.cloneNode(true)));
|
||||
return span;
|
||||
}
|
||||
|
||||
|
||||
+21
-2
@@ -21,7 +21,7 @@
|
||||
* - Element ids (clip paths) are made unique per instance: WebKit can't resolve
|
||||
* references into `display: none` subtrees, so ids must never be shared.
|
||||
*/
|
||||
import { useId, useMemo, type CSSProperties } from "react";
|
||||
import { useId, useLayoutEffect, useMemo, useRef, type CSSProperties } from "react";
|
||||
import clsx from "clsx";
|
||||
import { create } from "zustand";
|
||||
import styles from "./icons.module.css";
|
||||
@@ -839,6 +839,20 @@ const EMPTY: Prepared = { viewBox: "0 0 16 16", html: "", hasIds: false, mono: t
|
||||
|
||||
const withIds = (p: Prepared, prefix: string) => (p.hasIds ? p.html.replace(/__ID__/g, prefix) : p.html);
|
||||
|
||||
/** Parsed markup by source, cloned into each icon: a tree or list mounts dozens of the same icon
|
||||
* per frame, and parsing `innerHTML` for each one costs more than the rest of the row. */
|
||||
const parsed = new Map<string, SVGSVGElement>();
|
||||
|
||||
function fillIcon(svg: SVGSVGElement, html: string, shared: boolean) {
|
||||
let source = shared ? parsed.get(html) : undefined;
|
||||
if (!source) {
|
||||
source = document.createElementNS("http://www.w3.org/2000/svg", "svg");
|
||||
source.innerHTML = html;
|
||||
if (shared) parsed.set(html, source);
|
||||
}
|
||||
svg.replaceChildren(...Array.from(source.childNodes, (n) => n.cloneNode(true)));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** Largest `data:` image accepted as an icon (an avatar or a status badge a plugin fetched). */
|
||||
@@ -887,11 +901,17 @@ function SvgIcon({ name, size = 16, className, style, label }: IconProps) {
|
||||
const path = iconPath(name);
|
||||
const p = (path && prepare(path, size >= 18)) || prepare(ICONS.file, size >= 18) || EMPTY;
|
||||
const html = useMemo(() => withIds(p, `i${uid.replace(/[^a-zA-Z0-9_-]/g, "")}-`), [p, uid]);
|
||||
const ref = useRef<SVGSVGElement>(null);
|
||||
useLayoutEffect(() => {
|
||||
// Markup with per-instance ids is unique to this icon: nothing to share.
|
||||
if (ref.current) fillIcon(ref.current, html, !p.hasIds);
|
||||
}, [html, p.hasIds]);
|
||||
if (!path && name.startsWith("symbol-")) {
|
||||
return <SymbolBadge kind={name.slice(7)} className={className} style={style} />;
|
||||
}
|
||||
return (
|
||||
<svg
|
||||
ref={ref}
|
||||
className={clsx(styles.icon, p.mono && styles.mono, className)}
|
||||
style={style}
|
||||
width={size}
|
||||
@@ -902,7 +922,6 @@ function SvgIcon({ name, size = 16, className, style, label }: IconProps) {
|
||||
role={label ? "img" : undefined}
|
||||
aria-label={label}
|
||||
focusable="false"
|
||||
dangerouslySetInnerHTML={{ __html: html }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -42,6 +42,7 @@ export { selectableText, copyMenuFor, copyText } from "./selectableText";
|
||||
export { selectReadingPane, useSelectionBoundary } from "./useSelectionBoundary";
|
||||
export { lockDragCursor, type DragCursor } from "./dragCursor";
|
||||
export { useSanitizedField } from "./useSanitizedField";
|
||||
export { useFrozenWhileWindowResizes } from "./useFrozenWhileWindowResizes";
|
||||
export * from "./rowSelection";
|
||||
export * from "./LogPane";
|
||||
export * from "./Chip";
|
||||
@@ -0,0 +1,52 @@
|
||||
import { act, render } from "@testing-library/react";
|
||||
import { useRef } from "react";
|
||||
import { afterEach, beforeEach, expect, it, vi } from "vitest";
|
||||
import { WINDOW_RESIZE_SETTLE_MS, useFrozenWhileWindowResizes } from "./useFrozenWhileWindowResizes";
|
||||
|
||||
function Frozen() {
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
useFrozenWhileWindowResizes(ref);
|
||||
return (
|
||||
<div data-testid="parent">
|
||||
<div ref={ref} data-testid="view" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
beforeEach(() => vi.useFakeTimers());
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
it("keeps the view at its size while the window resizes and releases it once the drag pauses", () => {
|
||||
const { getByTestId } = render(<Frozen />);
|
||||
const view = getByTestId("view");
|
||||
const parent = getByTestId("parent");
|
||||
view.getBoundingClientRect = () => ({ width: 300, height: 120 }) as DOMRect;
|
||||
|
||||
act(() => void window.dispatchEvent(new Event("resize")));
|
||||
expect(view.style.width).toBe("300px");
|
||||
expect(view.style.height).toBe("120px");
|
||||
expect(view.style.flexGrow).toBe("0");
|
||||
expect(parent.style.overflow).toBe("hidden");
|
||||
|
||||
// Still dragging: the size taken at the start stays.
|
||||
view.getBoundingClientRect = () => ({ width: 200, height: 80 }) as DOMRect;
|
||||
act(() => vi.advanceTimersByTime(WINDOW_RESIZE_SETTLE_MS - 1));
|
||||
act(() => void window.dispatchEvent(new Event("resize")));
|
||||
act(() => vi.advanceTimersByTime(WINDOW_RESIZE_SETTLE_MS - 1));
|
||||
expect(view.style.width).toBe("300px");
|
||||
|
||||
act(() => vi.advanceTimersByTime(1));
|
||||
expect(view.style.width).toBe("");
|
||||
expect(view.style.height).toBe("");
|
||||
expect(view.style.flex).toBe("");
|
||||
expect(parent.style.overflow).toBe("");
|
||||
});
|
||||
|
||||
it("releases the view when it unmounts mid-drag", () => {
|
||||
const { getByTestId, unmount } = render(<Frozen />);
|
||||
const parent = getByTestId("parent");
|
||||
act(() => void window.dispatchEvent(new Event("resize")));
|
||||
expect(parent.style.overflow).toBe("hidden");
|
||||
unmount();
|
||||
expect(parent.style.overflow).toBe("");
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
import { useEffect, type RefObject } from "react";
|
||||
|
||||
/** How long the window must keep its size before a frozen element follows it. */
|
||||
export const WINDOW_RESIZE_SETTLE_MS = 150;
|
||||
|
||||
/**
|
||||
* While the window is being resized, keeps the element at the size it had when the drag started,
|
||||
* on its own layer and clipped by its parent, then lets it take the new size once the drag pauses.
|
||||
* For dense views that WebKit cannot lay out and paint at every step of a live resize: their pixels
|
||||
* are moved instead of redrawn, so the rest of the window keeps up with the pointer.
|
||||
*/
|
||||
export function useFrozenWhileWindowResizes(ref: RefObject<HTMLElement | null>): void {
|
||||
useEffect(() => {
|
||||
let frozen: { el: HTMLElement; parent: HTMLElement | null; parentOverflow: string } | null = null;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const release = () => {
|
||||
clearTimeout(timer);
|
||||
if (!frozen) return;
|
||||
const { el, parent, parentOverflow } = frozen;
|
||||
for (const p of ["width", "height", "flex", "will-change"]) el.style.removeProperty(p);
|
||||
if (parent) parent.style.overflow = parentOverflow;
|
||||
frozen = null;
|
||||
};
|
||||
const onResize = () => {
|
||||
const el = ref.current;
|
||||
if (!frozen && el?.isConnected) {
|
||||
const { width, height } = el.getBoundingClientRect();
|
||||
const parent = el.parentElement;
|
||||
frozen = { el, parent, parentOverflow: parent?.style.overflow ?? "" };
|
||||
el.style.setProperty("width", `${width}px`, "important");
|
||||
el.style.setProperty("height", `${height}px`, "important");
|
||||
el.style.setProperty("flex", "none", "important");
|
||||
el.style.setProperty("will-change", "transform");
|
||||
if (parent) parent.style.overflow = "hidden";
|
||||
}
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(release, WINDOW_RESIZE_SETTLE_MS);
|
||||
};
|
||||
window.addEventListener("resize", onResize);
|
||||
return () => {
|
||||
window.removeEventListener("resize", onResize);
|
||||
release();
|
||||
};
|
||||
}, [ref]);
|
||||
}
|
||||
@@ -58,8 +58,23 @@ export function mountWindowRoot(View: ComponentType, { prefetchLazy = false }: {
|
||||
function App() {
|
||||
useEffect(() => {
|
||||
hideSplash();
|
||||
if (!prefetchLazy) return;
|
||||
// The first file opened would otherwise also build the editor setup cold.
|
||||
const warm = () => {
|
||||
if (!document.querySelector(".cm-editor"))
|
||||
void import("./editor/core/cm/prewarm").then((m) => m.prewarmEditor());
|
||||
};
|
||||
const idle =
|
||||
typeof requestIdleCallback === "function"
|
||||
? requestIdleCallback(warm, { timeout: 2000 })
|
||||
: window.setTimeout(warm, 500);
|
||||
// Views split out of the start-up bundle load in the background once the UI is up.
|
||||
if (prefetchLazy) return prefetchLazyComponents();
|
||||
const stopPrefetch = prefetchLazyComponents();
|
||||
return () => {
|
||||
if (typeof cancelIdleCallback === "function") cancelIdleCallback(idle);
|
||||
else window.clearTimeout(idle);
|
||||
stopPrefetch();
|
||||
};
|
||||
}, []);
|
||||
return <View />;
|
||||
}
|
||||
|
||||
Reference in new issue
Заблокувати користувача