mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-23 08:49:33 -10:00
Compare commits
64
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
59b71295b2 | ||
|
|
5eff75cab5 | ||
|
|
aec1382e79 | ||
|
|
999d84b189 | ||
|
|
9fda9b92c2 | ||
|
|
261eb03009 | ||
|
|
db8b553364 | ||
|
|
2494b2efdf | ||
|
|
d78ce7ec66 | ||
|
|
9df9499bf5 | ||
|
|
d4b5581441 | ||
|
|
d96060f08b | ||
|
|
507258daec | ||
|
|
dae402b966 | ||
|
|
39e803b8f9 | ||
|
|
d6b56856d2 | ||
|
|
8a84e8f473 | ||
|
|
f31aa29f3e | ||
|
|
639e4b3df9 | ||
|
|
01b9908898 | ||
|
|
7f201ed87d | ||
|
|
85344b86b5 | ||
|
|
12e85a7c1b | ||
|
|
861acabf77 | ||
|
|
96395c979f | ||
|
|
e9f768d8b5 | ||
|
|
d15abe54e2 | ||
|
|
b501f51526 | ||
|
|
50cd478773 | ||
|
|
2c63f0eb22 | ||
|
|
ed1730f273 | ||
|
|
d6d0cc7926 | ||
|
|
a21de32077 | ||
|
|
546ff9f314 | ||
|
|
a144208170 | ||
|
|
fda2d2ff69 | ||
|
|
0fdf37f1bf | ||
|
|
5c592bbc86 | ||
|
|
819ccb8bb5 | ||
|
|
ae893f059f | ||
|
|
fb2f567d5b | ||
|
|
22af0931dd | ||
|
|
4af81625b1 | ||
|
|
f3d18c0eb8 | ||
|
|
e662c915a2 | ||
|
|
f57a17ec14 | ||
|
|
0b8d9135aa | ||
|
|
290ef6956e | ||
|
|
8a4b8f45b4 | ||
|
|
31b265cb41 | ||
|
|
a6a05caa2e | ||
|
|
4690463c53 | ||
|
|
8200ce8b5e | ||
|
|
b524f738e5 | ||
|
|
1f871dc1c2 | ||
|
|
ceb3cef1af | ||
|
|
735a0157c1 | ||
|
|
82f26202ed | ||
|
|
a90a9b20e3 | ||
|
|
aad701ba16 | ||
|
|
46d4036038 | ||
|
|
19859b4ae2 | ||
|
|
f3f05f8b15 | ||
|
|
b0417c83f4 |
No files matched your search
Binary file not shown.
|
Before Width: | Height: | Size: 160 KiB After Width: | Height: | Size: 138 KiB |
Generated
+2
-2
@@ -1104,9 +1104,9 @@ checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b"
|
||||
|
||||
[[package]]
|
||||
name = "cookie"
|
||||
version = "0.18.2"
|
||||
version = "0.18.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1a373e3602691c3cdea496d2f0ee5935151e6168fe87739483c463db1b2f2f87"
|
||||
checksum = "d55f2d6c30eeec7d5c6f98bd4395d4abb1895629eab97ee6522d340623615f8a"
|
||||
dependencies = [
|
||||
"time",
|
||||
"version_check",
|
||||
|
||||
@@ -536,6 +536,9 @@ pub enum AgentEntry {
|
||||
kind: String,
|
||||
status: AgentToolStatus,
|
||||
locations: Vec<IpcPath>,
|
||||
/// Images returned by the tool, kept separately from its truncated text.
|
||||
#[serde(default)]
|
||||
images: Vec<AgentImage>,
|
||||
/// Text the tool reported (command output…), truncated.
|
||||
output: Option<String>,
|
||||
diffs: Vec<AgentToolDiff>,
|
||||
|
||||
@@ -1007,11 +1007,16 @@ impl Session {
|
||||
let mut updates = Vec::new();
|
||||
let mut finished = None;
|
||||
let mut read_title = false;
|
||||
let mut refresh_usage = false;
|
||||
{
|
||||
let mut st = self.st.lock();
|
||||
let st = &mut *st;
|
||||
match kind {
|
||||
"system" => match msg.get("subtype").and_then(Value::as_str) {
|
||||
Some("compact_boundary") => {
|
||||
refresh_usage = msg.pointer("/compact_metadata/post_tokens").is_none_or(Value::is_null);
|
||||
updates.extend(st.tr.on_message(&msg));
|
||||
}
|
||||
Some("init") => {
|
||||
st.terminal_only = strings(msg.get("terminal_slash_commands"));
|
||||
}
|
||||
@@ -1115,6 +1120,31 @@ impl Session {
|
||||
if read_title {
|
||||
self.read_title();
|
||||
}
|
||||
if refresh_usage {
|
||||
self.refresh_usage();
|
||||
}
|
||||
}
|
||||
|
||||
/// Sends what the context holds after a compaction that didn't report it, as Claude Code
|
||||
/// counts it (`get_context_usage`); until then the meter would show the count from before.
|
||||
fn refresh_usage(self: &Arc<Self>) {
|
||||
let me = self.clone();
|
||||
tokio::spawn(async move {
|
||||
let Some(proc) = me.st.lock().proc.clone() else { return };
|
||||
let usage = match proc.control(json!({ "subtype": "get_context_usage" })).await {
|
||||
Ok(usage) => usage,
|
||||
Err(e) => {
|
||||
tracing::debug!("reading claude context usage after compaction: {e}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let n = |k: &str| usage.get(k).and_then(Value::as_u64);
|
||||
let (Some(used), Some(size)) = (n("totalTokens"), n("maxTokens").filter(|m| *m > 0)) else { return };
|
||||
let update = me.st.lock().tr.on_context_usage(used, size);
|
||||
if let Some(shim) = me.shim() {
|
||||
shim.notify(vec![update]);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Sends the session's title once it has one: the one in its transcript, or else one
|
||||
|
||||
@@ -531,6 +531,38 @@ async fn sessions_without_a_title_get_one_generated() {
|
||||
assert_eq!(request["request"]["persist"], true);
|
||||
}
|
||||
|
||||
/// A compaction that doesn't report what the context holds now (no `post_tokens`): the
|
||||
/// driver asks Claude Code, and the meter shows that instead of the count from before.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_compaction_without_its_token_count_reads_the_context_usage() {
|
||||
let mut processes = load_fixture("simple");
|
||||
processes[0].extend([
|
||||
Frame::Cli(json!({"type": "system", "subtype": "compact_boundary",
|
||||
"compact_metadata": {"trigger": "manual", "pre_tokens": 120000}})),
|
||||
Frame::Shim(json!({"type": "control_request", "request_id": "req_3",
|
||||
"request": {"subtype": "get_context_usage"}})),
|
||||
Frame::Cli(json!({"type": "control_response", "response": {"subtype": "success", "request_id": "req_3",
|
||||
"response": {"categories": [], "totalTokens": 4200, "maxTokens": 200000, "model": "claude"}}})),
|
||||
]);
|
||||
let cli = replay_cli(processes);
|
||||
let (config, cwd) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
|
||||
let cwd_path = std::fs::canonicalize(cwd.path()).unwrap();
|
||||
let h =
|
||||
Harness::connect(cli.clone(), config.path().into(), config.path().join("pending"), cwd_path, Vec::new()).await;
|
||||
let session = h.new_session().await;
|
||||
h.prompt(&session, "Reply with exactly: hello there").await.unwrap();
|
||||
let mut usage = Vec::new();
|
||||
for _ in 0..100 {
|
||||
usage = h.updates(&session, "usage_update");
|
||||
if usage.last().is_some_and(|u| u["used"] == 4200) {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
assert!(cli.errors.lock().is_empty(), "{:?}", cli.errors.lock());
|
||||
assert_eq!(usage.last().map(|u| (u["used"].clone(), u["size"].clone())), Some((json!(4200), json!(200000))));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn replay_multi_turn() {
|
||||
let r = replay("multi_turn").await;
|
||||
@@ -1098,6 +1130,24 @@ fn streamed_text_is_not_sent_twice() {
|
||||
assert_eq!(usage[0].update, json!({"sessionUpdate": "usage_update", "used": 15, "size": 1000}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_compaction_replaces_the_context_usage() {
|
||||
let mut t = Translator::new("s", PathBuf::from("/w"), true);
|
||||
let assistant = json!({"type": "assistant", "parent_tool_use_id": null,
|
||||
"message": {"id": "m1", "model": "x", "content": [], "usage": {"input_tokens": 900, "output_tokens": 50}}});
|
||||
t.on_message(&assistant);
|
||||
let result = json!({"modelUsage": {"x": {"contextWindow": 1000}}});
|
||||
assert_eq!(t.on_result(&result)[0].update["used"], 950);
|
||||
let boundary = |meta: Value| json!({"type": "system", "subtype": "compact_boundary", "compact_metadata": meta});
|
||||
let out = t.on_message(&boundary(json!({"trigger": "manual", "pre_tokens": 950, "post_tokens": 120})));
|
||||
assert_eq!(out[0].update, json!({"sessionUpdate": "usage_update", "used": 120, "size": 1000}));
|
||||
// The `/compact` turn's result reports what compaction left, not the count from before.
|
||||
assert_eq!(t.on_result(&result)[0].update["used"], 120);
|
||||
// Without `post_tokens` nothing is known yet (the driver asks): the stale count stays out.
|
||||
assert!(t.on_message(&boundary(json!({"trigger": "auto", "pre_tokens": 950}))).is_empty());
|
||||
assert!(t.on_result(&result).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rate_limits_and_cost() {
|
||||
let mut t = Translator::new("s", PathBuf::from("/w"), false);
|
||||
|
||||
@@ -144,6 +144,22 @@ pub(super) fn result_fields(name: &str, input: &Value, block: &Value, structured
|
||||
content.push(text(&t));
|
||||
}
|
||||
}
|
||||
if let Some(blocks) = block.get("content").and_then(Value::as_array) {
|
||||
for block in blocks {
|
||||
if block.get("type").and_then(Value::as_str) != Some("image") {
|
||||
continue;
|
||||
}
|
||||
let Some(source) = block.get("source") else { continue };
|
||||
if source.get("type").and_then(Value::as_str) != Some("base64") {
|
||||
continue;
|
||||
}
|
||||
let data = source.get("data").and_then(Value::as_str).unwrap_or_default();
|
||||
let mime = source.get("media_type").and_then(Value::as_str).unwrap_or_default();
|
||||
if !data.is_empty() && mime.starts_with("image/") {
|
||||
content.push(json!({"type": "content", "content": {"type": "image", "mimeType": mime, "data": data}}));
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = json!({ "status": if failed { "failed" } else { "completed" } });
|
||||
if !content.is_empty() {
|
||||
out["content"] = Value::Array(content);
|
||||
@@ -230,6 +246,43 @@ mod tests {
|
||||
assert_eq!(call_fields("WebSearch", &json!({"query": "q"}), cwd)["kind"], "fetch");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_tool_results_keep_text_and_inline_images() {
|
||||
let result = result_fields(
|
||||
"Read",
|
||||
&json!({"file_path": "/w/preview.png"}),
|
||||
&json!({"content": [
|
||||
{"type": "text", "text": "Preview ready"},
|
||||
{"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "aW1hZ2U="}}
|
||||
]}),
|
||||
None,
|
||||
);
|
||||
assert_eq!(result["status"], "completed");
|
||||
assert_eq!(
|
||||
result["content"],
|
||||
json!([
|
||||
text("Preview ready"),
|
||||
{"type": "content", "content": {"type": "image", "mimeType": "image/png", "data": "aW1hZ2U="}}
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_shell_tool_images_keep_fallback_error_text() {
|
||||
let result = result_fields(
|
||||
"Bash",
|
||||
&json!({}),
|
||||
&json!({"is_error": true, "content": [
|
||||
{"type": "text", "text": "Preview command failed"},
|
||||
{"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "aW1hZ2U="}}
|
||||
]}),
|
||||
Some(&json!({"stdout": "", "stderr": ""})),
|
||||
);
|
||||
assert_eq!(result["status"], "failed");
|
||||
assert_eq!(result["content"][0], text("Preview command failed"));
|
||||
assert_eq!(result["content"][1]["content"]["type"], "image");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn results() {
|
||||
let input = json!({"file_path": "/w/n.txt", "content": "two"});
|
||||
|
||||
@@ -458,6 +458,13 @@ impl Translator {
|
||||
let last = self.children.get(&tool_use).map(|c| c.last_text.clone()).filter(|t| !t.is_empty());
|
||||
self.finish_child(&tool_use, stop, last.or(summary))
|
||||
}
|
||||
// Compaction replaced the conversation with its summary: the context now holds
|
||||
// `post_tokens`. Without it the stale count must not come back with the result;
|
||||
// the driver asks Claude Code instead (`Session::refresh_usage`).
|
||||
Some("compact_boundary") => {
|
||||
self.used = msg.pointer("/compact_metadata/post_tokens").and_then(Value::as_u64);
|
||||
self.usage_update().into_iter().collect()
|
||||
}
|
||||
// A turn's background tasks (`run_in_background`) outlive it: the task keeps
|
||||
// the list and stays up while it isn't empty (see `Task::release_when_idle`).
|
||||
Some("background_tasks_changed") => {
|
||||
@@ -561,6 +568,16 @@ impl Translator {
|
||||
self.usage_update().into_iter().collect()
|
||||
}
|
||||
|
||||
/// The context usage Claude Code reports (`get_context_usage`), as a usage update.
|
||||
pub fn on_context_usage(&mut self, used: u64, size: u64) -> Update {
|
||||
self.used = Some(used);
|
||||
let mut update = json!({ "sessionUpdate": "usage_update", "used": used, "size": size });
|
||||
if let Some(amount) = self.cost_usd {
|
||||
update["cost"] = json!({ "amount": amount, "currency": "USD" });
|
||||
}
|
||||
Update { session: self.root.clone(), update }
|
||||
}
|
||||
|
||||
fn usage_update(&self) -> Option<Update> {
|
||||
let used = self.used?;
|
||||
let size = self
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Folds ACP `session/update` notifications into a task's entries.
|
||||
|
||||
use crate::model::{AgentEntry, AgentPlanItem, AgentSubagentStatus, AgentToolDiff, AgentToolStatus};
|
||||
use crate::model::{AgentEntry, AgentImage, AgentPlanItem, AgentSubagentStatus, AgentToolDiff, AgentToolStatus};
|
||||
use ide_core::IpcPath;
|
||||
use serde_json::Value;
|
||||
use std::collections::HashMap;
|
||||
@@ -84,6 +84,7 @@ impl Timeline {
|
||||
status: tool_status(update.get("status")).unwrap_or(AgentToolStatus::Pending),
|
||||
locations: locations(update.get("locations")),
|
||||
output: None,
|
||||
images: Vec::new(),
|
||||
diffs: Vec::new(),
|
||||
started_ms: Some(crate::now_ms()),
|
||||
ended_ms: None,
|
||||
@@ -150,7 +151,7 @@ impl Timeline {
|
||||
}
|
||||
|
||||
fn merge_tool(&mut self, index: usize, update: &Value) {
|
||||
let AgentEntry::Tool { title, kind, status, locations: locs, output, diffs, ended_ms, .. } =
|
||||
let AgentEntry::Tool { title, kind, status, locations: locs, output, images, diffs, ended_ms, .. } =
|
||||
&mut self.entries[index]
|
||||
else {
|
||||
return;
|
||||
@@ -173,10 +174,20 @@ impl Timeline {
|
||||
let Some(content) = update.get("content").and_then(Value::as_array) else { return };
|
||||
let mut text = String::new();
|
||||
let mut new_diffs = Vec::new();
|
||||
let mut new_images = Vec::new();
|
||||
for item in content {
|
||||
match item.get("type").and_then(Value::as_str) {
|
||||
Some("content") => {
|
||||
if let Some(t) = content_text(item.get("content")) {
|
||||
let content = item.get("content");
|
||||
if let Some(image) = content.filter(|c| c.get("type").and_then(Value::as_str) == Some("image"))
|
||||
&& let (Some(data), Some(mime)) =
|
||||
(image.get("data").and_then(Value::as_str), image.get("mimeType").and_then(Value::as_str))
|
||||
&& !data.is_empty()
|
||||
&& mime.starts_with("image/")
|
||||
{
|
||||
new_images.push(AgentImage { mime_type: mime.into(), data: data.into(), name: None });
|
||||
}
|
||||
if let Some(t) = content_text(content) {
|
||||
if !text.is_empty() {
|
||||
text.push('\n');
|
||||
}
|
||||
@@ -203,6 +214,9 @@ impl Timeline {
|
||||
if !new_diffs.is_empty() {
|
||||
*diffs = new_diffs;
|
||||
}
|
||||
if !new_images.is_empty() {
|
||||
*images = new_images;
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds or updates the card of subagent `id` from its `subagent_update`; returns the
|
||||
@@ -439,6 +453,31 @@ mod tests {
|
||||
assert!(matches!(&t.entries[0], AgentEntry::Question { chosen: Some(answer), .. } if answer == "One"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tool_images_survive_updates_text_truncation_and_serialization() {
|
||||
use base64::Engine;
|
||||
let mut t = Timeline::default();
|
||||
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "preview", "title": "Render", "kind": "execute"}));
|
||||
let mut old = serde_json::to_value(&t.entries[0]).unwrap();
|
||||
old.as_object_mut().unwrap().remove("images");
|
||||
let legacy: AgentEntry = serde_json::from_value(old).unwrap();
|
||||
assert!(matches!(legacy, AgentEntry::Tool { images, .. } if images.is_empty()));
|
||||
let data = base64::engine::general_purpose::STANDARD.encode(vec![0; MAX_OUTPUT]);
|
||||
let update = json!({"sessionUpdate": "tool_call_update", "toolCallId": "preview", "content": [
|
||||
{"type": "content", "content": {"type": "text", "text": "x".repeat(MAX_OUTPUT + 100)}},
|
||||
{"type": "content", "content": {"type": "image", "mimeType": "image/png", "data": data}}
|
||||
]});
|
||||
t.apply(&update);
|
||||
t.apply(&update);
|
||||
t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "preview", "status": "completed"}));
|
||||
let AgentEntry::Tool { images, output, status, .. } = &t.entries[0] else { panic!() };
|
||||
assert_eq!(images, &vec![AgentImage { mime_type: "image/png".into(), data, name: None }]);
|
||||
assert!(output.as_ref().unwrap().len() < MAX_OUTPUT + 100);
|
||||
assert_eq!(*status, AgentToolStatus::Completed);
|
||||
let saved = serde_json::to_string(&t.entries[0]).unwrap();
|
||||
assert_eq!(serde_json::from_str::<AgentEntry>(&saved).unwrap(), t.entries[0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chunks_merge_into_one_message_until_another_entry_comes() {
|
||||
let mut t = Timeline::default();
|
||||
|
||||
@@ -488,7 +488,7 @@ async fn find_java_module(call: &Call, main: &str) -> IdeResult<Option<String>>
|
||||
/// (compile errors are added to `errors`). Other configurations are returned as they are.
|
||||
async fn resolve_jvm_application(
|
||||
call: &Call,
|
||||
config: RunConfig,
|
||||
mut config: RunConfig,
|
||||
errors: &mut BuildErrors,
|
||||
) -> IdeResult<Result<RunConfig, String>> {
|
||||
if !JVM_APPLICATION_KINDS.contains(&config.kind.as_str()) {
|
||||
@@ -544,6 +544,7 @@ async fn resolve_jvm_application(
|
||||
(Some(exec), "java") => exec.clone(),
|
||||
_ => config.command.clone(),
|
||||
};
|
||||
config.extras.module = Some(module);
|
||||
Ok(Ok(RunConfig { command, args, ..config }))
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Maven / Gradle tool windows (the build model and its background sync) and
|
||||
//! Build › Build Project (compiling with the project's build system).
|
||||
mod workspace;
|
||||
pub(super) mod workspace;
|
||||
|
||||
use super::dependencies::{MavenCentralArtifacts, MavenCentralGroups, MavenCentralVersions};
|
||||
use crate::ops::Channel;
|
||||
@@ -181,7 +181,7 @@ fn prepare_plan(mut plan: compile::BuildPlan, root: &Path, settings: &Settings)
|
||||
|
||||
/// `model` building with the Maven profiles of the last sync (`-P`), as Maven runs from
|
||||
/// the tool window do.
|
||||
fn with_profiles(mut model: BuildModel, cache: &Path) -> BuildModel {
|
||||
pub(super) fn with_profiles(mut model: BuildModel, cache: &Path) -> BuildModel {
|
||||
let profiles = ide_build::maven_profiles(cache);
|
||||
if let (Some(m), false) = (&mut model.maven, profiles.is_empty()) {
|
||||
for p in &mut m.projects {
|
||||
@@ -952,16 +952,18 @@ pub async fn build_run(
|
||||
items: Vec::new(),
|
||||
});
|
||||
}
|
||||
let mut launch_caches = Vec::new();
|
||||
let plan = if let Some(id) = cmake {
|
||||
launch_caches.push(cache.clone());
|
||||
let configs = super::run::project_configs(&root, &settings, &config_dir)?;
|
||||
cmake_plan(&root, kind, &configs, &id)?
|
||||
} else if let Some(workspace) = ide_workspace::workspace::Workspace::load(&root)? {
|
||||
let mut combined: Option<compile::BuildPlan> = None;
|
||||
for member in workspace.projects.iter().filter(|p| file.as_ref().is_none_or(|f| f.starts_with(p))) {
|
||||
let settings = ide_workspace::SettingsStore::load(&config_dir, Some(member)).effective();
|
||||
let member_cache =
|
||||
if member == &root { cache.clone() } else { cache.join(crate::project::project_key(member)) };
|
||||
let member_cache = workspace::cache_at(&root, &cache, member);
|
||||
let model = with_profiles(load(member, &member_cache, &settings), &member_cache);
|
||||
launch_caches.push(member_cache);
|
||||
let plan = prepare_plan(
|
||||
compile::plan(
|
||||
member,
|
||||
@@ -985,6 +987,7 @@ pub async fn build_run(
|
||||
plan
|
||||
} else {
|
||||
let model = with_profiles(load(&root, &cache, &settings), &cache);
|
||||
launch_caches.push(cache.clone());
|
||||
match compile::plan(
|
||||
&root,
|
||||
&model,
|
||||
@@ -1007,7 +1010,9 @@ pub async fn build_run(
|
||||
});
|
||||
if kind == BuildKind::Rebuild {
|
||||
// The clean removed outputs that earlier launch snapshots still hold.
|
||||
launch_project.java_launch_snapshots.lock().forget_reusable_snapshots();
|
||||
for cache in launch_caches {
|
||||
launch_project.java_launches.for_cache(&cache).snapshots.lock().forget_reusable_snapshots();
|
||||
}
|
||||
}
|
||||
let result = result?;
|
||||
if result.success && single && kind == BuildKind::Build {
|
||||
|
||||
@@ -1,12 +1,33 @@
|
||||
use super::*;
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub(super) struct Scope {
|
||||
pub(in crate::ops) struct Scope {
|
||||
pub root: PathBuf,
|
||||
pub cache: PathBuf,
|
||||
pub settings: Settings,
|
||||
}
|
||||
|
||||
pub(in crate::ops) fn scope_for(project: &Project, path: &Path) -> IdeResult<Scope> {
|
||||
let workspace = ide_workspace::workspace::Workspace::load(&project.root)?;
|
||||
let root = workspace
|
||||
.as_ref()
|
||||
.and_then(|w| w.projects.iter().filter(|p| path.starts_with(p)).max_by_key(|p| p.components().count()))
|
||||
.unwrap_or(&project.root);
|
||||
Ok(Scope {
|
||||
cache: cache_at(&project.root, &project.build_cache_dir(), root),
|
||||
settings: if root == &project.root {
|
||||
project.settings.effective()
|
||||
} else {
|
||||
project.settings.for_project(root).effective()
|
||||
},
|
||||
root: root.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn cache_at(window_root: &Path, cache: &Path, root: &Path) -> PathBuf {
|
||||
if root == window_root { cache.to_owned() } else { cache.join(crate::project::project_key(root)) }
|
||||
}
|
||||
|
||||
pub(super) fn scopes(project: &Project, config: &Path) -> IdeResult<Vec<Scope>> {
|
||||
scopes_at(&project.root, &project.build_cache_dir(), config, project.settings.effective())
|
||||
}
|
||||
@@ -19,11 +40,7 @@ fn scopes_at(root: &Path, cache: &Path, config: &Path, settings: Settings) -> Id
|
||||
.into_iter()
|
||||
.filter(|p| p.is_dir())
|
||||
.map(|root| Scope {
|
||||
cache: if root == window_root {
|
||||
cache.to_owned()
|
||||
} else {
|
||||
cache.join(crate::project::project_key(&root))
|
||||
},
|
||||
cache: cache_at(window_root, cache, &root),
|
||||
settings: ide_workspace::SettingsStore::load(config, Some(&root)).effective(),
|
||||
root,
|
||||
})
|
||||
|
||||
@@ -228,6 +228,15 @@ pub fn fs_create_dir(path: PathBuf) -> IdeResult<()> {
|
||||
ide_vfs::create_dir(&path)
|
||||
}
|
||||
|
||||
/// The scratch files' folder of this host (`<data dir>/scratches`), created. A remote window
|
||||
/// keeps its scratches on the server, where its file commands run.
|
||||
#[command(trust = always)]
|
||||
pub fn fs_scratches_dir(host: &Host) -> IdeResult<ide_core::IpcPath> {
|
||||
let dir = host.data_dir.join("scratches");
|
||||
std::fs::create_dir_all(&dir)?;
|
||||
Ok(dir.into())
|
||||
}
|
||||
|
||||
/// Toggle Read-only Attribute: sets the writable bit (and the open document's
|
||||
/// state). Returns whether the file is read-only now.
|
||||
#[command(trust = always)]
|
||||
@@ -383,6 +392,7 @@ ide_command::domain!(
|
||||
fs_read_dir,
|
||||
fs_read_text,
|
||||
fs_rename,
|
||||
fs_scratches_dir,
|
||||
fs_set_writable,
|
||||
fs_synchronize_directories,
|
||||
fs_undo_delete,
|
||||
|
||||
@@ -4,7 +4,7 @@ pub(crate) mod cache;
|
||||
use crate::Host;
|
||||
use ide_command::command;
|
||||
|
||||
use super::build::load;
|
||||
use super::build::{load, with_profiles, workspace};
|
||||
use ide_build::BuildModel;
|
||||
use ide_build::compile;
|
||||
use ide_core::error::ErrorKind;
|
||||
@@ -46,37 +46,44 @@ pub(crate) async fn resolve_launch(
|
||||
) -> IdeResult<JavaLaunchInfo> {
|
||||
let started = std::time::Instant::now();
|
||||
let project = host.project(window)?;
|
||||
let module = project.root.join(module);
|
||||
let module = ide_core::project_roots::resolve(&project.root, &module);
|
||||
let scope = {
|
||||
let (project, module) = (project.clone(), module.clone());
|
||||
tokio::task::spawn_blocking(move || workspace::scope_for(&project, &module))
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))??
|
||||
};
|
||||
if !project.lsp.java_served_by_jdtls(&module) {
|
||||
return resolve_launch_without_jdtls(host, &project, module, test, policy, cancel).await;
|
||||
return resolve_launch_without_jdtls(host, &project, module, scope, test, policy, cancel).await;
|
||||
}
|
||||
let waiting = project.java_launches_waiting.add(module.clone(), test, policy);
|
||||
let settings = project.settings.effective();
|
||||
let scope = std::sync::Arc::new(scope);
|
||||
let launches = project.java_launches.for_cache(&scope.cache);
|
||||
let waiting = launches.waiting.add(module.clone(), test, policy);
|
||||
let prefer_maven = scope.settings.languages.java.maven.delegate_build;
|
||||
// A launch builds incrementally unless the configuration asks for Rebuild or NoBuild.
|
||||
let build = policy != BuildPolicy::NoBuild;
|
||||
let full = policy == BuildPolicy::Rebuild;
|
||||
let build_kind = if full { compile::BuildKind::Rebuild } else { compile::BuildKind::Build };
|
||||
let (model, external, mut delegated, prefer_maven, is_maven) = {
|
||||
let project = project.clone();
|
||||
let settings = settings.clone();
|
||||
let (model, external, mut delegated, is_maven) = {
|
||||
let scope = scope.clone();
|
||||
let launches = launches.clone();
|
||||
let module = module.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
project.java_launch_snapshots.lock().initialize();
|
||||
let model = load(&project.root, &project.build_cache_dir(), &settings);
|
||||
let non_java = build && compile::launch_has_non_java_sources(&project.root, &model, &module, test);
|
||||
let is_maven =
|
||||
model.maven.as_ref().is_some_and(|m| m.projects.iter().any(|p| project.root.join(&p.dir) == module));
|
||||
let prefer_maven = settings.languages.java.maven.delegate_build;
|
||||
launches.snapshots.lock().initialize();
|
||||
let root = &scope.root;
|
||||
let model = load_launch_model(&scope);
|
||||
let non_java = build && compile::launch_has_non_java_sources(root, &model, &module, test);
|
||||
let is_maven = is_maven_module(root, &model, &module);
|
||||
let delegated = build
|
||||
&& delegates_to_external_build(
|
||||
is_maven,
|
||||
policy,
|
||||
non_java,
|
||||
cache::has_record(&project.root, &project.build_cache_dir(), &module),
|
||||
cache::has_record(root, &scope.cache, &module),
|
||||
prefer_maven,
|
||||
);
|
||||
let external = non_java || delegated;
|
||||
(model, external, delegated, prefer_maven, is_maven)
|
||||
(model, external, delegated, is_maven)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
@@ -101,7 +108,7 @@ pub(crate) async fn resolve_launch(
|
||||
}
|
||||
let model = std::sync::Arc::new(model);
|
||||
let members = if delegated {
|
||||
build_members(&project, &model, &module, test, prefer_maven, &waiting, cancel).await?
|
||||
build_members(&project, &scope, &model, &module, test, &waiting, cancel).await?
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
@@ -110,7 +117,8 @@ pub(crate) async fn resolve_launch(
|
||||
let cancel = cancel.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let _external_build = external_build;
|
||||
let local_repo = ide_sdk::apply::maven_local_repository(&project.root, &settings);
|
||||
let (root, cache, settings) = (&scope.root, &scope.cache, &scope.settings);
|
||||
let local_repo = ide_sdk::apply::maven_local_repository(root, settings);
|
||||
// Module outputs the launch runs from a snapshot of: the originals must not come back.
|
||||
let mut snapshotted = Vec::new();
|
||||
// The modules of the launches sharing this build also share its classpath probe.
|
||||
@@ -118,8 +126,8 @@ pub(crate) async fn resolve_launch(
|
||||
std::iter::once(module.clone()).chain(members.iter().map(|m| m.module.clone())).collect();
|
||||
let built = if delegated {
|
||||
let rebuild_on_jdt_errors = rebuild_on_jdt_errors(policy, prefer_maven, info.error_count);
|
||||
let outputs = project.java_launch_snapshots.lock().build(
|
||||
&project.root,
|
||||
let outputs = launches.snapshots.lock().build(
|
||||
root,
|
||||
&model,
|
||||
&module,
|
||||
cache::BuildOptions { test, policy, rebuild_on_jdt_errors, members },
|
||||
@@ -132,7 +140,7 @@ pub(crate) async fn resolve_launch(
|
||||
snapshotted = outputs.originals;
|
||||
copies
|
||||
} else if external {
|
||||
let built = compile::build_for_launch(&project.root, &model, &module, test, build_kind, &cancel)?;
|
||||
let built = compile::build_for_launch(root, &model, &module, test, build_kind, &cancel)?;
|
||||
if let Some(failure) = built.failure {
|
||||
if policy != BuildPolicy::MakeAndContinueOnErrors {
|
||||
return Err(IdeError::internal(failure));
|
||||
@@ -149,24 +157,15 @@ pub(crate) async fn resolve_launch(
|
||||
// m2e runs inside jdtls on the server JDK and can resolve a different
|
||||
// Maven profile/classifier than the module build. Ask the same Maven
|
||||
// process that built the module for its runtime/test dependencies.
|
||||
let maven_cp = compile::module_classpaths(
|
||||
&project.root,
|
||||
&model,
|
||||
&probed,
|
||||
test,
|
||||
local_repo,
|
||||
&project.build_cache_dir(),
|
||||
&cancel,
|
||||
);
|
||||
let maven_cp = compile::module_classpaths(root, &model, &probed, test, local_repo, cache, &cancel);
|
||||
merge_maven_launch_classpath(&mut class_paths, &mut info, maven_cp, &snapshotted)?;
|
||||
} else {
|
||||
append_unique_class_paths(&mut class_paths, std::mem::take(&mut info.class_paths));
|
||||
}
|
||||
info.class_paths = class_paths;
|
||||
apply_library_classpath(&mut info, &project.root, &settings.project_structure.libraries, test);
|
||||
apply_library_classpath(&mut info, root, &settings.project_structure.libraries, test);
|
||||
if build && !delegated {
|
||||
let cache_dir = project.build_cache_dir();
|
||||
match compile::process_launch_resources(&project.root, &model, &cache_dir, &info.class_paths, &cancel) {
|
||||
match compile::process_launch_resources(root, &model, cache, &info.class_paths, &cancel) {
|
||||
Ok(tasks) if !tasks.is_empty() => tracing::info!(?tasks, "Processed launch resources with Gradle"),
|
||||
Ok(_) => {}
|
||||
Err(e) if e.kind == ErrorKind::Cancelled => return Err(e),
|
||||
@@ -177,7 +176,7 @@ pub(crate) async fn resolve_launch(
|
||||
}
|
||||
}
|
||||
let compile_ms = started.elapsed().as_millis() - lsp_ms;
|
||||
finish_launch(&mut info, &project.root, &module, &settings, &model, &data_dir);
|
||||
finish_launch(&mut info, root, &module, settings, &model, &data_dir);
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
@@ -194,28 +193,36 @@ pub(crate) async fn resolve_launch(
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
}
|
||||
|
||||
fn load_launch_model(scope: &workspace::Scope) -> BuildModel {
|
||||
with_profiles(load(&scope.root, &scope.cache, &scope.settings), &scope.cache)
|
||||
}
|
||||
|
||||
fn is_maven_module(root: &Path, model: &BuildModel, module: &Path) -> bool {
|
||||
model.maven.as_ref().is_some_and(|m| m.projects.iter().any(|p| root.join(&p.dir) == module))
|
||||
}
|
||||
|
||||
/// A launch of a module jdtls doesn't serve (another Java language server, or none): the
|
||||
/// build tool compiles it, and the classpath comes from that server, else from Maven.
|
||||
async fn resolve_launch_without_jdtls(
|
||||
host: &Host,
|
||||
project: &std::sync::Arc<crate::Project>,
|
||||
module: PathBuf,
|
||||
scope: workspace::Scope,
|
||||
test: bool,
|
||||
policy: BuildPolicy,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<JavaLaunchInfo> {
|
||||
let started = std::time::Instant::now();
|
||||
let settings = project.settings.effective();
|
||||
let scope = std::sync::Arc::new(scope);
|
||||
let kind = if policy == BuildPolicy::Rebuild { compile::BuildKind::Rebuild } else { compile::BuildKind::Build };
|
||||
let (model, built) = {
|
||||
let (root, cache, settings, module, cancel) =
|
||||
(project.root.clone(), project.build_cache_dir(), settings.clone(), module.clone(), cancel.clone());
|
||||
let (scope, module, cancel) = (scope.clone(), module.clone(), cancel.clone());
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let model = load(&root, &cache, &settings);
|
||||
let model = load_launch_model(&scope);
|
||||
let built = if policy == BuildPolicy::NoBuild {
|
||||
None
|
||||
} else {
|
||||
Some(compile::build_for_launch(&root, &model, &module, test, kind, &cancel))
|
||||
Some(compile::build_for_launch(&scope.root, &model, &module, test, kind, &cancel))
|
||||
};
|
||||
(model, built)
|
||||
})
|
||||
@@ -249,9 +256,9 @@ async fn resolve_launch_without_jdtls(
|
||||
let build_ms = started.elapsed().as_millis();
|
||||
let from_server = project.lsp.java_server_classpath(&module, test, cancel).await?;
|
||||
let data_dir = host.local_data_dir.clone();
|
||||
let project = project.clone();
|
||||
let cancel = cancel.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let (root, cache, settings) = (&scope.root, &scope.cache, &scope.settings);
|
||||
match from_server {
|
||||
Some(server) => {
|
||||
info.project_root = server.classpath.project_root;
|
||||
@@ -260,26 +267,14 @@ async fn resolve_launch_without_jdtls(
|
||||
append_unique_class_paths(&mut class_paths, server.classpath.class_paths);
|
||||
}
|
||||
None => {
|
||||
let is_maven = model
|
||||
.maven
|
||||
.as_ref()
|
||||
.is_some_and(|m| m.projects.iter().any(|p| project.root.join(&p.dir) == module));
|
||||
if !is_maven {
|
||||
if !is_maven_module(root, &model, &module) {
|
||||
return Err(IdeError::unavailable(
|
||||
"Cannot resolve the classpath: the Java language server does not report it \
|
||||
(java-analyzer/projectClasspath), and the module is not a Maven project",
|
||||
));
|
||||
}
|
||||
let local_repo = ide_sdk::apply::maven_local_repository(&project.root, &settings);
|
||||
let classpath = compile::module_classpath(
|
||||
&project.root,
|
||||
&model,
|
||||
&module,
|
||||
test,
|
||||
local_repo,
|
||||
&project.build_cache_dir(),
|
||||
&cancel,
|
||||
)?;
|
||||
let local_repo = ide_sdk::apply::maven_local_repository(root, settings);
|
||||
let classpath = compile::module_classpath(root, &model, &module, test, local_repo, cache, &cancel)?;
|
||||
append_unique_class_paths(
|
||||
&mut class_paths,
|
||||
std::env::split_paths(&classpath).map(|p| p.to_string_lossy().into_owned()),
|
||||
@@ -287,8 +282,8 @@ async fn resolve_launch_without_jdtls(
|
||||
}
|
||||
}
|
||||
info.class_paths = class_paths;
|
||||
apply_library_classpath(&mut info, &project.root, &settings.project_structure.libraries, test);
|
||||
finish_launch(&mut info, &project.root, &module, &settings, &model, &data_dir);
|
||||
apply_library_classpath(&mut info, root, &settings.project_structure.libraries, test);
|
||||
finish_launch(&mut info, root, &module, settings, &model, &data_dir);
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
@@ -445,10 +440,10 @@ fn apply_library_classpath(
|
||||
/// whether its JDT errors call for a clean rebuild (as its own launch would decide).
|
||||
async fn build_members(
|
||||
project: &std::sync::Arc<crate::Project>,
|
||||
scope: &std::sync::Arc<workspace::Scope>,
|
||||
model: &std::sync::Arc<BuildModel>,
|
||||
module: &Path,
|
||||
test: bool,
|
||||
prefer_maven: bool,
|
||||
waiting: &cache::WaitingGuard,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<Vec<cache::Member>> {
|
||||
@@ -456,10 +451,11 @@ async fn build_members(
|
||||
if others.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let prefer_maven = scope.settings.languages.java.maven.delegate_build;
|
||||
let joining = {
|
||||
let (project, model, module) = (project.clone(), model.clone(), module.to_path_buf());
|
||||
let (scope, model, module) = (scope.clone(), model.clone(), module.to_path_buf());
|
||||
tokio::task::spawn_blocking(move || {
|
||||
joining_launches(&project.root, &project.build_cache_dir(), &model, &module, test, others, prefer_maven)
|
||||
joining_launches(&scope.root, &scope.cache, &model, &module, test, others, prefer_maven)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
@@ -500,8 +496,7 @@ fn joining_launches(
|
||||
others
|
||||
.into_iter()
|
||||
.filter(|o| {
|
||||
let is_maven =
|
||||
model.maven.as_ref().is_some_and(|m| m.projects.iter().any(|p| root.join(&p.dir) == o.module));
|
||||
let is_maven = is_maven_module(root, model, &o.module);
|
||||
o.test == test
|
||||
&& matches!(o.policy, BuildPolicy::Automatic | BuildPolicy::Make)
|
||||
&& compile::launch_reactor(root, model, &o.module).as_ref() == Some(&reactor)
|
||||
|
||||
@@ -64,6 +64,30 @@ pub(super) struct Member {
|
||||
pub rebuild_on_jdt_errors: bool,
|
||||
}
|
||||
|
||||
/// Launches share a build only within the same workspace project's cache.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Sessions(Mutex<HashMap<PathBuf, Arc<Launches>>>);
|
||||
|
||||
pub(in crate::ops) struct Launches {
|
||||
pub waiting: Waiting,
|
||||
pub snapshots: Mutex<Session>,
|
||||
}
|
||||
|
||||
impl Sessions {
|
||||
pub(in crate::ops) fn for_cache(&self, cache: &Path) -> Arc<Launches> {
|
||||
self.0
|
||||
.lock()
|
||||
.entry(cache.to_owned())
|
||||
.or_insert_with(|| {
|
||||
Arc::new(Launches {
|
||||
waiting: Waiting::default(),
|
||||
snapshots: Mutex::new(Session::new(cache.to_owned())),
|
||||
})
|
||||
})
|
||||
.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// Java launches from their start until their build: one launch's Maven run also builds
|
||||
/// the modules of launches still waiting (configurations started together, #3971).
|
||||
#[derive(Default)]
|
||||
|
||||
@@ -242,7 +242,10 @@ fn settings_only(
|
||||
.cloned()
|
||||
});
|
||||
if workspace.as_ref().is_some_and(|w| w.is_container(&project.root)) || member.is_some() {
|
||||
if config.extras.module.is_none() && !matches!(config.kind.as_str(), "application" | "spring-boot") {
|
||||
let jvm = matches!(config.kind.as_str(), "application" | "spring-boot");
|
||||
if jvm && member.is_some() && config.cwd.is_none() {
|
||||
config.cwd = Some(owner.into());
|
||||
} else if config.extras.module.is_none() && !jvm {
|
||||
config.extras.module = config.cwd.as_deref().map(ide_core::ipc_path::to_ipc);
|
||||
}
|
||||
ide_run::scope::rebase(config, &project.root, None);
|
||||
|
||||
@@ -51,10 +51,8 @@ pub struct Project {
|
||||
pub(crate) member_excludes: MemberExcludes,
|
||||
/// Per-project cache directory (build tool sync results…).
|
||||
pub cache_dir: PathBuf,
|
||||
/// Superseded launch snapshots retained until this project session ends.
|
||||
pub(crate) java_launch_snapshots: Mutex<crate::ops::java::cache::Session>,
|
||||
/// Java launches waiting for their build, which can share one Maven run.
|
||||
pub(crate) java_launches_waiting: crate::ops::java::cache::Waiting,
|
||||
/// Pending launches and retained snapshots, scoped to each workspace project.
|
||||
pub(crate) java_launches: crate::ops::java::cache::Sessions,
|
||||
/// Reasons this window was already told why Kotlin is debugged with kotlin-debug-adapter.
|
||||
pub(crate) kotlin_debug_notices: Mutex<HashSet<&'static str>>,
|
||||
/// Database tool window: data sources and their connections.
|
||||
@@ -641,10 +639,7 @@ impl Host {
|
||||
detected_roots,
|
||||
member_excludes,
|
||||
cache_dir: self.local_data_dir.join("cache").join(&project_key),
|
||||
java_launch_snapshots: Mutex::new(crate::ops::java::cache::Session::new(
|
||||
self.local_data_dir.join("cache").join(&project_key).join("build"),
|
||||
)),
|
||||
java_launches_waiting: Default::default(),
|
||||
java_launches: Default::default(),
|
||||
kotlin_debug_notices: Mutex::default(),
|
||||
db,
|
||||
http_history,
|
||||
@@ -891,10 +886,7 @@ impl Host {
|
||||
detected_roots: Arc::default(),
|
||||
member_excludes: Arc::default(),
|
||||
cache_dir: self.local_data_dir.join("cache").join(&project_key),
|
||||
java_launch_snapshots: Mutex::new(crate::ops::java::cache::Session::new(
|
||||
self.local_data_dir.join("cache").join(&project_key).join("build"),
|
||||
)),
|
||||
java_launches_waiting: Default::default(),
|
||||
java_launches: Default::default(),
|
||||
kotlin_debug_notices: Mutex::default(),
|
||||
db,
|
||||
http_history,
|
||||
|
||||
@@ -74,6 +74,13 @@ async fn serves_projects_files_documents_search_and_runs() {
|
||||
let info: ServerInfo = peer.request("initialize", json!({ "version": rpc::PROTOCOL_VERSION }), None).await.unwrap();
|
||||
assert_eq!(info.protocol, rpc::PROTOCOL_VERSION);
|
||||
|
||||
let scratch_path = base.join("data/scratches");
|
||||
assert!(!scratch_path.exists());
|
||||
let expected = serde_json::to_value(ide_core::IpcPath::from(scratch_path.clone())).unwrap();
|
||||
assert_eq!(invoke(&peer, "fs_scratches_dir", json!({})).await.unwrap(), expected);
|
||||
assert!(scratch_path.is_dir());
|
||||
assert_eq!(invoke(&peer, "fs_scratches_dir", json!({})).await.unwrap(), expected);
|
||||
|
||||
let opened = invoke(&peer, "open_project", json!({ "path": project })).await.unwrap();
|
||||
assert_eq!(opened["name"], "demo");
|
||||
assert_eq!(opened["trusted"], false);
|
||||
|
||||
@@ -6,6 +6,107 @@ use std::{
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn java_launch_builds_the_owning_workspace_reactor() {
|
||||
use ide_run::BuildPolicy;
|
||||
use ide_workspace::{SettingsStore, settings::SettingsScope};
|
||||
use std::{fs, os::unix::fs::PermissionsExt};
|
||||
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let config_dir = base.join("config");
|
||||
let primary = base.join("primary");
|
||||
let sibling = base.join("spring");
|
||||
let nested = primary.join("nested");
|
||||
let roots = [&primary, &sibling, &nested];
|
||||
for (i, root) in roots.into_iter().enumerate() {
|
||||
fs::create_dir_all(root.join("app")).unwrap();
|
||||
fs::write(
|
||||
root.join("pom.xml"),
|
||||
format!("<project><groupId>demo</groupId><artifactId>reactor-{i}</artifactId><version>1</version><packaging>pom</packaging><modules><module>app</module></modules></project>"),
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
root.join("app/pom.xml"),
|
||||
format!("<project><parent><groupId>demo</groupId><artifactId>reactor-{i}</artifactId><version>1</version></parent><artifactId>app</artifactId></project>"),
|
||||
)
|
||||
.unwrap();
|
||||
let wrapper = root.join("mvnw");
|
||||
fs::write(
|
||||
&wrapper,
|
||||
r#"#!/bin/sh
|
||||
set -eu
|
||||
printf '%s\n' "$*" >> calls
|
||||
mkdir -p app/target/classes
|
||||
case " $* " in *" test-compile "*) mkdir -p app/target/test-classes;; esac
|
||||
scope=runtime
|
||||
for arg in "$@"; do
|
||||
case "$arg" in
|
||||
-Dmdep.includeScope=*) scope="${arg#*=}";;
|
||||
esac
|
||||
done
|
||||
for arg in "$@"; do
|
||||
case "$arg" in
|
||||
-Dmdep.outputFile=*)
|
||||
touch "app/$scope.jar"
|
||||
printf '%s\n' "$PWD/app/$scope.jar" > "app/${arg#*=}";;
|
||||
esac
|
||||
done
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
fs::set_permissions(wrapper, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
SettingsStore::load(&config_dir, Some(root))
|
||||
.set(
|
||||
SettingsScope::Project,
|
||||
"languages.java.maven.activeProfiles",
|
||||
serde_json::json!(format!("member-{i}")),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
// Exercise the build-tool classpath fallback without starting an installed server.
|
||||
let global = SettingsStore::load(&config_dir, None);
|
||||
for server in ["jdtls", "java-analyzer", "kmp-lsp"] {
|
||||
global
|
||||
.set(SettingsScope::Global, &format!("languageServers.{server}.enabled"), serde_json::json!(false))
|
||||
.unwrap();
|
||||
}
|
||||
let host = Host::new(HostConfig {
|
||||
config_dir,
|
||||
data_dir: base.join("data"),
|
||||
local_data_dir: base.join("data"),
|
||||
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
|
||||
syntax: Arc::default(),
|
||||
sink_for: Box::new(|_| Arc::new(NullSink)),
|
||||
owner: |w| w,
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
project_environment: false,
|
||||
});
|
||||
for root in roots {
|
||||
host.trust.decide(root, true, false).unwrap();
|
||||
}
|
||||
host.open_project("main", &primary).unwrap();
|
||||
for root in [&sibling, &nested] {
|
||||
ops::project::attach_workspace(&host, "main", root).unwrap();
|
||||
}
|
||||
for (index, root) in roots.into_iter().enumerate() {
|
||||
let module = if root == &sibling { root.join("app") } else { root.strip_prefix(&primary).unwrap().join("app") };
|
||||
let test = index != 0;
|
||||
let info = ops::java::java_resolve_launch(&host, "main", module, test, BuildPolicy::Make, RequestId::next())
|
||||
.await
|
||||
.unwrap();
|
||||
let out = root.join("app/target").join(if test { "test-classes" } else { "classes" });
|
||||
let jar = root.join("app").join(if test { "test.jar" } else { "runtime.jar" });
|
||||
assert!(info.class_paths.iter().any(|p| std::path::Path::new(p) == out));
|
||||
assert!(info.class_paths.iter().any(|p| std::path::Path::new(p) == jar));
|
||||
let calls = fs::read_to_string(root.join("calls")).unwrap();
|
||||
assert!(calls.lines().next().unwrap().contains("-pl app -am"), "{calls}");
|
||||
assert!(calls.lines().all(|line| line.contains(&format!("-P member-{index}"))), "{calls}");
|
||||
assert!(calls.contains("dependency:build-classpath"), "{calls}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn linked_projects_share_navigation_but_keep_files_repositories_and_run_directories() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -646,7 +646,10 @@ impl LspManager {
|
||||
/// jdtls reports `ProjectStatus` when an import or project update ends (a POM
|
||||
/// change, a Maven sync, other Maven profiles), but does not check open documents
|
||||
/// again against the new classpath: their errors would stay until the next edit.
|
||||
/// Generated Maven sources are attached first, so that recheck sees them.
|
||||
/// Nor does it ask for a semantic tokens refresh: a file outside any project (its
|
||||
/// import failed, say on an unresolvable parent POM) gets no tokens, and would stay
|
||||
/// uncoloured after the import is fixed. Generated Maven sources are attached
|
||||
/// first, so the recheck and the new tokens see them.
|
||||
pub(crate) fn java_projects_updated(self: &Arc<Self>, server: Arc<Server>, generation: u64) {
|
||||
let uris: Vec<String> = self
|
||||
.docs
|
||||
@@ -663,6 +666,10 @@ impl LspManager {
|
||||
self.runtime.spawn(async move {
|
||||
let Some(run) = server.running_gen(generation) else { return };
|
||||
mgr.sync_generated_sources(&server, &run).await;
|
||||
mgr.sink().emit(ide_core::IdeEvent::LspRefresh {
|
||||
server: server.id,
|
||||
kind: ide_core::event::LspRefreshKind::SemanticTokens,
|
||||
});
|
||||
for uri in uris {
|
||||
let params =
|
||||
json!({ "command": "java.project.refreshDiagnostics", "arguments": [uri, "thisFile", false] });
|
||||
|
||||
@@ -3165,6 +3165,32 @@ async fn open_java_files_are_checked_again_after_a_project_update() {
|
||||
eventually(|| refreshed() == expected).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_project_update_refreshes_java_semantic_tokens() {
|
||||
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
|
||||
let _ = h.open("A.java", "class A { private String name; }");
|
||||
h.wait_status("jdtls", ServerStatus::Ready).await;
|
||||
let state = h.launcher.state("jdtls");
|
||||
let refreshes = || {
|
||||
h.events
|
||||
.lock()
|
||||
.iter()
|
||||
.filter(|e| matches!(e, IdeEvent::LspRefresh { kind: LspRefreshKind::SemanticTokens, .. }))
|
||||
.count()
|
||||
};
|
||||
state
|
||||
.peer()
|
||||
.notify("language/status", json!({ "type": "Message", "message": "Updating project configurations..." }))
|
||||
.unwrap();
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
assert_eq!(refreshes(), 0);
|
||||
|
||||
// jdtls answers with no tokens for a file outside any project and sends no
|
||||
// `workspace/semanticTokens/refresh` once a later import takes it in.
|
||||
state.peer().notify("language/status", json!({ "type": "ProjectStatus", "message": "OK" })).unwrap();
|
||||
eventually(|| refreshes() == 1).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_project_update_attaches_maven_generated_sources_before_rechecking() {
|
||||
let mut caps = incremental_caps();
|
||||
|
||||
@@ -1587,11 +1587,13 @@ mod tests {
|
||||
}
|
||||
|
||||
/// A pipe stand-in that counts the bytes taken from it.
|
||||
#[cfg(unix)]
|
||||
struct Counted<R> {
|
||||
inner: R,
|
||||
taken: Arc<AtomicUsize>,
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
impl<R: Read> Read for Counted<R> {
|
||||
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
|
||||
let n = self.inner.read(buf)?;
|
||||
|
||||
@@ -1365,8 +1365,15 @@ pub fn configure_server(cfg: &mut LanguageServerConfig, root: &Path, server_root
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
// TypeScript 7 serves LSP itself: it replaces the tsserver-based server.
|
||||
let vue_command = s.tool_path(vue::SERVER).and_then(|p| setting_path(root, p));
|
||||
let vue_command = vue_command.as_deref().map_or(vue::SERVER.into(), Path::to_string_lossy);
|
||||
let vue_pkg = vue::server_package(&vue_command, &search_path());
|
||||
// TypeScript 7 serves LSP itself: it replaces the tsserver-based server, whose plugin
|
||||
// host goes away with it. The Vue language server's `@vue/typescript-plugin` loads into
|
||||
// that host, so a Vue project that has the server keeps the vtsls route and its `.vue`
|
||||
// support; elsewhere the native server still wins.
|
||||
if matches!(name, "vtsls" | "typescript-language-server")
|
||||
&& !(name == "vtsls" && vue_pkg.is_some() && (vue::vue_project(server_root) || vue::vue_project(root)))
|
||||
&& let Some(native) = native_tsdk(server_root, s).or_else(|| native_tsdk(root, s))
|
||||
{
|
||||
cfg.command = native.to_string_lossy().into_owned();
|
||||
@@ -1380,10 +1387,8 @@ pub fn configure_server(cfg: &mut LanguageServerConfig, root: &Path, server_root
|
||||
cfg.tsserver_project = false;
|
||||
return;
|
||||
}
|
||||
let vue_command = s.tool_path(vue::SERVER).and_then(|p| setting_path(root, p));
|
||||
let vue_command = vue_command.as_deref().map_or(vue::SERVER.into(), Path::to_string_lossy);
|
||||
if name == "vtsls"
|
||||
&& let Some(vue) = vue::server_package(&vue_command, &search_path())
|
||||
&& let Some(vue) = vue_pkg
|
||||
{
|
||||
let plugin = vue::tsserver_plugin(&vue);
|
||||
merge_init_options(cfg, json!({ "vtsls": { "tsserver": { "globalPlugins": [plugin] } } }));
|
||||
@@ -2453,6 +2458,56 @@ mod maven_linkage_tests {
|
||||
assert_eq!(options.pointer("/typescript/tsserver/maxTsServerMemory"), Some(&json!(6144)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typescript_7_keeps_vtsls_when_the_vue_server_is_installed() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
// The Vue server, as the hybrid block finds it through the tool's package dir.
|
||||
let bin = root.join("tools/node_modules/.bin/vue-language-server");
|
||||
let pkg = root.join("tools/node_modules/@vue/language-server/package.json");
|
||||
std::fs::create_dir_all(bin.parent().unwrap()).unwrap();
|
||||
std::fs::create_dir_all(pkg.parent().unwrap()).unwrap();
|
||||
std::fs::write(&bin, "#!/bin/sh\n").unwrap();
|
||||
std::fs::write(&pkg, "{}").unwrap();
|
||||
let mut s = Settings::default();
|
||||
s.tools
|
||||
.insert(vue::SERVER.into(), ide_core::settings::ToolSettings { path: bin.to_string_lossy().into_owned() });
|
||||
// A Vue project whose TypeScript is 7: the native executable would take over.
|
||||
std::fs::write(root.join("package.json"), r#"{"dependencies":{"vue":"^3.0.0"}}"#).unwrap();
|
||||
let modules = root.join("node_modules");
|
||||
let os = match std::env::consts::OS {
|
||||
"macos" => "darwin",
|
||||
"windows" => "win32",
|
||||
os => os,
|
||||
};
|
||||
let arch = match std::env::consts::ARCH {
|
||||
"aarch64" => "arm64",
|
||||
"x86_64" => "x64",
|
||||
arch => arch,
|
||||
};
|
||||
std::fs::create_dir_all(modules.join("typescript/lib")).unwrap();
|
||||
std::fs::write(modules.join("typescript/package.json"), r#"{"name":"typescript","version":"7.0.2"}"#).unwrap();
|
||||
let native = modules.join(format!("@typescript/typescript-{os}-{arch}/lib")).join(crate::exe("tsc"));
|
||||
std::fs::create_dir_all(native.parent().unwrap()).unwrap();
|
||||
std::fs::write(&native, "").unwrap();
|
||||
s.languages.typescript.version = "workspace".into();
|
||||
|
||||
// vtsls hosts the Vue plugin's tsserver; the native server cannot, so it loses.
|
||||
let mut cfg = crate::tests::server("vtsls");
|
||||
configure_server(&mut cfg, root, root, &s);
|
||||
assert_eq!(cfg.command, "vtsls");
|
||||
assert_eq!(
|
||||
serde_json::to_value(cfg.initialization_options).unwrap().pointer("/vtsls/tsserver/globalPlugins/0/name"),
|
||||
Some(&json!("@vue/typescript-plugin"))
|
||||
);
|
||||
assert_eq!(cfg.tsserver_project_extras.extensions, [vue::EXTENSION.to_string()]);
|
||||
|
||||
// typescript-language-server gets no plugin route: the native server still applies.
|
||||
let mut cfg = crate::tests::server("typescript-language-server");
|
||||
configure_server(&mut cfg, root, root, &s);
|
||||
assert_eq!(Path::new(&cfg.command), native);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hybrid_without_a_config_keeps_type_acquisition_and_plain_vtsls_stays_default() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -42,6 +42,16 @@ pub(crate) fn server_package(command: &str, path: &OsStr) -> Option<PathBuf> {
|
||||
package_dir(&find_command(command, path)?, PACKAGE)
|
||||
}
|
||||
|
||||
/// Whether `root`'s manifest depends on Vue or `@vue/cli-service`, i.e. it is a Vue project.
|
||||
/// The tsserver plugin host that `vtsls` carries cannot be loaded into the native TS7
|
||||
/// server, so this decides whether the tsserver route stays for a Vue project.
|
||||
pub(crate) fn vue_project(root: &Path) -> bool {
|
||||
let Ok(manifest) = std::fs::read_to_string(root.join("package.json")) else {
|
||||
return false;
|
||||
};
|
||||
package_dependencies(&manifest).iter().any(|d| d == "vue" || d == CLI_SERVICE)
|
||||
}
|
||||
|
||||
/// vtsls `globalPlugins` entry loading the Vue plugin shipped with `package`.
|
||||
pub(crate) fn tsserver_plugin(package: &Path) -> serde_json::Value {
|
||||
serde_json::json!({
|
||||
|
||||
@@ -81,6 +81,12 @@ fn npm_package(tool: &str) -> &str {
|
||||
}
|
||||
|
||||
impl Tools {
|
||||
/// The IDE's own installation of `tool` outside `node_modules` (Ruff's private virtualenv).
|
||||
fn managed_executable(&self, tool: &str) -> Option<PathBuf> {
|
||||
let spec = crate::registry::find(tool)?;
|
||||
self.exe_in(&crate::managed_bin_dir(&self.root, spec, self.platform)?, spec.commands[0])
|
||||
}
|
||||
|
||||
/// Explicit executable/script, then the nearest project package, then managed tools and PATH.
|
||||
pub fn formatter_command(&self, tool: &str, file: &Path, custom: Option<&Path>) -> IdeResult<Command> {
|
||||
self.resolve_formatter_command(tool, file, custom).map_err(|e| e.with_tool(tool))
|
||||
@@ -100,6 +106,8 @@ impl Tools {
|
||||
(package_bin(manifest.parent().unwrap(), tool)?, true)
|
||||
} else if self.root.join(&manifest).is_file() {
|
||||
(package_bin(&self.root.join(&package), tool)?, true)
|
||||
} else if let Some(path) = self.managed_executable(tool) {
|
||||
(path, false)
|
||||
} else {
|
||||
(self.which(tool).ok_or_else(|| IdeError::missing_tool(tool))?, false)
|
||||
};
|
||||
@@ -241,6 +249,20 @@ mod tests {
|
||||
assert_eq!(failure.data, Some(ErrorData::Tool { tool: "prettier".into(), missing: false }));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_formatter_the_ide_installed_in_its_virtualenv_is_found() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let tools = Tools::with_paths(dir.path().join("tools"), OsString::new(), crate::platform::Platform::current());
|
||||
let file = dir.path().join("main.py");
|
||||
assert!(tools.formatter_command("ruff", &file, None).is_err());
|
||||
let bin = dir.path().join("tools/ruff/venv/bin");
|
||||
std::fs::create_dir_all(&bin).unwrap();
|
||||
std::fs::write(bin.join("ruff"), "").unwrap();
|
||||
let command = tools.formatter_command("ruff", &file, None).unwrap();
|
||||
assert_eq!(Path::new(command.get_program()), bin.join("ruff"));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn stderr_is_preserved_verbatim_even_when_longer_than_four_thousand_characters() {
|
||||
|
||||
@@ -478,12 +478,11 @@ pub(crate) fn log(r: &Repo, q: &LogQuery, cancel: &CancellationToken) -> IdeResu
|
||||
all.request = None;
|
||||
all.stop_at = None;
|
||||
let repo = r.gix()?;
|
||||
let decorations = decorations(&repo)?;
|
||||
let (decorations, generation) = r.ref_decorations(&repo)?;
|
||||
let shallow_vec =
|
||||
repo.shallow_commits().map_err(gx)?.map(|ids| ids.iter().copied().collect::<Vec<_>>()).unwrap_or_default();
|
||||
let shallow: HashSet<ObjectId> = shallow_vec.iter().copied().collect();
|
||||
let refs = r.log_refs()?;
|
||||
let key = format!("{}:{refs:?}:{shallow_vec:?}", serde_json::to_string(&all).map_err(gx)?);
|
||||
let key = format!("{}:{generation}:{shallow_vec:?}", serde_json::to_string(&all).map_err(gx)?);
|
||||
let cached = index.views.get(&key).cloned();
|
||||
let view = if let Some(cached) = cached {
|
||||
cached
|
||||
@@ -646,7 +645,7 @@ fn log_indexed(
|
||||
let repo = r.gix()?;
|
||||
let shallow: HashSet<ObjectId> =
|
||||
repo.shallow_commits().map_err(gx)?.map(|ids| ids.iter().copied().collect()).unwrap_or_default();
|
||||
let decorations = decorations(&repo)?;
|
||||
let (decorations, _) = r.ref_decorations(&repo)?;
|
||||
let range = q.range.as_deref().map(str::trim).filter(|s| !s.is_empty());
|
||||
let revs: Vec<&str> = q.branch.iter().chain(&q.branches).map(|b| b.trim()).filter(|b| !b.is_empty()).collect();
|
||||
let ranges: Vec<_> = q.ranges.iter().map(|s| s.trim()).filter(|s| !s.is_empty()).collect();
|
||||
@@ -741,7 +740,7 @@ fn log_indexed_rows(
|
||||
if tips.is_empty() && range.is_none() && ranges.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let decorations = decorations(&repo)?;
|
||||
let (decorations, _) = r.ref_decorations(&repo)?;
|
||||
let paths: Vec<String> = q
|
||||
.path
|
||||
.iter()
|
||||
@@ -1406,8 +1405,19 @@ fn tips(repo: &gix::Repository, revs: &[&str]) -> IdeResult<Vec<ObjectId>> {
|
||||
Ok(tips)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local!(static DECORATION_SCANS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) });
|
||||
|
||||
/// How many times this thread listed all refs.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn decorations_scans() -> usize {
|
||||
DECORATION_SCANS.get()
|
||||
}
|
||||
|
||||
/// Commit id → decoration labels.
|
||||
pub(crate) fn decorations(repo: &gix::Repository) -> IdeResult<HashMap<ObjectId, Vec<String>>> {
|
||||
#[cfg(test)]
|
||||
DECORATION_SCANS.set(DECORATION_SCANS.get() + 1);
|
||||
let mut map: HashMap<ObjectId, Vec<String>> = HashMap::new();
|
||||
if let Ok(id) = repo.head_id() {
|
||||
map.entry(id.detach()).or_default().push("HEAD".to_string());
|
||||
|
||||
@@ -939,6 +939,7 @@ mod preserve;
|
||||
mod push_preview;
|
||||
mod push_report;
|
||||
mod rebase_editor;
|
||||
mod ref_decorations;
|
||||
mod worktree_config;
|
||||
pub use ops::UNSTAGED_CHANGES_PREVENT_REBASE;
|
||||
mod incoming;
|
||||
@@ -1078,6 +1079,7 @@ pub struct Repo {
|
||||
cli_status: std::sync::atomic::AtomicBool,
|
||||
automatic_shelf: std::sync::RwLock<Option<shelf::AutomaticShelf>>,
|
||||
log_index: std::sync::Mutex<log_index::LogIndex>,
|
||||
ref_decorations: std::sync::Mutex<ref_decorations::RefDecorations>,
|
||||
log_signatures: std::sync::Mutex<history::LogSignatureCache>,
|
||||
conflict_mutation: std::sync::Mutex<()>,
|
||||
amend_recovery: std::sync::Mutex<Option<commit_rewrite::PendingAmend>>,
|
||||
@@ -1137,11 +1139,9 @@ impl Repo {
|
||||
/// dirty-scope refresh after a watcher batch. An empty list is the full status.
|
||||
pub fn status_paths(&self, paths: &[PathBuf]) -> IdeResult<Vec<FileStatus>> {
|
||||
let _scope = self.execution_scope();
|
||||
// Restricted Mode starts no program of the repository, and the scoped read is `git status`
|
||||
// with a pathspec: answer with the full gitoxide status instead.
|
||||
if !self.execution_allowed.load(std::sync::atomic::Ordering::Acquire) {
|
||||
return status::status(self);
|
||||
}
|
||||
// Restricted Mode reads this through git too: `cli::command` strips what the repository's
|
||||
// config could run, and the status call empties its clean/process filters. The full
|
||||
// gitoxide status it used to answer with walked the whole tree for one changed file.
|
||||
if paths.is_empty() {
|
||||
return status::status_paths(self, &[]);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,264 @@
|
||||
//! Ref decorations of the history, reused while git's ref storage has not changed.
|
||||
//!
|
||||
//! Listing and peeling every ref costs about 25 µs each, which a history page paid in full
|
||||
//! even for a one-row page. A page now stats `HEAD`, `packed-refs` and the directories under
|
||||
//! `refs/` instead: git replaces a loose ref by renaming a lock file over it, which changes
|
||||
//! the modification time of the ref's directory, and rewrites `packed-refs` the same way.
|
||||
|
||||
use crate::Repo;
|
||||
use crate::repo::absolute;
|
||||
use gix::ObjectId;
|
||||
use ide_core::IdeResult;
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
/// A timestamp this close to the time it was read cannot tell two writes apart: a later write
|
||||
/// may leave the same value (coarse file systems, FAT's 2 s). Such a snapshot is never reused.
|
||||
const RACY_WINDOW: Duration = Duration::from_secs(2);
|
||||
|
||||
type Stat = Option<(SystemTime, u64)>;
|
||||
pub(crate) type Decorations = Arc<HashMap<ObjectId, Vec<String>>>;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct RefDecorations {
|
||||
snapshot: Option<Snapshot>,
|
||||
/// Changes when the decorations do, so cached views of them can be keyed by it.
|
||||
generation: u64,
|
||||
}
|
||||
|
||||
struct Snapshot {
|
||||
map: Decorations,
|
||||
stamp: Vec<(PathBuf, Stat)>,
|
||||
reusable: bool,
|
||||
}
|
||||
|
||||
fn stat(path: &Path) -> Stat {
|
||||
let metadata = std::fs::metadata(path).ok()?;
|
||||
Some((metadata.modified().ok()?, metadata.len()))
|
||||
}
|
||||
|
||||
/// `HEAD`, `packed-refs` and every directory under `refs/`.
|
||||
fn stamp(git_dir: &Path, common_dir: &Path) -> Vec<(PathBuf, Stat)> {
|
||||
let mut paths = vec![git_dir.join("HEAD"), common_dir.join("packed-refs")];
|
||||
let mut pending = vec![common_dir.join("refs")];
|
||||
while let Some(dir) = pending.pop() {
|
||||
if let Ok(entries) = std::fs::read_dir(&dir) {
|
||||
pending.extend(entries.flatten().filter(|e| e.file_type().is_ok_and(|t| t.is_dir())).map(|e| e.path()));
|
||||
}
|
||||
paths.push(dir);
|
||||
}
|
||||
paths.into_iter().map(|path| (path.clone(), stat(&path))).collect()
|
||||
}
|
||||
|
||||
impl RefDecorations {
|
||||
fn get(&mut self, repo: &gix::Repository, git_dir: &Path, common_dir: &Path) -> IdeResult<(Decorations, u64)> {
|
||||
if let Some(snapshot) = &self.snapshot
|
||||
&& snapshot.reusable
|
||||
&& snapshot.stamp.iter().all(|(path, before)| stat(path) == *before)
|
||||
{
|
||||
return Ok((snapshot.map.clone(), self.generation));
|
||||
}
|
||||
// Stamped before the refs are read, so a write after the stamp shows in the next one.
|
||||
let taken = SystemTime::now();
|
||||
let stamp = stamp(git_dir, common_dir);
|
||||
let map = crate::history::decorations(repo)?;
|
||||
let reusable = stamp.iter().all(|(_, stat)| stat.is_none_or(|(modified, _)| modified + RACY_WINDOW <= taken));
|
||||
let unchanged = self.snapshot.as_ref().is_some_and(|old| *old.map == map);
|
||||
let map = match &self.snapshot {
|
||||
Some(old) if unchanged => old.map.clone(),
|
||||
_ => {
|
||||
self.generation += 1;
|
||||
Arc::new(map)
|
||||
}
|
||||
};
|
||||
self.snapshot = Some(Snapshot { map: map.clone(), stamp, reusable });
|
||||
Ok((map, self.generation))
|
||||
}
|
||||
}
|
||||
|
||||
impl Repo {
|
||||
/// Commit id → decoration labels, and a number that changes whenever they do.
|
||||
pub(crate) fn ref_decorations(&self, repo: &gix::Repository) -> IdeResult<(Decorations, u64)> {
|
||||
let common_dir = absolute(repo.common_dir())?;
|
||||
self.ref_decorations.lock().unwrap_or_else(|p| p.into_inner()).get(repo, &self.git_dir, &common_dir)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::history::decorations_scans;
|
||||
use crate::{LogOrder, LogQuery, Repo};
|
||||
use std::path::Path;
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
fn git(dir: &Path, args: &[&str]) -> String {
|
||||
let out = std::process::Command::new("git")
|
||||
.current_dir(dir)
|
||||
.args(["-c", "init.defaultBranch=main", "-c", "user.name=T", "-c", "[email protected]"])
|
||||
.args(["-c", "commit.gpgsign=false"])
|
||||
.args(args)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
|
||||
String::from_utf8_lossy(&out.stdout).trim().to_string()
|
||||
}
|
||||
|
||||
fn commit(dir: &Path, message: &str) -> String {
|
||||
std::fs::write(dir.join("f"), message).unwrap();
|
||||
git(dir, &["add", "-A"]);
|
||||
git(dir, &["commit", "-qm", message]);
|
||||
git(dir, &["rev-parse", "HEAD"])
|
||||
}
|
||||
|
||||
/// Sets the modification time of `HEAD`, `packed-refs` and every directory under `refs/`.
|
||||
fn set_ref_times(repo: &Repo, time: SystemTime) {
|
||||
let git = repo.git_dir.clone();
|
||||
let mut paths = vec![git.join("HEAD"), git.join("packed-refs")];
|
||||
let mut pending = vec![git.join("refs")];
|
||||
while let Some(dir) = pending.pop() {
|
||||
pending.extend(std::fs::read_dir(&dir).unwrap().flatten().filter(|e| e.path().is_dir()).map(|e| e.path()));
|
||||
paths.push(dir);
|
||||
}
|
||||
let mut options = std::fs::File::options();
|
||||
options.read(true);
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::fs::OpenOptionsExt;
|
||||
const FILE_WRITE_ATTRIBUTES: u32 = 0x100;
|
||||
const FILE_FLAG_BACKUP_SEMANTICS: u32 = 0x0200_0000;
|
||||
options.access_mode(FILE_WRITE_ATTRIBUTES).custom_flags(FILE_FLAG_BACKUP_SEMANTICS);
|
||||
}
|
||||
for path in paths.into_iter().filter(|p| p.exists()) {
|
||||
options.open(path).unwrap().set_modified(time).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
/// As if the refs were written long ago, then reads the history once so the decorations
|
||||
/// are cached; a second read must not list the refs again.
|
||||
fn settle(repo: &Repo) {
|
||||
set_ref_times(repo, SystemTime::now() - Duration::from_secs(3600));
|
||||
page(repo, 0, 1);
|
||||
let scans = decorations_scans();
|
||||
page(repo, 0, 1);
|
||||
assert_eq!(decorations_scans(), scans, "the decorations were not reusable");
|
||||
}
|
||||
|
||||
fn page(repo: &Repo, skip: u32, limit: u32) -> Vec<crate::Commit> {
|
||||
repo.log(&LogQuery { skip, limit, summary_only: true, order: LogOrder::Topo, ..Default::default() }).unwrap()
|
||||
}
|
||||
|
||||
fn labels(repo: &Repo, id: &str) -> Vec<String> {
|
||||
let all = page(repo, 0, 0);
|
||||
all.into_iter().find(|c| c.id == id).unwrap().refs
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn warm_pages_do_not_list_the_refs() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = tmp.path();
|
||||
git(dir, &["init", "-q"]);
|
||||
for i in 0..30 {
|
||||
commit(dir, &format!("c{i}"));
|
||||
}
|
||||
for i in 0..20 {
|
||||
git(dir, &["branch", &format!("b{i}")]);
|
||||
}
|
||||
let repo = Repo::discover(dir).unwrap().unwrap();
|
||||
settle(&repo);
|
||||
let after_first = decorations_scans();
|
||||
for skip in [10, 20, 0, 5] {
|
||||
assert_eq!(page(&repo, skip, 1).len(), 1);
|
||||
assert_eq!(page(&repo, skip, 10).len(), 10);
|
||||
}
|
||||
assert_eq!(decorations_scans(), after_first, "a warm page listed the refs again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fresh_ref_timestamps_are_not_trusted() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = tmp.path();
|
||||
git(dir, &["init", "-q"]);
|
||||
let first = commit(dir, "first");
|
||||
let repo = Repo::discover(dir).unwrap().unwrap();
|
||||
set_ref_times(&repo, SystemTime::now());
|
||||
page(&repo, 0, 10);
|
||||
let scans = decorations_scans();
|
||||
// A write within the timestamp's resolution would leave it unchanged: rescan every time.
|
||||
page(&repo, 0, 10);
|
||||
assert!(decorations_scans() > scans);
|
||||
assert!(labels(&repo, &first).contains(&"main".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decorations_follow_every_kind_of_ref_change() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = tmp.path();
|
||||
git(dir, &["init", "-q"]);
|
||||
let first = commit(dir, "first");
|
||||
let repo = Repo::discover(dir).unwrap().unwrap();
|
||||
settle(&repo);
|
||||
let first_labels = labels(&repo, &first);
|
||||
assert!(first_labels.contains(&"HEAD".to_string()) && first_labels.contains(&"main".to_string()));
|
||||
|
||||
// A new commit moves HEAD and the branch.
|
||||
settle(&repo);
|
||||
let second = commit(dir, "second");
|
||||
assert_eq!(labels(&repo, &first), Vec::<String>::new());
|
||||
assert!(labels(&repo, &second).contains(&"main".to_string()));
|
||||
|
||||
// A new tag, then an annotated one, in a directory that did not exist before.
|
||||
settle(&repo);
|
||||
git(dir, &["tag", "v1", &first]);
|
||||
assert_eq!(labels(&repo, &first), ["tag: v1"]);
|
||||
settle(&repo);
|
||||
git(dir, &["tag", "-a", "-m", "m", "rel/v2", &first]);
|
||||
assert_eq!(labels(&repo, &first), ["tag: rel/v2", "tag: v1"]);
|
||||
|
||||
// A new branch, one moved to another commit, and one deleted.
|
||||
settle(&repo);
|
||||
git(dir, &["branch", "side", &first]);
|
||||
assert!(labels(&repo, &first).contains(&"side".to_string()));
|
||||
settle(&repo);
|
||||
git(dir, &["branch", "-f", "side", &second]);
|
||||
assert!(!labels(&repo, &first).contains(&"side".to_string()));
|
||||
assert!(labels(&repo, &second).contains(&"side".to_string()));
|
||||
settle(&repo);
|
||||
git(dir, &["branch", "-D", "side"]);
|
||||
assert!(!labels(&repo, &second).contains(&"side".to_string()));
|
||||
|
||||
// Refs in packed-refs: packing changes nothing visible, deleting one rewrites the file.
|
||||
git(dir, &["branch", "packed", &first]);
|
||||
git(dir, &["pack-refs", "--all"]);
|
||||
settle(&repo);
|
||||
assert!(labels(&repo, &first).contains(&"packed".to_string()));
|
||||
git(dir, &["branch", "-D", "packed"]);
|
||||
assert!(!labels(&repo, &first).contains(&"packed".to_string()));
|
||||
|
||||
// A detached HEAD and a tag deleted again.
|
||||
settle(&repo);
|
||||
git(dir, &["checkout", "-q", "--detach", &first]);
|
||||
assert!(labels(&repo, &first).contains(&"HEAD".to_string()));
|
||||
assert!(!labels(&repo, &second).contains(&"HEAD".to_string()));
|
||||
settle(&repo);
|
||||
git(dir, &["tag", "-d", "v1"]);
|
||||
assert_eq!(labels(&repo, &first), ["HEAD", "tag: rel/v2"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_ref_change_between_pages_replaces_the_cached_view() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = tmp.path();
|
||||
git(dir, &["init", "-q"]);
|
||||
let first = commit(dir, "first");
|
||||
commit(dir, "second");
|
||||
let repo = Repo::discover(dir).unwrap().unwrap();
|
||||
settle(&repo);
|
||||
page(&repo, 0, 10);
|
||||
settle(&repo);
|
||||
git(dir, &["tag", "v1", &first]);
|
||||
let rows = page(&repo, 0, 10);
|
||||
assert_eq!(rows.iter().find(|c| c.id == first).unwrap().refs, ["tag: v1"]);
|
||||
}
|
||||
}
|
||||
@@ -88,6 +88,7 @@ pub(crate) fn discover(path: &Path) -> IdeResult<Option<Repo>> {
|
||||
cli_status: Default::default(),
|
||||
automatic_shelf: Default::default(),
|
||||
log_index: Default::default(),
|
||||
ref_decorations: Default::default(),
|
||||
log_signatures: Default::default(),
|
||||
conflict_mutation: Default::default(),
|
||||
amend_recovery: Default::default(),
|
||||
|
||||
@@ -583,4 +583,60 @@ mod tests {
|
||||
cli_status(&repo, &IgnoredNames::default()).unwrap();
|
||||
assert!(marker.exists(), "control: git status did not run the filter");
|
||||
}
|
||||
|
||||
fn committed_repo(dir: &Path) {
|
||||
git(dir, &["init", "-q"]);
|
||||
git(dir, &["config", "user.name", "Test User"]);
|
||||
git(dir, &["config", "user.email", "[email protected]"]);
|
||||
git(dir, &["config", "commit.gpgsign", "false"]);
|
||||
std::fs::write(dir.join("a.txt"), "same\n").unwrap();
|
||||
std::fs::write(dir.join("b.txt"), "same\n").unwrap();
|
||||
commit_all(dir, "base");
|
||||
}
|
||||
|
||||
/// The dirty-scope refresh in Restricted Mode reads the named paths only: it used to answer
|
||||
/// with the full status, which walks the whole tree for one saved file.
|
||||
#[test]
|
||||
fn restricted_status_paths_reads_only_the_named_paths() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let dir = temp.path();
|
||||
committed_repo(dir);
|
||||
std::fs::write(dir.join("a.txt"), "changed\n").unwrap();
|
||||
std::fs::write(dir.join("b.txt"), "changed\n").unwrap();
|
||||
|
||||
let repo = Repo::discover(dir).unwrap().expect("repository found");
|
||||
let one = repo.status_paths(&[repo.root().join("a.txt")]).unwrap();
|
||||
assert_eq!(one.iter().map(|s| s.rel_path.as_str()).collect::<Vec<_>>(), ["a.txt"]);
|
||||
assert_eq!(repo.status().unwrap().len(), 2, "the full status still lists both");
|
||||
}
|
||||
|
||||
/// The scoped read is `git status`, which applies the repository's clean filters to compare
|
||||
/// content: Restricted Mode must empty them there as it does for the full read.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn restricted_status_paths_does_not_run_repository_filters() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let dir = temp.path();
|
||||
committed_repo(dir);
|
||||
let marker = dir.join(".git/executed");
|
||||
let script = dir.join(".git/marker.sh");
|
||||
std::fs::write(&script, format!("#!/bin/sh\ntouch '{}'\ncat\n", marker.display())).unwrap();
|
||||
std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
git(dir, &["config", "filter.marker.clean", script.to_str().unwrap()]);
|
||||
std::fs::write(dir.join(".gitattributes"), "*.txt filter=marker\n").unwrap();
|
||||
// Same size, new mtime: git has to read (and clean) the file to tell whether it changed.
|
||||
std::thread::sleep(std::time::Duration::from_millis(1100));
|
||||
std::fs::write(dir.join("a.txt"), "diff\n").unwrap();
|
||||
|
||||
let repo = Repo::discover(dir).unwrap().expect("repository found");
|
||||
let paths = [repo.root().join("a.txt")];
|
||||
let listed = repo.status_paths(&paths).unwrap();
|
||||
assert_eq!(listed.len(), 1, "the change is still listed");
|
||||
assert!(!marker.exists(), "Restricted Mode ran the repository's clean filter");
|
||||
// Control: a trusted run does use the filter, so the fixture is live.
|
||||
repo.set_execution_allowed(true);
|
||||
repo.status_paths(&paths).unwrap();
|
||||
assert!(marker.exists(), "control: git status did not run the filter");
|
||||
}
|
||||
}
|
||||
@@ -591,8 +591,17 @@ fn select_into(
|
||||
encoding: &dyn Fn(&Path) -> IdeResult<TextEncoding>,
|
||||
) -> IdeResult<Vec<String>> {
|
||||
let index = r.git_dir.join("index");
|
||||
if index.exists() {
|
||||
std::fs::copy(&index, &tmp.0)?;
|
||||
match std::fs::File::open(index) {
|
||||
Ok(mut source) => {
|
||||
let metadata = source.metadata()?;
|
||||
let mut copy = std::fs::File::create(&tmp.0)?;
|
||||
copy.set_permissions(metadata.permissions())?;
|
||||
std::io::copy(&mut source, &mut copy)?;
|
||||
// Git uses the index timestamp to decide which same-size files need a content check.
|
||||
copy.set_modified(metadata.modified()?)?;
|
||||
}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(e) => return Err(e.into()),
|
||||
}
|
||||
let env = [("GIT_INDEX_FILE", tmp.0.as_os_str())];
|
||||
fill_commit_index(r, &env, options, encoding)
|
||||
|
||||
@@ -2017,11 +2017,17 @@ fn partial_commit_of_chosen_hunks_leaves_worktree_and_index_alone() {
|
||||
#[test]
|
||||
fn pending_changes_show_what_the_commit_would_hold_without_touching_the_index() {
|
||||
let fx = Fixture::new();
|
||||
fx.git(&["config", "core.checkStat", "minimal"]);
|
||||
fx.git(&["config", "core.trustctime", "false"]);
|
||||
let same_tick = std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_700_000_000);
|
||||
let set_mtime =
|
||||
|path| std::fs::File::options().write(true).open(fx.path(path)).unwrap().set_modified(same_tick).unwrap();
|
||||
let base = "a\nb\nc\nd\ne\nf\ng\nh\ni\nj\n";
|
||||
fx.write("f.txt", base);
|
||||
fx.write("staged.txt", "s\n");
|
||||
fx.write("old.txt", "moved\nfile\nwith\nlines\n");
|
||||
fx.write("bin.dat", "\0\x01");
|
||||
set_mtime("bin.dat");
|
||||
fx.commit_all("base");
|
||||
let repo = fx.repo();
|
||||
let utf8 = |_: &Path| -> ide_core::IdeResult<&encoding_rs::Encoding> { Ok(encoding_rs::UTF_8) };
|
||||
@@ -2032,6 +2038,9 @@ fn pending_changes_show_what_the_commit_would_hold_without_touching_the_index()
|
||||
fx.git(&["add", "staged.txt"]);
|
||||
fx.git(&["mv", "old.txt", "new.txt"]);
|
||||
fx.write("bin.dat", "\0\x02");
|
||||
// Git must recheck a same-size edit made on the same clock tick as the index.
|
||||
set_mtime("bin.dat");
|
||||
set_mtime(".git/index");
|
||||
fx.write("added.txt", "new\n");
|
||||
let index_before = std::fs::read(fx.dir.join(".git/index")).unwrap();
|
||||
|
||||
|
||||
@@ -1753,7 +1753,8 @@ mod tests {
|
||||
std::fs::write(root.join("src/a/after.rs"), "x").unwrap();
|
||||
assert!(wait_for(&batches, |b| all_paths(b).contains(&root.join("src/a/after.rs"))));
|
||||
let paths = all_paths(&batches.lock());
|
||||
assert!(!paths.iter().any(|p| p.starts_with(root.join("node_modules"))), "{paths:?}");
|
||||
let excluded = root.join("node_modules");
|
||||
assert!(!paths.iter().any(|p| p != &excluded && p.starts_with(&excluded)), "{paths:?}");
|
||||
assert!(!paths.contains(&root.join("lib/out/o.txt")));
|
||||
|
||||
// Un-ignoring lib/out keeps its existing filename watch.
|
||||
|
||||
@@ -125,16 +125,16 @@ Tasks are saved per project and survive restarts. When the agent supports resumi
|
||||
|
||||
## Manage agents
|
||||
|
||||
**Settings › Tools › Agents** (also **More Agents…** in the agent picker) has two tabs:
|
||||
**Settings › Agents › Agent Setup** (also **More Agents…** in the agent picker) lists built-in agents and agents from the ACP Registry.
|
||||
|
||||
- **Built-in**: for each built-in agent, whether its executable was found on `PATH`, a field to point at a **Custom executable**, **Environment variables** for the agent process (written as `NAME=value; OTHER=value`; the values are kept in the OS credential store) and how to sign in. Changes apply to new sessions. When the agent is a global npm install (such as Claude Code, Codex or Gemini CLI), **Check for updates** compares it with npm's latest stable release and **Update to…** updates that installation.
|
||||
- **ACP Registry**: agents published in the [ACP Registry](https://agentclientprotocol.com). Search, **Install**, **Update** and **Remove**. Installed agents are kept in OpenIDEA's data directory; downloads are checked against the registry's SHA-256 when it provides one.
|
||||
|
||||
**Settings › Tools › Agents › Chat** chooses what the task header shows: **Context window usage**, **Time spent on the task**, **Usage limits** (when the agent reports them, such as Claude Code) and **Session cost**.
|
||||
**Settings › Agents › Chat** chooses what the task header shows: **Context window usage**, **Time spent on the task**, **Usage limits** (when the agent reports them, such as Claude Code) and **Session cost**.
|
||||
|
||||
### External MCP servers
|
||||
|
||||
**Settings › Agents › External MCP Servers** configures MCP servers across three persistent levels, while the composer's **MCP** picker (or `/mcp`) controls them per session:
|
||||
**Settings › Agents › MCP Connections** configures MCP servers across three persistent levels, while the composer's **MCP** picker (or `/mcp`) controls them per session:
|
||||
|
||||
- **Global (`User`)**: saved in `settings.toml` with environment variable and HTTP header values stored in the OS credential store, shared across projects and agents (or scoped to selected agents).
|
||||
- **Project (`Workspace`)**: saved in `.openidea/settings.toml`; entries with the same name override Global servers, and servers added outside OpenIDEA stay off until approved.
|
||||
|
||||
@@ -69,6 +69,7 @@ Long operations (pull, prune, Compose) show progress at the top with a **Cancel*
|
||||
|
||||
Selecting an item shows tabs in the detail pane:
|
||||
|
||||
- **Compose project**: **Dashboard** (project overview, services with live resource usage, named volumes created by the project).
|
||||
- **Container**: **Dashboard** (overview, live resource usage, port bindings that open in the browser, mounts, networks, environment variables, labels), **Log** (last 1,000 lines, following while the container runs, with **Timestamps**), **Processes** (`docker top`) and **Inspect** (the raw JSON).
|
||||
- **Image**: **Dashboard** (tags, containers using it, environment, labels), **Layers** and **Inspect**.
|
||||
- **Volume** and **network**: **Dashboard** and **Inspect**.
|
||||
|
||||
@@ -20,7 +20,7 @@ A file holds only the values that differ from the layer below. Tables merge key
|
||||
|
||||
Some settings are ignored in the project file: `mcpServer`, imported color schemes (`editor.customSchemes`) and `agents.newTaskApprovals` are global only. Project trust is never read from settings.
|
||||
|
||||
A project file can't loosen what coding agents may do: `agentSecurity.allowedCommands` and `agents.defaults` are global only, and `agentSecurity.blockedCommands` in a project adds to the global list rather than replacing it. An MCP server in the project's `agents.mcpServers` stays off until you turn it on in **Settings › Agents › External MCP Servers**, and again after its definition changes.
|
||||
A project file can't loosen what coding agents may do: `agentSecurity.allowedCommands` and `agents.defaults` are global only, and `agentSecurity.blockedCommands` in a project adds to the global list rather than replacing it. An MCP server in the project's `agents.mcpServers` stays off until you turn it on in **Settings › Agents › MCP Connections**, and again after its definition changes.
|
||||
|
||||
## File format
|
||||
|
||||
|
||||
@@ -125,16 +125,16 @@ agent 运行过一个任务后,新任务会以它自动批准所有操作的
|
||||
|
||||
## 管理 agent
|
||||
|
||||
**设置 › 工具 › 智能体**(也可以在 agent 选择器中点 **更多 Agent…**)有两个标签页:
|
||||
**设置 › 智能体 › 智能体配置**(也可以在 agent 选择器中点 **更多 Agent…**)列出了内置智能体和 ACP Registry 提供的智能体。
|
||||
|
||||
- **内置**:每个内置 agent 的可执行文件是否在 `PATH` 中找到、指定 **自定义可执行文件** 的输入框、传给 agent 进程的 **环境变量**(格式为 `NAME=value; OTHER=value`;这些值保存在系统凭据存储中)以及登录方式。改动对新会话生效。如果 agent 是 npm 全局安装(例如 Claude Code、Codex、Gemini CLI),**检查更新** 会与 npm 的最新稳定版比较,点击 **更新至…** 即可更新这份安装。
|
||||
- **ACP 注册表**:[ACP Registry](https://agentclientprotocol.com) 中发布的 agent,可以搜索、**安装**、**更新** 和 **移除**。安装的 agent 保存在 OpenIDEA 的数据目录中;注册表提供 SHA-256 时会校验下载内容。
|
||||
|
||||
**设置 › 工具 › 智能体 › 聊天** 决定任务标题栏显示哪些信息:**上下文窗口用量**、**任务耗时**、**用量限额**(agent 报告时,例如 Claude Code)和 **会话花费**。
|
||||
**设置 › 智能体 › 聊天** 决定任务标题栏显示哪些信息:**上下文窗口用量**、**任务耗时**、**用量限额**(agent 报告时,例如 Claude Code)和 **会话花费**。
|
||||
|
||||
### 外部 MCP 服务器
|
||||
|
||||
**设置 › 智能体 › 外部 MCP 服务器** 按三个持久层级管理 MCP 服务器,输入框底部的 **MCP** 选择器(或 `/mcp` 命令)则按单个会话控制它们:
|
||||
**设置 › 智能体 › MCP 连接** 按三个持久层级管理 MCP 服务器,输入框底部的 **MCP** 选择器(或 `/mcp` 命令)则按单个会话控制它们:
|
||||
|
||||
- **全局(`用户`)**:保存在 `settings.toml` 中,环境变量与 HTTP 请求头的值保存在系统凭据存储里,跨项目与各智能体共享(也可限定给选定的智能体)。
|
||||
- **项目(`工作区`)**:保存在 `.openidea/settings.toml` 中,同名服务器覆盖全局配置;在 OpenIDEA 外部写入的项目服务器在批准启用前保持关闭。
|
||||
|
||||
@@ -69,6 +69,7 @@ OpenIDEA 通过 `docker` 命令行操作 Docker,所以只要能提供可用的
|
||||
|
||||
选中某项后,详情区会显示以下标签页:
|
||||
|
||||
- **Compose 项目**:**仪表盘**(项目概览、各服务的实时资源使用情况、该项目创建的命名卷)。
|
||||
- **容器**:**仪表盘**(概览、实时资源使用情况、可在浏览器中打开的端口绑定、挂载、网络、环境变量、标签)、**日志**(最近 1,000 行,容器运行时持续跟随,可切换 **时间戳**)、**进程**(`docker top`)和 **检查**(原始 JSON)。
|
||||
- **镜像**:**仪表盘**(标签、使用它的容器、环境变量、标签)、**镜像层** 和 **检查**。
|
||||
- **卷** 和 **网络**:**仪表盘** 和 **检查**。
|
||||
|
||||
@@ -20,7 +20,7 @@ description: "OpenIDEA 的设置保存在哪里、全局文件与项目文件如
|
||||
|
||||
有些设置在项目文件中会被忽略:`mcpServer`、导入的配色方案(`editor.customSchemes`)和 `agents.newTaskApprovals` 只能全局配置。项目信任状态永远不会从设置文件中读取。
|
||||
|
||||
项目文件不能放宽编码智能体的权限:`agentSecurity.allowedCommands` 和 `agents.defaults` 只能全局配置;项目中的 `agentSecurity.blockedCommands` 会追加到全局列表中,而不是替换它。项目 `agents.mcpServers` 中的 MCP 服务器会保持关闭,直到你在 **设置 › 智能体 › 外部 MCP 服务器** 中将其开启;服务器定义改变后也需要重新开启。
|
||||
项目文件不能放宽编码智能体的权限:`agentSecurity.allowedCommands` 和 `agents.defaults` 只能全局配置;项目中的 `agentSecurity.blockedCommands` 会追加到全局列表中,而不是替换它。项目 `agents.mcpServers` 中的 MCP 服务器会保持关闭,直到你在 **设置 › 智能体 › MCP 连接** 中将其开启;服务器定义改变后也需要重新开启。
|
||||
|
||||
## 文件格式
|
||||
|
||||
|
||||
@@ -131,3 +131,60 @@ for (const home of [false, true]) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
test("short prompts fit before and after a completed agent exchange", async ({ workbench: page }) => {
|
||||
await prepare(page, true, false);
|
||||
const box = page.getByRole("textbox", { name: "Message", exact: true }).filter({ visible: true });
|
||||
const scroller = page.locator(".cm-scroller").filter({ has: box });
|
||||
const overflow = () =>
|
||||
scroller.evaluate((el) => ({
|
||||
x: el.scrollWidth - el.clientWidth,
|
||||
y: el.scrollHeight - el.clientHeight,
|
||||
}));
|
||||
|
||||
await expect(box.locator(".cm-placeholder")).toBeVisible();
|
||||
await expect.poll(overflow).toEqual({ x: 0, y: 0 });
|
||||
await box.fill("Reply with OK.");
|
||||
await expect.poll(overflow).toEqual({ x: 0, y: 0 });
|
||||
await page.getByRole("button", { name: "Start", exact: true }).click();
|
||||
await expect(page.locator("html")).toHaveAttribute("data-submitted-prompt", /Reply with OK/);
|
||||
await page.evaluate(() => document.dispatchEvent(new Event("test:agent-ack")));
|
||||
await expect(page.getByRole("tab", { name: task.title })).toBeVisible();
|
||||
await page.evaluate(async (id) => {
|
||||
const storePath = "/src/features/agents/store.ts";
|
||||
const { useAgents } = await import(storePath);
|
||||
useAgents.setState({
|
||||
entries: new Map([
|
||||
[
|
||||
id,
|
||||
[
|
||||
{ type: "user", text: "Reply with OK.", attachments: [] },
|
||||
{ type: "agent", text: "OK" },
|
||||
],
|
||||
],
|
||||
]),
|
||||
});
|
||||
}, task.id);
|
||||
await expect(page.getByText("OK", { exact: true })).toBeVisible();
|
||||
await expect.poll(overflow).toEqual({ x: 0, y: 0 });
|
||||
|
||||
await page.getByRole("button", { name: "Agents", exact: true }).click();
|
||||
await page.getByRole("button", { name: "New Agent Task", exact: true }).click();
|
||||
await expect(box.locator(".cm-placeholder")).toBeVisible();
|
||||
await expect(scroller).toHaveCSS("overflow-x", "hidden");
|
||||
await expect.poll(overflow).toEqual({ x: 0, y: 0 });
|
||||
await box.fill("Short draft");
|
||||
await expect.poll(overflow).toEqual({ x: 0, y: 0 });
|
||||
|
||||
await box.fill("word".repeat(2000));
|
||||
await expect(scroller).toHaveCSS("overflow-y", "auto");
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const { x, y } = await overflow();
|
||||
return x === 0 && y > 0;
|
||||
})
|
||||
.toBe(true);
|
||||
await box.fill("");
|
||||
await expect(box.locator(".cm-placeholder")).toBeVisible();
|
||||
await expect.poll(overflow).toEqual({ x: 0, y: 0 });
|
||||
});
|
||||
@@ -308,11 +308,15 @@ test("manages multi-level MCP servers in Settings and per-session overrides via
|
||||
await sessionPopup.getByRole("button", { name: "Reset" }).click();
|
||||
await expect(sessionPopup.getByRole("button", { name: "Reset" })).toHaveCount(0);
|
||||
|
||||
// 2. Jump directly from the session MCP popover's gear button to Settings › External MCP Servers.
|
||||
await sessionPopup.getByRole("button", { name: "External MCP Servers…" }).click();
|
||||
// 2. Jump directly from the session MCP popover's gear button to Settings › Agents › MCP Connections.
|
||||
await sessionPopup.getByRole("button", { name: "MCP Connections…", exact: true }).click();
|
||||
const settingsDialog = page.getByRole("dialog", { name: "Settings", exact: true });
|
||||
await expect(settingsDialog).toBeVisible();
|
||||
await expect(settingsDialog.getByRole("heading", { name: "External MCP Servers" })).toBeVisible();
|
||||
await expect(settingsDialog.getByRole("heading", { name: "MCP Connections", exact: true })).toBeVisible();
|
||||
await expect(settingsDialog.getByRole("treeitem", { name: "MCP Connections", exact: true })).toHaveAttribute(
|
||||
"aria-selected",
|
||||
"true",
|
||||
);
|
||||
|
||||
// Probe `github-mcp-server` and inspect discovered tools inside the expandable card.
|
||||
await settingsDialog.getByRole("button", { name: "Test github-mcp-server" }).click();
|
||||
@@ -321,7 +325,7 @@ test("manages multi-level MCP servers in Settings and per-session overrides via
|
||||
|
||||
if (screenshotDir) {
|
||||
await settingsDialog
|
||||
.getByRole("heading", { name: "External MCP Servers" })
|
||||
.getByRole("heading", { name: "MCP Connections", exact: true })
|
||||
.evaluate((el) => el.scrollIntoView({ block: "start" }));
|
||||
await settingsDialog.screenshot({ path: `${screenshotDir}/mcp-hub-levels.png` });
|
||||
await settingsDialog.getByRole("button", { name: "Add from JSON" }).click();
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
import { Buffer } from "node:buffer";
|
||||
import type { AgentEntry, AgentTask } from "../src/bindings";
|
||||
import { expect, test } from "./fixtures";
|
||||
|
||||
const task: AgentTask = {
|
||||
id: "tool-images",
|
||||
title: "Render preview",
|
||||
provider: "claude",
|
||||
model: null,
|
||||
status: "ready",
|
||||
isolation: "local",
|
||||
cwd: "/dev/acme-api",
|
||||
branch: null,
|
||||
base: null,
|
||||
baseCommit: null,
|
||||
error: null,
|
||||
createdMs: 0,
|
||||
updatedMs: 0,
|
||||
config: [],
|
||||
commands: [],
|
||||
usage: null,
|
||||
queue: [],
|
||||
};
|
||||
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="900" height="220" viewBox="0 0 900 220">
|
||||
<rect width="900" height="220" fill="#f1f5f9"/>
|
||||
<g fill="#0f766e"><circle cx="150" cy="92" r="48"/><rect x="103" y="137" width="94" height="42" rx="8"/></g>
|
||||
<g fill="#2563eb"><ellipse cx="450" cy="92" rx="28" ry="48"/><rect x="420" y="137" width="60" height="42" rx="8"/></g>
|
||||
<g fill="#b45309"><circle cx="750" cy="92" r="48"/><rect x="703" y="137" width="94" height="42" rx="8"/></g>
|
||||
<g fill="#0f172a" font-size="20" font-family="sans-serif" text-anchor="middle"><text x="150" y="208">Front</text><text x="450" y="208">Side</text><text x="750" y="208">Back</text></g></svg>`;
|
||||
const image = { mimeType: "image/svg+xml", data: Buffer.from(svg).toString("base64"), name: null };
|
||||
const entries: AgentEntry[] = [
|
||||
{
|
||||
type: "user",
|
||||
text: "Render three views of the sample model.",
|
||||
attachments: [],
|
||||
sentMs: 1000,
|
||||
doneMs: 2000,
|
||||
steered: false,
|
||||
},
|
||||
{ type: "thought", text: "Rendering the sample views." },
|
||||
{
|
||||
type: "tool",
|
||||
id: "render",
|
||||
title: "Render preview",
|
||||
kind: "read",
|
||||
status: "completed",
|
||||
locations: [],
|
||||
output: null,
|
||||
diffs: [],
|
||||
images: [image],
|
||||
},
|
||||
{
|
||||
type: "tool",
|
||||
id: "inspect",
|
||||
title: "Read preview metadata",
|
||||
kind: "read",
|
||||
status: "completed",
|
||||
locations: [],
|
||||
output: "Preview generated successfully.",
|
||||
diffs: [],
|
||||
},
|
||||
{ type: "agent", text: "The preview is ready: front, side and back." },
|
||||
];
|
||||
|
||||
for (const foldTurns of [true, false]) {
|
||||
test(`tool images remain visible and open a full preview with turn folding=${foldTurns}`, async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
if (!foldTurns) await page.setViewportSize({ width: 700, height: 750 });
|
||||
await page.evaluate(
|
||||
async ({ task, entries, foldTurns }) => {
|
||||
const storePath = "/src/features/agents/store.ts";
|
||||
const projectPath = "/src/platform/project.ts";
|
||||
const ipcPath = "/src/platform/ipc.ts";
|
||||
const store = await import(storePath);
|
||||
const { useProject } = await import(projectPath);
|
||||
const { commands } = await import(ipcPath);
|
||||
commands.agentEntries = async () => ({ status: "ok", data: entries });
|
||||
useProject.setState({ settings: { agents: { foldTurns, toolCalls: "grouped" } } });
|
||||
store.useAgents.setState({
|
||||
loaded: true,
|
||||
error: null,
|
||||
tasks: new Map([[task.id, task]]),
|
||||
entries: new Map([[task.id, entries]]),
|
||||
unread: new Set(),
|
||||
});
|
||||
store.openTaskInEditorLocation(task.id);
|
||||
},
|
||||
{ task, entries, foldTurns },
|
||||
);
|
||||
await expect(page.getByText("The preview is ready: front, side and back.", { exact: true })).toBeVisible();
|
||||
const preview = page.getByRole("img", { name: "Image", exact: true });
|
||||
await expect(preview).toBeVisible();
|
||||
await expect(preview).toHaveJSProperty("naturalWidth", 900);
|
||||
expect(await preview.evaluate((img) => img.closest("details") === null)).toBe(true);
|
||||
const box = (await preview.boundingBox())!;
|
||||
expect(box.x).toBeGreaterThanOrEqual(0);
|
||||
expect(box.x + box.width).toBeLessThanOrEqual(page.viewportSize()!.width);
|
||||
const fold = page.locator("details").first();
|
||||
await expect(fold).not.toHaveAttribute("open");
|
||||
await preview.click();
|
||||
const dialog = page.getByRole("dialog", { name: "Image", exact: true });
|
||||
await expect(dialog.getByRole("img")).toHaveJSProperty("naturalWidth", 900);
|
||||
await dialog.getByText("Close", { exact: true }).click();
|
||||
await expect(dialog).toHaveCount(0);
|
||||
await fold.locator("summary").first().click();
|
||||
await expect(preview).toHaveCount(1);
|
||||
await fold.locator("summary").first().click();
|
||||
await expect(preview).toBeVisible();
|
||||
});
|
||||
}
|
||||
@@ -274,6 +274,7 @@ test("completion clips long parameters before the suggestion name and return typ
|
||||
});
|
||||
await expect(row.locator(".cm-lsp-type")).toHaveText(returnType);
|
||||
await page.setViewportSize({ width: 820, height: 760 });
|
||||
await page.evaluate(() => document.fonts.ready);
|
||||
await expect
|
||||
.poll(() =>
|
||||
row.evaluate((el) => {
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import type { Locator, Page } from "@playwright/test";
|
||||
import { expect, openFromTree, stubDesktop, test } from "./fixtures";
|
||||
|
||||
/** Opens the sample with the server's lenses `titles` above its first line, at editor font `fontSize`. */
|
||||
async function lensRow(page: Page, fontSize: number, titles: string[]): Promise<{ editor: Locator; row: Locator }> {
|
||||
const editor = await openFromTree(page, "build.gradle.kts");
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(
|
||||
async ({ fontSize, titles }) => {
|
||||
const projectPath = "/src/platform/project.ts";
|
||||
const { useProject } = await import(/* @vite-ignore */ projectPath);
|
||||
const settings = useProject.getState().settings;
|
||||
useProject.setState({ settings: { ...settings, editor: { ...settings?.editor, fontSize } } });
|
||||
const at = { line: 0, col: 0 };
|
||||
window.__ipc.handlers.lsp_code_lens = () =>
|
||||
titles.map((title) => ({ range: { start: at, end: at }, command: { title, command: "noop", arguments: [] } }));
|
||||
},
|
||||
{ fontSize, titles },
|
||||
);
|
||||
// An edit asks the server for its lenses again.
|
||||
await editor.locator(".cm-line").first().click();
|
||||
await page.keyboard.press("End");
|
||||
await page.keyboard.type(" ");
|
||||
const row = editor.locator(".cm-openidea-lens");
|
||||
await expect(row).toContainText(titles[0]!);
|
||||
return { editor, row };
|
||||
}
|
||||
|
||||
test("a Code Vision row fits CJK hints at a large editor font", async ({ workbench: page }) => {
|
||||
const { editor, row } = await lensRow(page, 20, ["10 个用法", "无用法"]);
|
||||
const overflow = await row.evaluate((el) => {
|
||||
const box = el.getBoundingClientRect();
|
||||
return [...el.querySelectorAll(".cm-openidea-lensItem")].map((item) => {
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(item);
|
||||
const text = range.getBoundingClientRect();
|
||||
return Math.max(box.top - text.top, text.bottom - box.bottom);
|
||||
});
|
||||
});
|
||||
expect(overflow).toHaveLength(2);
|
||||
for (const px of overflow) expect(px).toBeLessThanOrEqual(0);
|
||||
// The editor measured the taller row: the lines below it still sit beside their numbers.
|
||||
const line = editor.locator(".cm-line", { hasText: "class OrderController" });
|
||||
const number = editor.locator(".cm-lineNumbers .cm-gutterElement", { hasText: /^8$/ });
|
||||
const [lineTop, numberTop] = [(await line.boundingBox())!.y, (await number.boundingBox())!.y];
|
||||
expect(Math.abs(lineTop - numberTop)).toBeLessThanOrEqual(1);
|
||||
});
|
||||
|
||||
test("a Code Vision row keeps its height at the default editor font", async ({ workbench: page }) => {
|
||||
const { row } = await lensRow(page, 13, ["3 usages"]);
|
||||
expect((await row.boundingBox())!.height).toBe(16);
|
||||
});
|
||||
@@ -0,0 +1,106 @@
|
||||
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
|
||||
|
||||
const className = "com.example.billing.SettlementSnapshot";
|
||||
const amountField = "crossBorderSettlementAmountInMinorUnitsBeforeExchangeRateAdjustment";
|
||||
const amount = "125486.75";
|
||||
const referenceField = "externalSettlementProcessorReconciliationReferenceForMonthlyReport";
|
||||
const reference = "EU-West / settlement batch 701 / reconciliation complete";
|
||||
|
||||
test("Memory Instances leaves room for field values and referrer actions in a narrow dock", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 1180, height: 720 });
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(
|
||||
async ({ className, amountField, amount, referenceField, reference }) => {
|
||||
const debugModule = "/src/features/debugger/state.ts";
|
||||
const layoutModule = "/src/workbench/toolwindows/store.ts";
|
||||
const { adoptSession } = await import(/* @vite-ignore */ debugModule);
|
||||
const { moveToolWindow, setToolWindowSize, showToolWindow } = await import(/* @vite-ignore */ layoutModule);
|
||||
const h = window.__ipc.handlers;
|
||||
h.debug_jvm_memory_classes = () => ({
|
||||
status: "ready",
|
||||
snapshot: {
|
||||
rows: [{ name: className, instances: 1, bytes: 48, deltaInstances: null, deltaBytes: null, module: null }],
|
||||
totalInstances: 1,
|
||||
totalBytes: 48,
|
||||
hasBaseline: false,
|
||||
elapsedMs: 2,
|
||||
source: "debugger",
|
||||
javaVersion: "21",
|
||||
takenWhileSuspended: true,
|
||||
},
|
||||
});
|
||||
h.debug_jvm_memory_instances = () => ({
|
||||
status: "ready",
|
||||
generation: 1,
|
||||
instances: [{ kind: "object", typeName: className, id: 12 }],
|
||||
truncated: false,
|
||||
});
|
||||
h.debug_jvm_memory_fields = ({ object }) => ({
|
||||
status: "ready",
|
||||
fields:
|
||||
(object as { id: number }).id === 12
|
||||
? [
|
||||
{ name: amountField, value: { kind: "primitive", typeName: "double", text: amount } },
|
||||
{ name: referenceField, value: { kind: "string", text: reference, length: reference.length, id: 16 } },
|
||||
]
|
||||
: [],
|
||||
});
|
||||
h.debug_jvm_memory_referrers = () => ({
|
||||
status: "ready",
|
||||
referrers: [{ value: { kind: "object", id: 12, typeName: className }, via: [referenceField] }],
|
||||
truncated: false,
|
||||
});
|
||||
adoptSession(91, {
|
||||
name: "Billing Service",
|
||||
adapter: "java-debug",
|
||||
status: "paused",
|
||||
stops: 1,
|
||||
caps: { jvmMemory: true, jvmInstances: true },
|
||||
});
|
||||
moveToolWindow("debug", "right");
|
||||
setToolWindowSize("right", 330);
|
||||
showToolWindow("debug", true);
|
||||
},
|
||||
{ className, amountField, amount, referenceField, reference },
|
||||
);
|
||||
|
||||
const debug = page.getByRole("region", { name: "Debug", exact: true });
|
||||
await debug.getByRole("tab", { name: "Memory", exact: true }).click();
|
||||
await debug.getByRole("row").filter({ hasText: className }).dblclick();
|
||||
const title = `Instances of ${className}`;
|
||||
const instances = debug.getByRole("region", { name: title, exact: true });
|
||||
const tree = instances.getByRole("tree", { name: title });
|
||||
const root = tree.getByRole("treeitem", { name: /SettlementSnapshot@12/ });
|
||||
await root.locator("[data-tree-toggle]").click();
|
||||
|
||||
const fieldName = instances.getByText(amountField, { exact: true });
|
||||
const fieldValue = instances.getByText(amount, { exact: true });
|
||||
const fits = (el: Element) => el.clientWidth > 0 && el.scrollWidth <= el.clientWidth + 1;
|
||||
await expect.poll(() => fieldValue.evaluate(fits)).toBe(true);
|
||||
await expect.poll(() => fieldName.evaluate(fits)).toBe(false);
|
||||
await expect(fieldName).toHaveAttribute("title", amountField);
|
||||
await expect(fieldValue).toHaveAttribute("title", amount);
|
||||
await expect(instances.getByText(title, { exact: true })).toHaveCSS(
|
||||
"font-family",
|
||||
await instances.evaluate((el) => getComputedStyle(el).fontFamily),
|
||||
);
|
||||
|
||||
const referrerRow = tree.getByRole("treeitem").filter({ hasText: referenceField });
|
||||
const showReferrers = referrerRow.getByRole("button", { name: "Show Referrers" });
|
||||
await referrerRow.hover();
|
||||
await expect(showReferrers).toBeInViewport({ ratio: 1 });
|
||||
await showReferrers.press("Enter");
|
||||
await expect(tree.getByText("Referrers", { exact: true })).toBeVisible();
|
||||
expect(await ipcCalls(page, "debug_jvm_memory_referrers")).toHaveLength(1);
|
||||
|
||||
await page.evaluate(async () => {
|
||||
const layoutModule = "/src/workbench/toolwindows/store.ts";
|
||||
const { moveToolWindow, setToolWindowSize } = await import(/* @vite-ignore */ layoutModule);
|
||||
moveToolWindow("debug", "bottom");
|
||||
setToolWindowSize("bottom", 400);
|
||||
});
|
||||
await expect.poll(() => fieldName.evaluate(fits)).toBe(true);
|
||||
await expect.poll(() => fieldValue.evaluate(fits)).toBe(true);
|
||||
});
|
||||
@@ -487,6 +487,45 @@ test("Markdown preview highlights ⌘F matches, selected words and scales diagra
|
||||
expect(reset.excalidraw).toBeCloseTo(base.excalidraw, 1);
|
||||
});
|
||||
|
||||
for (const mode of ["Preview Only", "Editor and Preview"]) {
|
||||
test(`Markdown ${mode} reveals a cross-file heading on first open`, async ({ workbench: page }) => {
|
||||
const path = "/dev/acme-api/linked-heading.md";
|
||||
const heading = "5.2 状态机";
|
||||
const spacer = Array.from({ length: 80 }, (_, i) => `Paragraph ${i}.`).join("\n\n");
|
||||
const target = `# Destination\n\n${spacer}\n\n## ${heading}\n\n${spacer}`;
|
||||
const editor = await openFromTree(page, "README.md");
|
||||
await page.evaluate(
|
||||
async ({ path, target }) => {
|
||||
const backendModule = "/src/editor/core/backend.ts";
|
||||
const routeModule = "/src/platform/tauriCore.ts";
|
||||
const { docBackend } = await import(/* @vite-ignore */ backendModule);
|
||||
const { setInvokeRoute } = await import(/* @vite-ignore */ routeModule);
|
||||
docBackend().files.set(path, target);
|
||||
setInvokeRoute((cmd: string, args?: Record<string, unknown>) =>
|
||||
cmd === "fs_read_text" && args?.path === path ? Promise.resolve(target) : null,
|
||||
);
|
||||
},
|
||||
{ path, target },
|
||||
);
|
||||
|
||||
await editor.locator(".cm-content").focus();
|
||||
await page.keyboard.press("Meta+a");
|
||||
await page.keyboard.insertText("[Linked heading](linked-heading.md#52-%E7%8A%B6%E6%80%81%E6%9C%BA)");
|
||||
if (mode === "Preview Only") await page.getByRole("button", { name: mode, exact: true }).click();
|
||||
|
||||
const destinationTab = page.getByRole("tab", { name: "linked-heading.md", exact: true });
|
||||
const preview = page.getByRole("document", { name: "Markdown preview" });
|
||||
await expect(destinationTab).toHaveCount(0);
|
||||
await preview.getByRole("link", { name: "Linked heading" }).click();
|
||||
await expect(destinationTab).toHaveAttribute("aria-selected", "true");
|
||||
await expect(page.getByRole("button", { name: mode, exact: true })).toHaveAttribute("aria-pressed", "true");
|
||||
await expect(preview.getByRole("heading", { name: heading })).toBeInViewport({ ratio: 1 });
|
||||
if (mode === "Editor and Preview") {
|
||||
await expect(editor.locator(".cm-line", { hasText: heading })).toBeInViewport({ ratio: 1 });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
test("Markdown preview keeps following find and edits after scrolling the source", async ({ workbench: page }) => {
|
||||
const editor = await openFromTree(page, "README.md");
|
||||
const content = editor.locator(".cm-content");
|
||||
@@ -629,6 +668,91 @@ test("single-line selection stays on its own row when font glyphs exceed line he
|
||||
expect(Math.abs(selBox!.height - lineBox!.height)).toBeLessThanOrEqual(1);
|
||||
});
|
||||
|
||||
test("find and occurrence highlights stay on their own row when font glyphs exceed line height", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.evaluate(async () => {
|
||||
const projectModule = "/src/platform/project.ts";
|
||||
const schemaModule = "/src/features/settings/model/schema.ts";
|
||||
const [{ useProject }, { DEFAULT_SETTINGS }] = await Promise.all([
|
||||
import(/* @vite-ignore */ projectModule),
|
||||
import(/* @vite-ignore */ schemaModule),
|
||||
]);
|
||||
const base = useProject.getState().settings ?? DEFAULT_SETTINGS;
|
||||
useProject.setState({
|
||||
settings: { ...base, editor: { ...base.editor, fontSize: 18, lineHeight: 18 } },
|
||||
});
|
||||
const root = document.documentElement.style;
|
||||
root.setProperty("--bg-editor", "#ffffff");
|
||||
root.setProperty("--bg-current-line", "#ffffff");
|
||||
root.setProperty("--bg-identifier-under-caret", "#cc0000");
|
||||
root.setProperty("--bg-search-match", "#cc00cc");
|
||||
root.setProperty("--bg-search-match-current", "#cc8800");
|
||||
await document.fonts.ready;
|
||||
});
|
||||
|
||||
const editor = await openFromTree(page, "README.md");
|
||||
const content = editor.locator(".cm-content");
|
||||
await content.click();
|
||||
await page.keyboard.press("Meta+a");
|
||||
await page.keyboard.insertText(
|
||||
[" ", "description", " ", "description", " "].join("\n"),
|
||||
);
|
||||
|
||||
const lines = editor.locator(".cm-line");
|
||||
await expect(lines).toHaveCount(5);
|
||||
|
||||
const blankRowsAreUnpainted = async () => {
|
||||
const [editorBox, b0, b2, b4, matchBox] = await Promise.all([
|
||||
editor.boundingBox(),
|
||||
lines.nth(0).boundingBox(),
|
||||
lines.nth(2).boundingBox(),
|
||||
lines.nth(4).boundingBox(),
|
||||
lines.nth(1).boundingBox(),
|
||||
]);
|
||||
const png = await editor.screenshot();
|
||||
const base64 = png.toString("base64");
|
||||
return page.evaluate(
|
||||
async ({ base64, editorBox, blanks, probeX }) => {
|
||||
const img = new Image();
|
||||
img.src = `data:image/png;base64,${base64}`;
|
||||
await img.decode();
|
||||
const scale = img.width / editorBox!.width;
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = img.width;
|
||||
canvas.height = img.height;
|
||||
const ctx = canvas.getContext("2d")!;
|
||||
ctx.drawImage(img, 0, 0);
|
||||
const x = Math.round((probeX - editorBox!.x) * scale);
|
||||
for (const row of blanks) {
|
||||
const yStart = Math.ceil((row!.y - editorBox!.y) * scale) + 1;
|
||||
const yEnd = Math.floor((row!.y + row!.height - editorBox!.y) * scale) - 1;
|
||||
for (let y = yStart; y <= yEnd; y++) {
|
||||
const [r, g, b] = ctx.getImageData(x, y, 1, 1).data;
|
||||
if (r !== 255 || g !== 255 || b !== 255) return { ok: false, x, y, rgb: [r, g, b] };
|
||||
}
|
||||
}
|
||||
return { ok: true };
|
||||
},
|
||||
{ base64, editorBox, blanks: [b0, b2, b4], probeX: matchBox!.x + 30 },
|
||||
);
|
||||
};
|
||||
|
||||
// Selection match on line 4 (`description`) when line 2 is selected.
|
||||
await lines.nth(1).dblclick();
|
||||
await expect(editor.locator(".cm-selectionMatch")).toHaveCount(1);
|
||||
expect(await blankRowsAreUnpainted()).toEqual({ ok: true });
|
||||
|
||||
// Find matches: line 2 is `.cm-openidea-findMatch-current` (with 1px frame), line 4 is `.cm-openidea-findMatch`.
|
||||
await page.keyboard.press("Meta+f");
|
||||
const find = page.getByRole("textbox", { name: "Find" });
|
||||
await expect(find).toBeFocused();
|
||||
await find.fill("description");
|
||||
await expect(editor.locator(".cm-openidea-findMatch-current")).toHaveCount(1);
|
||||
await expect(editor.locator(".cm-openidea-findMatch")).toHaveCount(2);
|
||||
expect(await blankRowsAreUnpainted()).toEqual({ ok: true });
|
||||
});
|
||||
|
||||
test("vertical tabs leave a narrow editor group most of its width", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 900, height: 600 });
|
||||
await openFromTree(page, "settings.gradle.kts");
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
|
||||
|
||||
// #5402: an External Tool run from Find Action resolves $FilePath$ against the focused component,
|
||||
// the Project view's selected file while the tree has focus, else the editor's file.
|
||||
test("External Tools take $FilePath$ from the Project view selection, else the editor", async ({ workbench: page }) => {
|
||||
await page.getByRole("treeitem", { name: "README.md", exact: true }).dblclick();
|
||||
const editor = page.locator(".cm-content");
|
||||
await expect(editor).toBeFocused();
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async () => {
|
||||
const projectPath = "/src/platform/project.ts";
|
||||
const { useProject } = await import(/* @vite-ignore */ projectPath);
|
||||
const tool = { id: "echo", name: "Echo File Path", program: "echo", arguments: "$FilePath$ $FileName$" };
|
||||
useProject.setState({ settings: { externalTools: [{ ...tool, openConsole: false, synchronizeAfter: false }] } });
|
||||
let id = 0;
|
||||
window.__ipc.handlers.run_start = ({ config }) => {
|
||||
id++;
|
||||
// Exits at once, so the next run of the same tool doesn't ask to stop this one.
|
||||
window.__ipc.emit({ type: "runExited", run: id, code: 0 });
|
||||
return {
|
||||
id,
|
||||
configId: (config as { id: string }).id,
|
||||
name: (config as { name: string }).name,
|
||||
pid: 4242,
|
||||
running: true,
|
||||
pty: false,
|
||||
};
|
||||
};
|
||||
});
|
||||
|
||||
const runTool = async () => {
|
||||
await page.keyboard.press("Meta+Shift+A");
|
||||
const search = page.getByRole("dialog", { name: "Search Everywhere", exact: true });
|
||||
await search.getByRole("combobox").fill("Echo File Path");
|
||||
await expect(search.getByRole("option", { name: /Echo File Path/ })).toBeVisible();
|
||||
await search.getByRole("combobox").press("Enter");
|
||||
await expect(search).toBeHidden();
|
||||
};
|
||||
const startedArgs = async () =>
|
||||
(await ipcCalls(page, "run_start")).map((c) => (c as { config: { args: string[] } }).config.args);
|
||||
|
||||
await page.getByRole("treeitem", { name: "build.gradle.kts", exact: true }).click();
|
||||
await runTool();
|
||||
await expect.poll(startedArgs).toEqual([["/dev/acme-api/build.gradle.kts", "build.gradle.kts"]]);
|
||||
|
||||
await editor.click();
|
||||
await runTool();
|
||||
await expect.poll(startedArgs).toEqual([
|
||||
["/dev/acme-api/build.gradle.kts", "build.gradle.kts"],
|
||||
["/dev/acme-api/README.md", "README.md"],
|
||||
]);
|
||||
});
|
||||
@@ -0,0 +1,51 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import { expect, stubDesktop, test } from "./fixtures";
|
||||
|
||||
async function stubProjectTypes(page: Page, types: string[]) {
|
||||
await stubDesktop(page);
|
||||
await page.evaluate((types) => {
|
||||
const h = window.__ipc.handlers;
|
||||
h.index_file_extensions = () => types.map((extension, i) => ({ extension, files: 100 - i }));
|
||||
h.languages = () => types.map((extension) => ({ id: extension, name: extension, extensions: [extension] }));
|
||||
h.search_validate = () => null;
|
||||
}, types);
|
||||
}
|
||||
|
||||
async function openMaskMenu(page: Page) {
|
||||
await page.keyboard.press("Meta+Shift+f");
|
||||
const dialog = page.getByRole("dialog", { name: "Find in Files" });
|
||||
await dialog.getByRole("button", { name: "Recent file masks" }).click();
|
||||
const menu = page.getByRole("menu").last();
|
||||
await expect(menu).toBeVisible();
|
||||
return menu;
|
||||
}
|
||||
|
||||
test("the file mask menu offers every known file type in the project", async ({ workbench: page }) => {
|
||||
await stubProjectTypes(page, ["rs", "md", "json", "toml", "yml", "properties"]);
|
||||
const menu = await openMaskMenu(page);
|
||||
await expect(menu.getByRole("menuitem")).toHaveText(["*.rs", "*.md", "*.json", "*.toml", "*.yml", "*.properties"]);
|
||||
await menu.getByRole("menuitem", { name: "*.properties" }).click();
|
||||
await expect(page.getByRole("textbox", { name: "File mask" })).toHaveValue("*.properties");
|
||||
});
|
||||
|
||||
test("a long file mask menu stays inside the window and scrolls to its last type", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 1040, height: 520 });
|
||||
const types = Array.from({ length: 40 }, (_, i) => `type${String(i).padStart(2, "0")}`);
|
||||
await stubProjectTypes(page, types);
|
||||
const menu = await openMaskMenu(page);
|
||||
const popup = menu.locator("..");
|
||||
await expect(menu.getByRole("menuitem")).toHaveCount(40);
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const { y, height } = (await popup.boundingBox())!;
|
||||
return y >= 0 && y + height <= 520;
|
||||
})
|
||||
.toBe(true);
|
||||
|
||||
await menu.getByRole("menuitem").first().focus();
|
||||
await page.keyboard.press("End");
|
||||
const last = menu.getByRole("menuitem", { name: "*.type39" });
|
||||
await expect(last).toBeFocused();
|
||||
await expect(last).toBeInViewport();
|
||||
await expect.poll(async () => popup.evaluate((node) => node.scrollTop)).toBeGreaterThan(0);
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
import { expect, openFromTree, test } from "./fixtures";
|
||||
|
||||
test("multiline editor search keeps three visible lines and replaces with the full text", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
const editor = await openFromTree(page, "build.gradle.kts");
|
||||
await page.setViewportSize({ width: 540, height: 500 });
|
||||
const content = editor.locator(".cm-content");
|
||||
const query = "currency=EUR\nregion=eu-west\npipeline=clearing\nmode=batch\ntimeout=30\nretries=2";
|
||||
const replacement = query.replace("clearing", "settlement").replace("timeout=30", "timeout=45");
|
||||
await content.press("Meta+a");
|
||||
await page.keyboard.insertText(`[ledger]\n${query}\n\n[reporting]\n${query}\n`);
|
||||
await content.press("Escape");
|
||||
await content.press("Meta+r");
|
||||
|
||||
const bar = page.getByRole("search", { name: "Replace in file" });
|
||||
const find = bar.getByRole("textbox", { name: "Find", exact: true });
|
||||
const replace = bar.getByRole("textbox", { name: "Replace", exact: true });
|
||||
await find.fill(query);
|
||||
await replace.fill(replacement);
|
||||
for (const field of [find, replace]) {
|
||||
const visibleLines = await field.evaluate((el) => el.clientHeight / parseFloat(getComputedStyle(el).lineHeight));
|
||||
expect(visibleLines).toBeCloseTo(3);
|
||||
await field.press("Control+End");
|
||||
await expect.poll(() => field.evaluate((el) => el.scrollTop)).toBeGreaterThan(0);
|
||||
}
|
||||
await expect(find).toHaveValue(query);
|
||||
await expect(replace).toHaveValue(replacement);
|
||||
const count = bar.locator("[aria-live]");
|
||||
await expect(count).toHaveText(/\/2$/);
|
||||
const selected = await count.innerText();
|
||||
const next = bar.getByRole("button", { name: /Next Occurrence/ });
|
||||
await next.click();
|
||||
await expect(count).toHaveText(/^[12]\/2$/);
|
||||
await expect(count).not.toHaveText(selected);
|
||||
|
||||
await bar.getByRole("button", { name: "Replace All", exact: true }).click();
|
||||
await expect(editor.locator(".cm-line", { hasText: "timeout=45" })).toHaveCount(2);
|
||||
await expect(editor.locator(".cm-line", { hasText: "pipeline=clearing" })).toHaveCount(0);
|
||||
await bar.getByRole("button", { name: "Close", exact: true }).click();
|
||||
await expect(content).toBeFocused();
|
||||
await content.press("Meta+z");
|
||||
await expect(editor.locator(".cm-line", { hasText: "pipeline=clearing" })).toHaveCount(2);
|
||||
});
|
||||
@@ -0,0 +1,83 @@
|
||||
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
|
||||
|
||||
test("New Worktree keeps form fields aligned and creates the selected worktree in a short window", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 1120, height: 740 });
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async () => {
|
||||
const root = "/dev/acme-api";
|
||||
const service = `${root}/service`;
|
||||
window.__ipc.handlers.vcs_branches = () => [{ name: "main", current: true, remote: false }];
|
||||
window.__ipc.handlers.vcs_tags = () => [];
|
||||
window.__ipc.handlers.vcs_worktrees = ({ repo }) => [{ path: repo, branch: "main", main: true, submodule: false }];
|
||||
window.__ipc.handlers.vcs_worktree_include = () => ({ exists: true });
|
||||
window.__ipc.handlers.vcs_add_worktree = () => ({ copyWarning: null, setupWarning: null });
|
||||
const store = "/src/features/vcs/store.ts";
|
||||
const { useVcs } = await import(/* @vite-ignore */ store);
|
||||
useVcs.setState({ root, roots: [root, service], repo: root, available: true });
|
||||
const context = "/src/platform/context.ts";
|
||||
const { setContext } = await import(/* @vite-ignore */ context);
|
||||
setContext("vcsAvailable", true);
|
||||
const actions = "/src/platform/actions.ts";
|
||||
const { executeAction } = await import(/* @vite-ignore */ actions);
|
||||
await executeAction("vcs.newWorktree");
|
||||
});
|
||||
|
||||
const dialog = page.getByRole("dialog", { name: "New Worktree" });
|
||||
const name = dialog.getByRole("textbox", { name: "Name:" });
|
||||
const branch = dialog.getByRole("textbox", { name: "New branch name" });
|
||||
const location = dialog.getByRole("textbox", { name: "Location:" });
|
||||
const repository = dialog.getByRole("button", { name: "Repository", exact: true });
|
||||
const checkout = dialog.getByRole("button", { name: "Check out", exact: true });
|
||||
const setup = dialog.getByRole("checkbox", { name: "Run setup script" });
|
||||
const script = dialog.getByRole("textbox", { name: "Setup script:" });
|
||||
await expect(name).toHaveValue("acme-api-main-wt");
|
||||
await branch.fill("review/ledger-batch");
|
||||
await name.fill("ledger-review");
|
||||
await location.fill("/dev/reviews");
|
||||
await setup.check();
|
||||
await script.fill("/dev/setup.sh");
|
||||
const preview = dialog.getByText("Worktree location: /dev/reviews/ledger-review", { exact: true });
|
||||
await expect(preview).toBeVisible();
|
||||
|
||||
for (const size of [
|
||||
{ width: 1120, height: 740 },
|
||||
{ width: 440, height: 520 },
|
||||
]) {
|
||||
await page.setViewportSize(size);
|
||||
const column = (await name.boundingBox())!.x;
|
||||
for (const [label, field] of [
|
||||
["Name:", name],
|
||||
["Location:", location],
|
||||
["Repository:", repository],
|
||||
["Check out:", checkout],
|
||||
["Create a new branch", branch],
|
||||
["Setup script:", script],
|
||||
] as const) {
|
||||
const caption = dialog.getByText(label, { exact: true });
|
||||
await expect(caption).toBeVisible();
|
||||
const captionBox = (await caption.boundingBox())!;
|
||||
const fieldBox = (await field.boundingBox())!;
|
||||
expect(fieldBox.x, label).toBeCloseTo(column, 0);
|
||||
expect(captionBox.x + captionBox.width, label).toBeLessThanOrEqual(fieldBox.x);
|
||||
expect(captionBox.y + captionBox.height / 2, label).toBeCloseTo(fieldBox.y + fieldBox.height / 2, 0);
|
||||
}
|
||||
expect((await preview.boundingBox())!.x).toBeCloseTo(column, 0);
|
||||
}
|
||||
|
||||
await setup.uncheck();
|
||||
await expect(script).toHaveCount(0);
|
||||
await dialog.getByRole("button", { name: "Create", exact: true }).click();
|
||||
await expect(dialog).toHaveCount(0);
|
||||
expect(await ipcCalls(page, "vcs_add_worktree")).toEqual([
|
||||
{
|
||||
repo: "/dev/acme-api",
|
||||
path: "/dev/reviews/ledger-review",
|
||||
commitish: "refs/heads/main",
|
||||
newBranch: "review/ledger-batch",
|
||||
copyConfig: true,
|
||||
setup: null,
|
||||
},
|
||||
]);
|
||||
});
|
||||
@@ -5,14 +5,29 @@ test.use({ video: "on" });
|
||||
test("offers file templates for the selected workspace member", async ({ workbench: page }) => {
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async () => {
|
||||
const markers: Record<string, string> = {
|
||||
"/work/api": "go.mod",
|
||||
"/work/web": "pom.xml",
|
||||
"/work/library": "pom.xml",
|
||||
const markers: Record<string, string[]> = {
|
||||
"/work/api": ["go.mod"],
|
||||
"/work/web": ["pom.xml"],
|
||||
"/work/library": ["pom.xml"],
|
||||
"/work/tutor": ["package.json", "vite.config.ts"],
|
||||
};
|
||||
window.__ipc.handlers.fs_read_dir = ({ path }) => {
|
||||
const name = markers[String(path)];
|
||||
return name ? [{ name, path: `${path}/${name}`, kind: "file", size: 0, mtimeMs: 0 }] : [];
|
||||
const files = (markers[String(path)] ?? []).map((name) => ({
|
||||
name,
|
||||
path: `${path}/${name}`,
|
||||
kind: "file",
|
||||
size: 0,
|
||||
mtimeMs: 0,
|
||||
}));
|
||||
return path === "/work/tutor"
|
||||
? [...files, { name: "src", path: "/work/tutor/src", kind: "dir", size: 0, mtimeMs: 0 }]
|
||||
: files;
|
||||
};
|
||||
const backend = "/src/editor/core/backend.ts";
|
||||
const { docBackend } = await import(/* @vite-ignore */ backend);
|
||||
window.__ipc.handlers.fs_create_file = ({ path }) => {
|
||||
docBackend().files.set(String(path), "");
|
||||
return null;
|
||||
};
|
||||
window.__ipc.handlers.run_configs = () => [
|
||||
{
|
||||
@@ -54,6 +69,7 @@ test("offers file templates for the selected workspace member", async ({ workben
|
||||
await expect(page.getByRole("menuitem", { name: "Go Module", exact: true })).toBeVisible();
|
||||
await expect(page.getByRole("menuitem", { name: "JSON File", exact: true })).toBeVisible();
|
||||
await expect(page.getByRole("menuitem", { name: "Java Class", exact: true })).toHaveCount(0);
|
||||
await expect(page.getByRole("menuitem", { name: "Svelte Component", exact: true })).toHaveCount(0);
|
||||
await expect(page.getByRole("menuitem", { name: "Tomcat Context Descriptor", exact: true })).toHaveCount(0);
|
||||
await page.keyboard.press("Escape");
|
||||
await page.keyboard.press("Escape");
|
||||
@@ -73,6 +89,23 @@ test("offers file templates for the selected workspace member", async ({ workben
|
||||
await expect(popup.getByText("Java Class", { exact: true })).toBeVisible();
|
||||
await expect(popup.getByText("Tomcat Context Descriptor", { exact: true })).toHaveCount(0);
|
||||
await expect(popup.getByText("Go File", { exact: true })).toHaveCount(0);
|
||||
await page.keyboard.press("Escape");
|
||||
|
||||
const tutor = page.getByRole("treeitem", { name: "tutor /work/tutor", exact: true });
|
||||
if ((await tutor.getAttribute("aria-expanded")) !== "true") await tutor.locator("[data-tree-toggle]").click();
|
||||
await newMenu("/work/tutor/src");
|
||||
const component = page.getByRole("menuitem", { name: "Svelte Component", exact: true });
|
||||
await expect(component).toBeVisible();
|
||||
await page.screenshot({ path: test.info().outputPath("svelte-new-menu.png"), animations: "disabled" });
|
||||
await component.click();
|
||||
const svelte = page.getByRole("dialog", { name: "New Svelte Component", exact: true });
|
||||
const name = svelte.getByRole("textbox", { name: "Name", exact: true });
|
||||
await name.fill("+page.svelte");
|
||||
await name.press("Enter");
|
||||
await expect(svelte).toBeHidden();
|
||||
expect(await ipcCalls(page, "fs_create_file")).toEqual([{ path: "/work/tutor/src/+page.svelte" }]);
|
||||
await expect(page.getByRole("tab", { name: "+page.svelte" })).toHaveAttribute("aria-selected", "true");
|
||||
await expect(page.locator(".cm-content")).toContainText("<script>");
|
||||
});
|
||||
|
||||
test("uses the single project's type in the keyboard New popup", async ({ workbench: page }) => {
|
||||
|
||||
+15
-2
@@ -37,6 +37,15 @@ test("type-ahead jumps to a matching node", async ({ workbench: page }) => {
|
||||
await expect(tree.locator('[role="treeitem"][aria-selected="true"]')).toHaveText("README.md");
|
||||
});
|
||||
|
||||
test("a single click shows the file in the preview tab, which the next one reuses", async ({ workbench: page }) => {
|
||||
const tabs = page.getByRole("tablist", { name: "Editor tabs" });
|
||||
await page.getByRole("treeitem", { name: "README.md", exact: true }).click();
|
||||
await expect(tabs.getByRole("tab", { name: "README.md" })).toBeVisible();
|
||||
await page.getByRole("treeitem", { name: "settings.gradle.kts", exact: true }).click();
|
||||
await expect(tabs.getByRole("tab", { name: "settings.gradle.kts" })).toBeVisible();
|
||||
await expect(tabs.getByRole("tab", { name: "README.md" })).toHaveCount(0);
|
||||
});
|
||||
|
||||
test("Rename targets a file or folder directly from its context menu", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 720, height: 480 });
|
||||
const menu = page.getByRole("menu", { name: "Context menu" });
|
||||
@@ -90,6 +99,7 @@ test("Git ignore submenu offers shared and local destinations for files and fold
|
||||
});
|
||||
|
||||
test("keeps New open on a slow diagonal path across sibling items", async ({ workbench: page }) => {
|
||||
await page.clock.install();
|
||||
await page.getByRole("treeitem", { name: "README.md", exact: true }).click({ button: "right" });
|
||||
const parent = page.getByRole("menuitem", { name: "New", exact: true });
|
||||
const box = (await parent.boundingBox())!;
|
||||
@@ -101,13 +111,16 @@ test("keeps New open on a slow diagonal path across sibling items", async ({ wor
|
||||
.filter({ has: page.getByRole("menuitem", { name: "Directory", exact: true }) });
|
||||
const target = (await submenu.getByRole("menuitem").last().boundingBox())!;
|
||||
const end = { x: target.x + 20, y: target.y + target.height / 2 };
|
||||
// Keep the gesture cadence independent of the runner's input and assertion round trips.
|
||||
await page.clock.pauseAt(new Date(Date.now() + 1000));
|
||||
for (let step = 1; step <= 10; step++) {
|
||||
await page.mouse.move(start.x + ((end.x - start.x) * step) / 10, start.y + ((end.y - start.y) * step) / 10);
|
||||
await page.waitForTimeout(75);
|
||||
await page.clock.runFor(75);
|
||||
await expect(parent).toHaveAttribute("aria-expanded", "true");
|
||||
}
|
||||
await page.waitForTimeout(350);
|
||||
await page.clock.runFor(350);
|
||||
await expect(parent).toHaveAttribute("aria-expanded", "true");
|
||||
await page.clock.resume();
|
||||
await page.keyboard.press("Escape");
|
||||
await page.keyboard.press("Escape");
|
||||
});
|
||||
|
||||
@@ -12,9 +12,8 @@ test("the scratch language chooser fits short windows and keeps recents separate
|
||||
const { setScratchBackend } = await import(/* @vite-ignore */ scratch);
|
||||
const { rememberLanguage } = await import(/* @vite-ignore */ store);
|
||||
setScratchBackend({
|
||||
dataDir: async () => "/test-app-data",
|
||||
scratchesDir: async () => "/test-app-data/scratches",
|
||||
listNames: async () => [],
|
||||
createDir: async () => {},
|
||||
createFile: async () => {},
|
||||
languages: async () => [
|
||||
...Array.from({ length: 24 }, (_, i) => {
|
||||
|
||||
+5
-2
@@ -14,7 +14,7 @@ test("double Shift opens Search Everywhere with its tabs; Escape closes it", asy
|
||||
});
|
||||
|
||||
test("Search Everywhere finds and runs an action", async ({ workbench: page }) => {
|
||||
await doubleShift(page);
|
||||
await page.locator("header").getByRole("button", { name: "Search Everywhere", exact: true }).click();
|
||||
const dialog = page.getByRole("dialog", { name: "Search Everywhere" });
|
||||
await dialog.getByRole("combobox").fill("Language Servers");
|
||||
const option = dialog.getByRole("option", { name: /Language Servers/ }).first();
|
||||
@@ -122,7 +122,10 @@ test("Find in Files streams matches by file and opens the chosen one at its line
|
||||
const expected = getComputedStyle(probe).backgroundColor;
|
||||
probe.remove();
|
||||
const own = getComputedStyle(el);
|
||||
return own.backgroundColor === expected && own.color === getComputedStyle(el.parentElement!).color;
|
||||
return (
|
||||
(own.backgroundColor === expected || own.backgroundImage.includes(expected)) &&
|
||||
own.color === getComputedStyle(el.parentElement!).color
|
||||
);
|
||||
}),
|
||||
).toBe(true);
|
||||
const originalPreview = await preview.textContent();
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
* header on screen: titles stay on one line and every header control lies inside the popup.
|
||||
*/
|
||||
import type { Page } from "@playwright/test";
|
||||
import { expect, openFromTree, stubDesktop, test } from "./fixtures";
|
||||
import { expect, ipcCalls, openFromTree, stubDesktop, test } from "./fixtures";
|
||||
|
||||
const LONG_RESULT_PATH = "config/RegionalOrderReconciliationEndpointsForSandboxEnvironments.txt";
|
||||
|
||||
@@ -118,6 +118,35 @@ test.describe("search popups at the minimum window width", () => {
|
||||
await dialog.getByRole("button", { name: /Browse/ }).click({ trial: true });
|
||||
});
|
||||
|
||||
test("multi-line search and replacement leave room for matches and scroll inside their fields", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await stubFindMatches(page);
|
||||
await run(page, "find.replaceInPath");
|
||||
const dialog = page.getByRole("dialog", { name: "Replace in Files" });
|
||||
const search = dialog.getByRole("textbox", { name: "Text to find" });
|
||||
const replacement = dialog.getByRole("textbox", { name: "Replace with" });
|
||||
const query = "base=http://localhost:8080\nregion=eu-west\nmode=batch\nverify=true\nretry=2\ntimeout=30";
|
||||
const changed = query.replace("localhost:8080", "localhost:9443").replace("retry=2", "retry=4");
|
||||
await search.fill(query);
|
||||
await replacement.fill(changed);
|
||||
for (const field of [search, replacement]) {
|
||||
const visibleLines = await field.evaluate((el) => el.clientHeight / parseFloat(getComputedStyle(el).lineHeight));
|
||||
expect(visibleLines).toBeCloseTo(3);
|
||||
await field.press("Control+End");
|
||||
await expect.poll(() => field.evaluate((el) => el.scrollTop)).toBeGreaterThan(0);
|
||||
}
|
||||
await expect(search).toHaveValue(query);
|
||||
await expect(replacement).toHaveValue(changed);
|
||||
await expect(dialog.getByRole("listbox", { name: "Matches" }).getByRole("option").first()).toBeInViewport();
|
||||
const calls = await ipcCalls(page, "search_start");
|
||||
expect(calls.some(({ query: sent }) => (sent as { pattern: string }).pattern === query)).toBe(true);
|
||||
await expect(dialog.getByRole("button", { name: "Replace All", exact: true })).toBeInViewport({ ratio: 1 });
|
||||
|
||||
await replacement.fill("updated");
|
||||
await expect(replacement).toHaveAttribute("rows", "1");
|
||||
});
|
||||
|
||||
test("Replace in Files keeps its footer actions together as the window narrows", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 1120, height: 750 });
|
||||
await openFromTree(page, "settings.gradle.kts");
|
||||
|
||||
+439
-1
@@ -1,5 +1,5 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import { expect, test } from "./fixtures";
|
||||
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
|
||||
|
||||
/** Supply detected configurations without launching desktop processes. */
|
||||
async function configure(page: Page, extra = 0) {
|
||||
@@ -241,3 +241,441 @@ test("the Services detail pane adds no second scrollbar over a console", async (
|
||||
expect(result.scrollers.filter((c) => c.includes("detailPane") || c.includes("_panel_"))).toEqual([]);
|
||||
expect(result.scrollers.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
test("Docker dashboard keeps multi-line container commands bounded and collapsible", async ({ workbench: page }) => {
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async () => {
|
||||
const script = Array.from({ length: 18 }, (_, i) => ` export STEP_${i}="/persist/slot-${i}"`).join("\n");
|
||||
const inspectJson = JSON.stringify([
|
||||
{
|
||||
Created: "2026-11-22T01:41:28Z",
|
||||
State: { Status: "running", Pid: 2048, StartedAt: "2026-11-22T01:41:29Z" },
|
||||
HostConfig: { RestartPolicy: { Name: "unless-stopped", MaximumRetryCount: 0 } },
|
||||
Config: {
|
||||
Entrypoint: ["/bin/bash", "-ec", `set -euo pipefail\n${script}\nexec /entrypoint.sh "$@"\n`, "--"],
|
||||
Cmd: ["./bin/Runner.Listener", "run", "--startuptype", "service"],
|
||||
WorkingDir: "/actions-runner",
|
||||
Env: [],
|
||||
Labels: {},
|
||||
},
|
||||
Mounts: [],
|
||||
NetworkSettings: { Ports: {}, Networks: {} },
|
||||
},
|
||||
]);
|
||||
const containerId = "13de5573bf36a9c8d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2c3";
|
||||
const snapshot = {
|
||||
availability: { kind: "ready", clientVersion: "27.3.1", serverVersion: "27.3.1", context: null },
|
||||
executable: "/usr/local/bin/docker",
|
||||
containers: [
|
||||
{
|
||||
id: containerId,
|
||||
name: "runner-1",
|
||||
image: "myoung34/github-runner:latest",
|
||||
command: '"/bin/bash -ec \'set…"',
|
||||
state: "running",
|
||||
status: "Up 2 hours",
|
||||
ports: "",
|
||||
createdAt: "2026-11-22 01:41:28 +0000 UTC",
|
||||
composeProject: "selfhost",
|
||||
composeService: "github-runner",
|
||||
composeWorkingDir: "/Users/dev/selfhost",
|
||||
composeFiles: ["/Users/dev/selfhost/docker-compose.yml"],
|
||||
},
|
||||
],
|
||||
images: [],
|
||||
volumes: [],
|
||||
networks: [],
|
||||
errors: [],
|
||||
};
|
||||
window.__ipc.handlers.docker_settings = () => ({
|
||||
connections: [{ id: "local", name: "Docker", endpoint: { kind: "default" } }],
|
||||
registries: [],
|
||||
});
|
||||
window.__ipc.handlers.docker_snapshot = () => snapshot;
|
||||
window.__ipc.handlers.docker_inspect = () => inspectJson;
|
||||
window.__ipc.handlers.docker_container_stats = () => ({
|
||||
cpuPerc: "1.20%",
|
||||
memUsage: "256MiB / 8GiB",
|
||||
memPerc: "3.12%",
|
||||
netIo: "1MB / 1MB",
|
||||
blockIo: "0B / 0B",
|
||||
pids: "12",
|
||||
});
|
||||
window.__ipc.handlers.docker_events = () => new Promise(() => {});
|
||||
window.__ipc.handlers.cancel_request = () => null;
|
||||
|
||||
const storeModule = "/src/features/services/store.ts";
|
||||
const treeModule = "/src/features/services/tree.ts";
|
||||
const { useServices } = await import(/* @vite-ignore */ storeModule);
|
||||
const { useServicesTree } = await import(/* @vite-ignore */ treeModule);
|
||||
useServices.setState({
|
||||
settings: { connections: [{ id: "local", name: "Docker", endpoint: { kind: "default" } }], registries: [] },
|
||||
conns: { local: { snapshot, loading: false, error: null } },
|
||||
detailTab: "dashboard",
|
||||
});
|
||||
useServicesTree.setState({
|
||||
expanded: new Set(["docker:local", "docker:local:compose:selfhost"]),
|
||||
selectedKey: `docker:local:container:${containerId}`,
|
||||
selectedKeys: new Set([`docker:local:container:${containerId}`]),
|
||||
});
|
||||
});
|
||||
|
||||
await page.keyboard.press("Meta+8");
|
||||
const services = page.getByRole("region", { name: "Services", exact: true });
|
||||
await expect(services.getByText("Container Overview")).toBeVisible();
|
||||
|
||||
const toggle = services.getByRole("button", { name: /^\d+ lines$/ });
|
||||
await expect(toggle).toHaveAttribute("aria-expanded", "false");
|
||||
|
||||
const preview = services.locator("code[data-no-tooltip]");
|
||||
await expect(preview).toContainText("↵");
|
||||
|
||||
// Hovering the truncated command preview must not spawn a giant auto-ellipsis tooltip.
|
||||
await preview.hover();
|
||||
await page.waitForTimeout(700);
|
||||
await expect(page.getByRole("tooltip")).toHaveCount(0);
|
||||
|
||||
// Collapsed row stays strictly between Started and Working directory (no upward overlap).
|
||||
const startedLabel = services.getByText("Started", { exact: true });
|
||||
const commandLabel = services.getByText("Command", { exact: true });
|
||||
const workingDirLabel = services.getByText("Working directory", { exact: true });
|
||||
const collapsedStartedBox = (await startedLabel.boundingBox())!;
|
||||
const collapsedPreviewBox = (await preview.boundingBox())!;
|
||||
const collapsedWorkingBox = (await workingDirLabel.boundingBox())!;
|
||||
expect(collapsedPreviewBox.y).toBeGreaterThan(collapsedStartedBox.y + collapsedStartedBox.height);
|
||||
expect(collapsedWorkingBox.y).toBeGreaterThan(collapsedPreviewBox.y + collapsedPreviewBox.height);
|
||||
|
||||
// Expanding reveals Entrypoint + Command arguments inside a bounded scroll box growing downward.
|
||||
await toggle.click();
|
||||
const collapseBtn = services.getByRole("button", { name: "Collapse", exact: true });
|
||||
await expect(collapseBtn).toHaveAttribute("aria-expanded", "true");
|
||||
await expect(services.getByText("Entrypoint", { exact: true })).toBeVisible();
|
||||
await expect(services.getByText("Command arguments", { exact: true })).toBeVisible();
|
||||
|
||||
const expandedStartedBox = (await startedLabel.boundingBox())!;
|
||||
const expandedCommandLabelBox = (await commandLabel.boundingBox())!;
|
||||
const entrypointPre = services.locator("pre").first();
|
||||
const scrollContainer = entrypointPre.locator("xpath=ancestor::div[1]/parent::div");
|
||||
const scrollBox = (await scrollContainer.boundingBox())!;
|
||||
const expandedWorkingBox = (await workingDirLabel.boundingBox())!;
|
||||
|
||||
expect(expandedCommandLabelBox.y).toBeGreaterThan(expandedStartedBox.y + expandedStartedBox.height);
|
||||
expect(scrollBox.y).toBeGreaterThan(expandedCommandLabelBox.y);
|
||||
expect(scrollBox.height).toBeLessThanOrEqual(182);
|
||||
expect(expandedWorkingBox.y).toBeGreaterThanOrEqual(scrollBox.y + scrollBox.height - 1);
|
||||
|
||||
await collapseBtn.click();
|
||||
await expect(services.getByRole("button", { name: /^\d+ lines$/ })).toHaveAttribute("aria-expanded", "false");
|
||||
});
|
||||
|
||||
test("Docker Compose container Jump to Source opens the Compose file at the command or the service", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async () => {
|
||||
const composePath = "/dev/acme-api/docker-compose.yml";
|
||||
const composeYaml = [
|
||||
"services:",
|
||||
" postgres:",
|
||||
" image: postgres:16",
|
||||
" github-runner:",
|
||||
" image: myoung34/github-runner:latest",
|
||||
" entrypoint:",
|
||||
" - /bin/bash",
|
||||
" - -ec",
|
||||
" - |",
|
||||
" mkdir -p /persist/slots",
|
||||
' exec /entrypoint.sh "$@"',
|
||||
' command: ["./bin/Runner.Listener", "run", "--startuptype", "service"]',
|
||||
"",
|
||||
].join("\n");
|
||||
|
||||
const backendModule = "/src/editor/core/backend.ts";
|
||||
const { docBackend } = await import(/* @vite-ignore */ backendModule);
|
||||
docBackend().files.set(composePath, composeYaml);
|
||||
window.__ipc.handlers.fs_read_text = ({ path }) => {
|
||||
if (path === composePath) return composeYaml;
|
||||
throw { kind: "notFound", message: `not found: ${String(path)}`, detail: null };
|
||||
};
|
||||
|
||||
const runnerId = "13de5573bf36a9c8d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2c3";
|
||||
const dbId = "98ab76cd54ef3210fedcba9876543210abcdef0123456789abcdef0123456789";
|
||||
const snapshot = {
|
||||
availability: { kind: "ready", clientVersion: "27.3.1", serverVersion: "27.3.1", context: null },
|
||||
executable: "/usr/local/bin/docker",
|
||||
containers: [
|
||||
{
|
||||
id: runnerId,
|
||||
name: "selfhost-github-runner-1",
|
||||
image: "myoung34/github-runner:latest",
|
||||
command: '"/bin/bash -ec \'mkdir…"',
|
||||
state: "running",
|
||||
status: "Up 2 hours",
|
||||
ports: "",
|
||||
createdAt: "2026-11-22 01:41:28 +0000 UTC",
|
||||
composeProject: "selfhost",
|
||||
composeService: "github-runner",
|
||||
composeWorkingDir: "/dev/acme-api",
|
||||
composeFiles: [composePath],
|
||||
},
|
||||
{
|
||||
id: dbId,
|
||||
name: "selfhost-postgres-1",
|
||||
image: "postgres:16",
|
||||
command: "postgres",
|
||||
state: "running",
|
||||
status: "Up 2 hours",
|
||||
ports: "",
|
||||
createdAt: "2026-11-22 01:41:28 +0000 UTC",
|
||||
composeProject: "selfhost",
|
||||
composeService: "postgres",
|
||||
composeWorkingDir: "/dev/acme-api",
|
||||
composeFiles: [composePath],
|
||||
},
|
||||
],
|
||||
images: [],
|
||||
volumes: [],
|
||||
networks: [],
|
||||
errors: [],
|
||||
};
|
||||
|
||||
window.__ipc.handlers.docker_settings = () => ({
|
||||
connections: [{ id: "local", name: "Docker", endpoint: { kind: "default" } }],
|
||||
registries: [],
|
||||
});
|
||||
window.__ipc.handlers.docker_snapshot = () => snapshot;
|
||||
window.__ipc.handlers.docker_inspect = () =>
|
||||
JSON.stringify([
|
||||
{
|
||||
Created: "2026-11-22T01:41:28Z",
|
||||
State: { Status: "running", Pid: 2048, StartedAt: "2026-11-22T01:41:29Z" },
|
||||
HostConfig: { RestartPolicy: { Name: "unless-stopped", MaximumRetryCount: 0 } },
|
||||
Config: {
|
||||
Entrypoint: ["/bin/bash", "-ec", 'mkdir -p /persist/slots\nexec /entrypoint.sh "$@"'],
|
||||
Cmd: ["./bin/Runner.Listener", "run", "--startuptype", "service"],
|
||||
WorkingDir: "/actions-runner",
|
||||
Env: [],
|
||||
Labels: {},
|
||||
},
|
||||
Mounts: [],
|
||||
NetworkSettings: { Ports: {}, Networks: {} },
|
||||
},
|
||||
]);
|
||||
window.__ipc.handlers.docker_container_stats = () => ({
|
||||
cpuPerc: "0.50%",
|
||||
memUsage: "128MiB / 8GiB",
|
||||
memPerc: "1.56%",
|
||||
netIo: "0B / 0B",
|
||||
blockIo: "0B / 0B",
|
||||
pids: "4",
|
||||
});
|
||||
window.__ipc.handlers.docker_events = () => new Promise(() => {});
|
||||
window.__ipc.handlers.cancel_request = () => null;
|
||||
|
||||
const storeModule = "/src/features/services/store.ts";
|
||||
const treeModule = "/src/features/services/tree.ts";
|
||||
const { useServices } = await import(/* @vite-ignore */ storeModule);
|
||||
const { useServicesTree } = await import(/* @vite-ignore */ treeModule);
|
||||
useServices.setState({
|
||||
settings: { connections: [{ id: "local", name: "Docker", endpoint: { kind: "default" } }], registries: [] },
|
||||
conns: { local: { snapshot, loading: false, error: null } },
|
||||
detailTab: "dashboard",
|
||||
});
|
||||
useServicesTree.setState({
|
||||
expanded: new Set(["docker:local", "docker:local:compose:selfhost"]),
|
||||
selectedKey: `docker:local:container:${runnerId}`,
|
||||
selectedKeys: new Set([`docker:local:container:${runnerId}`]),
|
||||
});
|
||||
});
|
||||
|
||||
await page.keyboard.press("Meta+8");
|
||||
const services = page.getByRole("region", { name: "Services", exact: true });
|
||||
await expect(services.getByText("Container Overview")).toBeVisible();
|
||||
|
||||
// Clicking Jump to Source on the Command row opens docker-compose.yml with caret on `command:` value
|
||||
await services.getByRole("button", { name: "Jump to Source", exact: true }).click();
|
||||
const editor = page.locator(".cm-editor");
|
||||
await expect(editor.locator(".cm-activeLine")).toHaveText(
|
||||
' command: ["./bin/Runner.Listener", "run", "--startuptype", "service"]',
|
||||
);
|
||||
const caret = await page.evaluate(async () => {
|
||||
const api = await import(/* @vite-ignore */ "/src/editor/api.ts" as string);
|
||||
const view = api.activeEditor()?.view;
|
||||
if (!view) return null;
|
||||
const head = view.state.selection.main.head;
|
||||
const line = view.state.doc.lineAt(head);
|
||||
return { line: line.number - 1, col: head - line.from };
|
||||
});
|
||||
expect(caret).toEqual({ line: 11, col: 13 });
|
||||
|
||||
// F4 on a Compose container node jumps to its service declaration
|
||||
const tree = services.getByRole("tree", { name: "Services", exact: true });
|
||||
await tree.getByRole("treeitem", { name: /github-runner/ }).click();
|
||||
await page.keyboard.press("F4");
|
||||
await expect(editor.locator(".cm-activeLine")).toHaveText(" github-runner:");
|
||||
await tree.getByRole("treeitem", { name: /postgres/ }).click();
|
||||
await page.keyboard.press("F4");
|
||||
await expect(editor.locator(".cm-activeLine")).toHaveText(" postgres:");
|
||||
});
|
||||
|
||||
test("Docker Compose dashboard shows per-service resource usage and named project volumes", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async () => {
|
||||
(window as unknown as { __cpuPerc: string }).__cpuPerc = "6.25%";
|
||||
const anonName = "37cc33a7d603260a82a378d7d3eeb835b748b5712614e2e5b4a3d6572f5e1e71";
|
||||
const snapshot = {
|
||||
availability: { kind: "ready", clientVersion: "28.0.1", serverVersion: "28.0.1", context: null },
|
||||
executable: "/usr/bin/docker",
|
||||
containers: [
|
||||
{
|
||||
id: "db-1",
|
||||
name: "shop-db-1",
|
||||
image: "postgres:16",
|
||||
command: "postgres",
|
||||
state: "running",
|
||||
status: "Up 15 minutes",
|
||||
ports: "127.0.0.1:5432->5432/tcp",
|
||||
createdAt: "2026-04-20T05:00:00Z",
|
||||
composeProject: "shop",
|
||||
composeService: "db",
|
||||
composeWorkingDir: "/work/shop",
|
||||
composeFiles: ["/work/shop/docker-compose.yml"],
|
||||
mounts: ["shop_pgdata"],
|
||||
networks: ["shop_default"],
|
||||
},
|
||||
{
|
||||
id: "api-1",
|
||||
name: "shop-api-1",
|
||||
image: "node:22",
|
||||
command: "node server.js",
|
||||
state: "exited",
|
||||
status: "Exited (0) 2 minutes ago",
|
||||
ports: "",
|
||||
createdAt: "2026-04-20T05:00:00Z",
|
||||
composeProject: "shop",
|
||||
composeService: "api",
|
||||
composeWorkingDir: "/work/shop",
|
||||
composeFiles: ["/work/shop/docker-compose.yml"],
|
||||
mounts: [],
|
||||
networks: ["shop_default"],
|
||||
},
|
||||
],
|
||||
images: [],
|
||||
volumes: [
|
||||
{
|
||||
name: anonName,
|
||||
driver: "local",
|
||||
mountpoint: `/var/lib/docker/volumes/${anonName}/_data`,
|
||||
composeProject: "shop",
|
||||
scope: "local",
|
||||
labels: { "com.docker.volume.anonymous": "" },
|
||||
},
|
||||
{
|
||||
name: "shop_pgdata",
|
||||
driver: "local",
|
||||
mountpoint: "/var/lib/docker/volumes/shop_pgdata/_data",
|
||||
composeProject: "shop",
|
||||
scope: "local",
|
||||
labels: {
|
||||
"com.docker.compose.project": "shop",
|
||||
"com.docker.compose.volume": "pgdata",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "other_cache",
|
||||
driver: "local",
|
||||
mountpoint: "/var/lib/docker/volumes/other_cache/_data",
|
||||
composeProject: "other",
|
||||
scope: "local",
|
||||
labels: {
|
||||
"com.docker.compose.project": "other",
|
||||
"com.docker.compose.volume": "cache",
|
||||
},
|
||||
},
|
||||
],
|
||||
networks: [{ id: "net-1", name: "shop_default", driver: "bridge", scope: "local", composeProject: "shop" }],
|
||||
errors: [],
|
||||
};
|
||||
|
||||
window.__ipc.handlers.docker_settings = () => ({
|
||||
connections: [{ id: "default", name: "Docker", endpoint: { kind: "default" } }],
|
||||
registries: [],
|
||||
});
|
||||
window.__ipc.handlers.docker_snapshot = () => snapshot;
|
||||
window.__ipc.handlers.docker_events = () => new Promise(() => {});
|
||||
window.__ipc.handlers.docker_inspect = () => "[]";
|
||||
window.__ipc.handlers.docker_container_stats = ({ id }) => {
|
||||
if (id !== "db-1") throw { kind: "notFound", message: "container not running", detail: null };
|
||||
return {
|
||||
cpuPerc: (window as unknown as { __cpuPerc: string }).__cpuPerc,
|
||||
memUsage: "128MiB / 2GiB",
|
||||
memPerc: "6.25%",
|
||||
netIo: "2.4MB / 980kB",
|
||||
blockIo: "12MB / 4.1MB",
|
||||
pids: "17",
|
||||
};
|
||||
};
|
||||
|
||||
const storeMod = "/src/features/services/store.ts";
|
||||
const treeMod = "/src/features/services/tree.ts";
|
||||
const { useServices } = await import(/* @vite-ignore */ storeMod);
|
||||
const { useServicesTree } = await import(/* @vite-ignore */ treeMod);
|
||||
useServices.setState({
|
||||
settings: { connections: [{ id: "default", name: "Docker", endpoint: { kind: "default" } }], registries: [] },
|
||||
conns: { default: { snapshot, loading: false, error: null } },
|
||||
});
|
||||
useServicesTree.setState({
|
||||
expanded: new Set(["docker:default"]),
|
||||
selectedKey: "docker:default:compose:shop",
|
||||
selectedKeys: new Set(["docker:default:compose:shop"]),
|
||||
});
|
||||
});
|
||||
|
||||
await page.keyboard.press("Meta+8");
|
||||
const services = page.getByRole("region", { name: "Services", exact: true });
|
||||
const detail = services.locator("[data-panel][id=services-detail]");
|
||||
await expect(detail.getByText("Compose project 'shop'")).toBeVisible();
|
||||
|
||||
const dbRow = detail.locator("tr", { hasText: "shop-db-1" });
|
||||
const apiRow = detail.locator("tr", { hasText: "shop-api-1" });
|
||||
await expect(dbRow).toContainText("6.25%");
|
||||
await expect(dbRow).toContainText("128MiB / 2GiB (6.25%)");
|
||||
await expect(dbRow).toContainText("2.4MB / 980kB");
|
||||
await expect(dbRow).toContainText("12MB / 4.1MB");
|
||||
await expect(dbRow).toContainText("17");
|
||||
await expect(apiRow).toContainText("Exited (0) 2 minutes ago");
|
||||
|
||||
// Stopped service container is never queried for live stats, and no manual Refresh button is shown.
|
||||
const queriedIds = (await ipcCalls(page, "docker_container_stats")).map((c) => c.id);
|
||||
expect(new Set(queriedIds)).toEqual(new Set(["db-1"]));
|
||||
await expect(detail.getByRole("button", { name: "Refresh", exact: true })).toHaveCount(0);
|
||||
|
||||
// Running service metrics auto-refresh in place without user action.
|
||||
await page.evaluate(() => {
|
||||
(window as unknown as { __cpuPerc: string }).__cpuPerc = "18.50%";
|
||||
});
|
||||
await expect(dbRow).toContainText("18.50%", { timeout: 5000 });
|
||||
|
||||
// Named Compose volume appears with logical name + driver; anonymous and other-project volumes do not.
|
||||
const volumeButton = detail.getByRole("button", { name: /shop_pgdata/ });
|
||||
await expect(volumeButton).toContainText("pgdata · local");
|
||||
await expect(detail.getByText("other_cache")).toHaveCount(0);
|
||||
await expect(detail.getByText(/37cc33a7/)).toHaveCount(0);
|
||||
|
||||
// Clicking the named volume opens its Volume dashboard and links back to the Compose project.
|
||||
await volumeButton.click();
|
||||
await expect(detail.getByText("Volume Overview")).toBeVisible();
|
||||
await detail.getByRole("button", { name: "shop", exact: true }).click();
|
||||
await expect(detail.getByText("Compose project 'shop'")).toBeVisible();
|
||||
|
||||
// Clicking a service in the table navigates to its Container dashboard, which auto-refreshes live stats.
|
||||
await detail.getByRole("button", { name: "shop-db-1", exact: true }).click();
|
||||
await expect(detail.getByText("Container Overview")).toBeVisible();
|
||||
await expect(detail).toContainText("18.50%");
|
||||
await page.evaluate(() => {
|
||||
(window as unknown as { __cpuPerc: string }).__cpuPerc = "27.40%";
|
||||
});
|
||||
await expect(detail).toContainText("27.40%", { timeout: 5000 });
|
||||
});
|
||||
@@ -385,6 +385,8 @@ test("edits and stages from the index in unified diffs of read-only files", asyn
|
||||
const index = modal.locator('.cm-content[aria-label="Staged (index)"]');
|
||||
await expect(index).toBeEditable();
|
||||
await expect(index).toHaveText(/val alpha = "index"\s+val alpha = "local"/, { useInnerText: true });
|
||||
await expect(modal.locator(".cm-diffNumbers-modified .cm-diffWidgetNumber")).toHaveText(["1", "3"]);
|
||||
await expect(modal.locator(".cm-diffNumbers-original .cm-diffWidgetNumber")).toHaveCount(0);
|
||||
const setReadOnly = (readOnly: boolean) =>
|
||||
page.evaluate((readOnly) => window.__ipc.handlers.test_set_readonly?.({ readOnly }), readOnly);
|
||||
await setReadOnly(false);
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
|
||||
|
||||
test("groups stashes by repository and keeps the selected stash actions scoped", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 1100, height: 720 });
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async () => {
|
||||
const main = "/dev/acme-api";
|
||||
const service = `${main}/warehouse-api`;
|
||||
const stash = (index: number, id: string, title: string) => ({
|
||||
index,
|
||||
id,
|
||||
message: `On main: ${title}`,
|
||||
base: "base",
|
||||
timeMs: new Date(2025, 4, 14, 10, 30).getTime(),
|
||||
});
|
||||
const handlers = window.__ipc.handlers;
|
||||
handlers.vcs_stashes = ({ repo }) =>
|
||||
repo === service
|
||||
? [stash(0, "warehouse-stash", "Review warehouse routing")]
|
||||
: [stash(0, "ledger-stash", "Check totals"), stash(1, "invoice-stash", "Match invoice balances")];
|
||||
handlers.vcs_commit_files = ({ repo }) => [
|
||||
{ path: repo === service ? "routing.txt" : "totals.txt", kind: "modified", oldPath: null },
|
||||
];
|
||||
const store = "/src/features/vcs/store.ts";
|
||||
const context = "/src/platform/context.ts";
|
||||
const actions = "/src/platform/actions.ts";
|
||||
const toolWindows = "/src/workbench/toolwindows/store.ts";
|
||||
const { useVcs } = await import(/* @vite-ignore */ store);
|
||||
const { setContext } = await import(/* @vite-ignore */ context);
|
||||
const { executeAction } = await import(/* @vite-ignore */ actions);
|
||||
const { moveToolWindow, setToolWindowSize } = await import(/* @vite-ignore */ toolWindows);
|
||||
useVcs.setState({ available: true, root: main, repo: main, roots: [main, service] });
|
||||
setContext("vcsAvailable", true);
|
||||
moveToolWindow("commit", "bottom");
|
||||
await executeAction("vcs.showStashes");
|
||||
setToolWindowSize("bottom", 310);
|
||||
});
|
||||
|
||||
const tree = page.getByRole("tree", { name: "Stashes", exact: true });
|
||||
const main = tree.getByRole("treeitem").filter({ has: page.getByText("acme-api", { exact: true }) });
|
||||
const service = tree.getByRole("treeitem", { name: /warehouse-api/ });
|
||||
const apply = page
|
||||
.getByRole("toolbar", { name: "Stashes", exact: true })
|
||||
.getByRole("button", { name: "Apply Stash" });
|
||||
const first = tree.getByRole("treeitem", { name: /Check totals/ });
|
||||
await expect(service, "repository group starts expanded").toHaveAttribute("aria-expanded", "true");
|
||||
await expect(main).toHaveAccessibleName(/acme-api\s*2/);
|
||||
await expect(first).toHaveAttribute("aria-level", "2");
|
||||
await expect(first).toHaveAttribute("aria-selected", "true");
|
||||
|
||||
for (const width of [1100, 440]) {
|
||||
await page.setViewportSize({ width, height: 720 });
|
||||
const subject = first.getByText("Check totals", { exact: true });
|
||||
const date = subject.locator("xpath=following-sibling::*[1]");
|
||||
await expect(date).toHaveText(/2025/);
|
||||
await expect.poll(() => subject.evaluate((el) => el.scrollWidth <= el.clientWidth)).toBe(true);
|
||||
await expect(date).toHaveCSS("font-size", await subject.evaluate((el) => getComputedStyle(el).fontSize));
|
||||
const titleBox = (await subject.boundingBox())!;
|
||||
const dateBox = (await date.boundingBox())!;
|
||||
expect(dateBox.x - titleBox.x - titleBox.width).toBeCloseTo(6, 0);
|
||||
}
|
||||
|
||||
await tree.focus();
|
||||
await tree.press("Home");
|
||||
await tree.press("ArrowLeft");
|
||||
await expect(main).toHaveAttribute("aria-expanded", "false");
|
||||
await expect(first).toHaveCount(0);
|
||||
await expect(apply).toBeDisabled();
|
||||
await expect(page.getByText("Select a stash to view its changes.")).toBeVisible();
|
||||
await tree.press("ArrowRight");
|
||||
await expect(first).toBeVisible();
|
||||
await tree.getByText("Review warehouse routing", { exact: true }).click();
|
||||
await expect(apply).toBeEnabled();
|
||||
await expect(page.getByRole("tree", { name: "Changed files" }).getByText("routing.txt")).toBeVisible();
|
||||
expect((await ipcCalls(page, "vcs_commit_files")).at(-1)).toEqual({
|
||||
repo: "/dev/acme-api/warehouse-api",
|
||||
commit: "warehouse-stash",
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,123 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
|
||||
|
||||
async function seedReview(page: Page) {
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async () => {
|
||||
const project = "/src/platform/project.ts";
|
||||
const context = "/src/platform/context.ts";
|
||||
const repositoryStore = "/src/features/github/data/repository.ts";
|
||||
const pullRequests = "/src/features/github/data/pullRequest.ts";
|
||||
const { useProject } = await import(/* @vite-ignore */ project);
|
||||
const { setContext } = await import(/* @vite-ignore */ context);
|
||||
const { useGhRepository } = await import(/* @vite-ignore */ repositoryStore);
|
||||
const { setPullRequestData } = await import(/* @vite-ignore */ pullRequests);
|
||||
useProject.setState((s: { settings: { editor: unknown } }) => ({
|
||||
settings: {
|
||||
...s.settings,
|
||||
editor: { ...(s.settings?.editor as object), fontFamily: "Courier New", fontSize: 17, lineHeight: 25 },
|
||||
},
|
||||
}));
|
||||
const coordinates = { owner: "sample", name: "settlement" };
|
||||
useGhRepository.setState({
|
||||
connection: {
|
||||
coordinates,
|
||||
repository: { id: "repository", nameWithOwner: "sample/settlement" },
|
||||
currentUser: { id: "reviewer", login: "reviewer" },
|
||||
root: null,
|
||||
remotes: [],
|
||||
},
|
||||
});
|
||||
setContext("githubConnected", true);
|
||||
setContext("githubCurrentBranchPullRequest", true);
|
||||
setPullRequestData(7, "details", () => ({ number: 7, viewerDidAuthor: false }));
|
||||
setPullRequestData(7, "pendingReview", () => ({ id: "draft-seven", state: "PENDING", commentsCount: 12 }));
|
||||
});
|
||||
}
|
||||
|
||||
async function openReview(page: Page) {
|
||||
await page.evaluate(async () => {
|
||||
const actions = "/src/platform/actions.ts";
|
||||
const { executeAction } = await import(/* @vite-ignore */ actions);
|
||||
await executeAction("github.pullRequest.submitReview", 7);
|
||||
});
|
||||
}
|
||||
|
||||
test("centers the unanchored composer, follows the editor font and reflows its review actions", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 1120, height: 840 });
|
||||
await seedReview(page);
|
||||
await openReview(page);
|
||||
const popup = page.getByRole("dialog", { name: "Submit Review" });
|
||||
const editor = popup.getByRole("textbox", { name: "Review comment" });
|
||||
const verticalCenter = () =>
|
||||
popup.evaluate((el) => {
|
||||
const { top, height } = el.getBoundingClientRect();
|
||||
return Math.abs(top + height / 2 - innerHeight / 2);
|
||||
});
|
||||
await expect.poll(verticalCenter, { message: "verticalCenter at standard size" }).toBeLessThan(1);
|
||||
await expect(editor).toBeFocused();
|
||||
await expect(editor).toHaveCSS("font-size", "17px");
|
||||
await expect(editor).toHaveCSS("line-height", "25px");
|
||||
await expect(editor).toHaveCSS("font-family", /Courier New/);
|
||||
await editor.fill("Please double-check the rounding step.");
|
||||
|
||||
const grip = (await popup.getByRole("separator", { name: "Resize" }).boundingBox())!;
|
||||
await page.mouse.move(grip.x + grip.width / 2, grip.y + grip.height / 2);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(grip.x + grip.width / 2 + 56, grip.y + grip.height / 2 + 32);
|
||||
await page.mouse.up();
|
||||
await expect.poll(async () => (await popup.boundingBox())!.width).toBeGreaterThan(540);
|
||||
await page.setViewportSize({ width: 300, height: 400 });
|
||||
await expect.poll(verticalCenter, { message: "verticalCenter after shrinking" }).toBeLessThan(1);
|
||||
const approve = (await popup.getByRole("button", { name: "Approve", exact: true }).boundingBox())!;
|
||||
const comment = (await popup.getByRole("button", { name: "Comment", exact: true }).boundingBox())!;
|
||||
expect(comment.y).toBeGreaterThan(approve.y);
|
||||
expect(comment.x + comment.width).toBeLessThan(300);
|
||||
await expect(editor).toHaveValue("Please double-check the rounding step.");
|
||||
await editor.press("Escape");
|
||||
await expect(popup).toHaveCount(0);
|
||||
await openReview(page);
|
||||
await expect(editor).toHaveValue("Please double-check the rounding step.");
|
||||
});
|
||||
|
||||
test("keeps anchored review controls and the comment visible after a long submission error", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 355, height: 390 });
|
||||
await seedReview(page);
|
||||
await page.evaluate(async () => {
|
||||
const path = "/src/features/github/details/SubmitReviewPopup.tsx";
|
||||
const { showSubmitReview } = await import(/* @vite-ignore */ path);
|
||||
const anchor = document.createElement("button");
|
||||
anchor.style.cssText = "position:fixed;top:350px;left:275px;";
|
||||
anchor.textContent = "Review anchor";
|
||||
document.body.append(anchor);
|
||||
window.__ipc.handlers.gh_api = ({ request }) => {
|
||||
const { query } = JSON.parse((request as { body: string }).body);
|
||||
if (!query.includes("submitPullRequestReview")) throw Error("Unexpected GitHub request");
|
||||
return JSON.stringify({ errors: [{ message: "Review request failed. " + "outdated-reference-".repeat(35) }] });
|
||||
};
|
||||
void showSubmitReview(7, anchor);
|
||||
});
|
||||
const popup = page.getByRole("dialog", { name: "Submit Review" });
|
||||
const editor = popup.getByRole("textbox", { name: "Review comment" });
|
||||
const button = popup.getByRole("button", { name: "Comment", exact: true });
|
||||
await editor.fill("Check the batch limit.");
|
||||
await button.click();
|
||||
const error = popup.getByRole("alert");
|
||||
await expect(error).toContainText("Review request failed.");
|
||||
await expect(button).toBeEnabled();
|
||||
await expect(editor).toHaveValue("Check the batch limit.");
|
||||
const box = (await popup.boundingBox())!;
|
||||
const buttonBox = (await button.boundingBox())!;
|
||||
expect(box.y + box.height).toBeLessThan(350);
|
||||
expect(buttonBox.y + buttonBox.height).toBeLessThanOrEqual(box.y + box.height);
|
||||
expect(box.x + box.width).toBeLessThanOrEqual(355);
|
||||
await expect.poll(() => error.evaluate((el) => el.scrollHeight > el.clientHeight)).toBe(true);
|
||||
const calls = await ipcCalls(page, "gh_api");
|
||||
expect(calls).toHaveLength(1);
|
||||
const { variables } = JSON.parse((calls[0]!.request as { body: string }).body);
|
||||
expect(variables).toEqual({ reviewId: "draft-seven", event: "COMMENT", body: "Check the batch limit." });
|
||||
});
|
||||
@@ -0,0 +1,88 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import { expect, test } from "./fixtures";
|
||||
|
||||
async function openDiff(page: Page, left: string, right: string, options: Record<string, unknown> = {}) {
|
||||
await page.evaluate(
|
||||
async ({ left, right, options }) => {
|
||||
localStorage.setItem(
|
||||
"openidea.vcs.diffOptions",
|
||||
JSON.stringify({ mode: "unified", collapse: false, ...options }),
|
||||
);
|
||||
const actions = "/src/platform/actions.ts";
|
||||
const { executeAction } = await import(/* @vite-ignore */ actions);
|
||||
await executeAction("diff.compareTexts", {
|
||||
path: "SettlementRules.txt",
|
||||
left: { text: left, label: "Original" },
|
||||
right: { text: right, label: "Modified" },
|
||||
});
|
||||
},
|
||||
{ left, right, options },
|
||||
);
|
||||
return page.getByRole("toolbar", { name: "Diff" });
|
||||
}
|
||||
|
||||
async function rowNumbers(page: Page, text: string, deleted = false) {
|
||||
return page
|
||||
.locator(deleted ? ".cm-deletedLine" : ".cm-line")
|
||||
.filter({ hasText: text })
|
||||
.evaluate((row) => {
|
||||
const top = row.getBoundingClientRect().top;
|
||||
const editor = row.closest(".cm-editor")!;
|
||||
const read = (side: string) =>
|
||||
[...editor.querySelectorAll(`.cm-diffNumbers-${side} :is(.cm-gutterElement, .cm-diffWidgetNumber)`)].find(
|
||||
(number) =>
|
||||
getComputedStyle(number).visibility === "visible" && Math.abs(number.getBoundingClientRect().top - top) < 1,
|
||||
)?.textContent ?? null;
|
||||
return [read("original"), read("modified")];
|
||||
});
|
||||
}
|
||||
|
||||
test("Unified Diff keeps original and modified numbers aligned with wrapped and removed lines", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 1000, height: 640 });
|
||||
const oldRule = "Obsolete settlement rule " + "requires review for each exceptional invoice. ".repeat(3);
|
||||
const toolbar = await openDiff(
|
||||
page,
|
||||
["Settlement rules", oldRule, "Retire legacy routing", "Report totals", "Finish batch"].join("\n"),
|
||||
["Settlement rules", "Validate settlement currency", "Report totals", "Finish batch"].join("\n"),
|
||||
{ softWrap: true },
|
||||
);
|
||||
await expect(toolbar).toContainText("1 difference");
|
||||
|
||||
for (const width of [1000, 440]) {
|
||||
await page.setViewportSize({ width, height: 640 });
|
||||
await expect.poll(() => rowNumbers(page, "Obsolete settlement rule", true)).toEqual(["2", null]);
|
||||
await expect.poll(() => rowNumbers(page, "Retire legacy routing", true)).toEqual(["3", null]);
|
||||
await expect.poll(() => rowNumbers(page, "Validate settlement currency")).toEqual([null, "2"]);
|
||||
await expect.poll(() => rowNumbers(page, "Report totals")).toEqual(["4", "3"]);
|
||||
}
|
||||
|
||||
const removed = page.locator(".cm-deletedLine").filter({ hasText: "Obsolete settlement rule" });
|
||||
const lineHeight = await removed.evaluate((el) => parseFloat(getComputedStyle(el).lineHeight));
|
||||
expect((await removed.boundingBox())!.height).toBeGreaterThan(lineHeight * 2);
|
||||
await toolbar.getByRole("button", { name: "Next Difference", exact: true }).click();
|
||||
await expect(toolbar).toContainText("1 of 1 differences");
|
||||
});
|
||||
|
||||
test("Unified Diff numbers account for ignored empty lines and a removal at EOF without a newline", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await openDiff(
|
||||
page,
|
||||
"Settlement rules\n\nReport totals\nFinish batch\nRemove final rule",
|
||||
"Settlement rules\nReport totals\nFinish batch",
|
||||
{ ignore: "whitespaceAndLines" },
|
||||
);
|
||||
await expect.poll(() => rowNumbers(page, "Report totals")).toEqual(["3", "2"]);
|
||||
await expect.poll(() => rowNumbers(page, "Finish batch")).toEqual(["4", "3"]);
|
||||
await expect.poll(() => rowNumbers(page, "Remove final rule", true)).toEqual(["5", null]);
|
||||
});
|
||||
|
||||
test("Unified Diff follows vertical scrolling inside one large removal", async ({ workbench: page }) => {
|
||||
const removed = Array.from({ length: 250 }, (_, i) => `Retired workflow ${i + 1}.`);
|
||||
await openDiff(page, ["Start batch", ...removed, "Finish batch"].join("\n"), "Start batch\nFinish batch");
|
||||
const target = page.locator(".cm-deletedLine").filter({ hasText: "Retired workflow 229." });
|
||||
await target.scrollIntoViewIfNeeded();
|
||||
await expect.poll(() => rowNumbers(page, "Retired workflow 229.", true)).toEqual(["230", null]);
|
||||
});
|
||||
+1
-1
@@ -67,7 +67,7 @@
|
||||
"@floating-ui/react-dom": "^2.1.9",
|
||||
"@fontsource-variable/inter": "^5.3.0",
|
||||
"@fontsource-variable/jetbrains-mono": "^5.3.0",
|
||||
"@lezer/common": "^1.5.3",
|
||||
"@lezer/common": "^1.5.6",
|
||||
"@lezer/highlight": "^1.2.5",
|
||||
"@lezer/lr": "^1.4.11",
|
||||
"@mathjax/mathjax-tex-font": "4.1.3",
|
||||
|
||||
Generated
+44
-44
@@ -76,8 +76,8 @@ importers:
|
||||
specifier: ^5.3.0
|
||||
version: 5.3.0
|
||||
'@lezer/common':
|
||||
specifier: ^1.5.3
|
||||
version: 1.5.3
|
||||
specifier: ^1.5.6
|
||||
version: 1.5.6
|
||||
'@lezer/highlight':
|
||||
specifier: ^1.2.5
|
||||
version: 1.2.5
|
||||
@@ -473,8 +473,8 @@ packages:
|
||||
'@jridgewell/[email protected]':
|
||||
resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==}
|
||||
|
||||
'@lezer/[email protected].3':
|
||||
resolution: {integrity: sha512-H0iErY4e43LpXbYDyBci5W4v/RwTgGV3YzYOlJPiGZ8RY8w51kVE+xLn1tg3Z6UmSfyETvtsUK3r7YsgDQEI7Q==}
|
||||
'@lezer/[email protected].6':
|
||||
resolution: {integrity: sha512-NZxu3q49ck+YYbEJPuIPIyFP37XneBvzPIarBHEXBLBVfkZqQieZ/Y2boYnGNYtmjpOZLnAKs/lwqtmDpi365w==}
|
||||
|
||||
'@lezer/[email protected]':
|
||||
resolution: {integrity: sha512-vh9gWWJOXFVY8HBHK3Twzq8MgwG2iN4GSyzBP9sCGTe37P15x2R14VaBQk0VA0ezTRN1KHYBBsHhvpGZ2Xy/pA==}
|
||||
@@ -2481,21 +2481,21 @@ snapshots:
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
|
||||
'@codemirror/[email protected]':
|
||||
dependencies:
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
|
||||
'@codemirror/[email protected]':
|
||||
dependencies:
|
||||
'@codemirror/lang-html': 6.4.12
|
||||
'@codemirror/lang-javascript': 6.2.5
|
||||
'@codemirror/language': 6.13.1
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
@@ -2509,7 +2509,7 @@ snapshots:
|
||||
'@codemirror/autocomplete': 6.20.3
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/state': 6.7.6
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/css': 1.3.9
|
||||
|
||||
'@codemirror/[email protected]':
|
||||
@@ -2517,7 +2517,7 @@ snapshots:
|
||||
'@codemirror/autocomplete': 6.20.3
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/state': 6.7.6
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/go': 1.0.1
|
||||
|
||||
'@codemirror/[email protected]':
|
||||
@@ -2528,7 +2528,7 @@ snapshots:
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/css': 1.3.9
|
||||
'@lezer/html': 1.3.13
|
||||
|
||||
@@ -2544,7 +2544,7 @@ snapshots:
|
||||
'@codemirror/lint': 6.9.7
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/javascript': 1.5.6
|
||||
|
||||
'@codemirror/[email protected]':
|
||||
@@ -2554,7 +2554,7 @@ snapshots:
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
@@ -2567,7 +2567,7 @@ snapshots:
|
||||
dependencies:
|
||||
'@codemirror/lang-css': 6.3.1
|
||||
'@codemirror/language': 6.13.1
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
@@ -2578,7 +2578,7 @@ snapshots:
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
@@ -2589,7 +2589,7 @@ snapshots:
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/markdown': 1.8.0
|
||||
|
||||
'@codemirror/[email protected]':
|
||||
@@ -2597,7 +2597,7 @@ snapshots:
|
||||
'@codemirror/lang-html': 6.4.12
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/state': 6.7.6
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/php': 1.0.6
|
||||
|
||||
'@codemirror/[email protected]':
|
||||
@@ -2605,7 +2605,7 @@ snapshots:
|
||||
'@codemirror/autocomplete': 6.20.3
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/state': 6.7.6
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/python': 1.1.19
|
||||
|
||||
'@codemirror/[email protected]':
|
||||
@@ -2618,7 +2618,7 @@ snapshots:
|
||||
'@codemirror/lang-css': 6.3.1
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/state': 6.7.6
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/sass': 1.1.0
|
||||
|
||||
'@codemirror/[email protected]':
|
||||
@@ -2626,7 +2626,7 @@ snapshots:
|
||||
'@codemirror/autocomplete': 6.20.3
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/state': 6.7.6
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
@@ -2635,14 +2635,14 @@ snapshots:
|
||||
'@codemirror/lang-html': 6.4.12
|
||||
'@codemirror/lang-javascript': 6.2.5
|
||||
'@codemirror/language': 6.13.1
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
'@codemirror/[email protected]':
|
||||
dependencies:
|
||||
'@codemirror/language': 6.13.1
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
@@ -2652,7 +2652,7 @@ snapshots:
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/xml': 1.0.6
|
||||
|
||||
'@codemirror/[email protected]':
|
||||
@@ -2660,7 +2660,7 @@ snapshots:
|
||||
'@codemirror/autocomplete': 6.20.3
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/state': 6.7.6
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
'@lezer/yaml': 1.0.4
|
||||
@@ -2696,7 +2696,7 @@ snapshots:
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/streamparser': 6.0.0
|
||||
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
style-mod: 4.1.4
|
||||
@@ -2832,101 +2832,101 @@ snapshots:
|
||||
'@jridgewell/resolve-uri': 3.1.2
|
||||
'@jridgewell/sourcemap-codec': 1.6.0
|
||||
|
||||
'@lezer/[email protected].3': {}
|
||||
'@lezer/[email protected].6': {}
|
||||
|
||||
'@lezer/[email protected]':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
'@lezer/[email protected]':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
'@lezer/[email protected]':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
'@lezer/[email protected]':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
'@lezer/[email protected]':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
|
||||
'@lezer/[email protected]':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
'@lezer/[email protected]':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
'@lezer/[email protected]':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
'@lezer/[email protected]':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
'@lezer/[email protected](patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
|
||||
'@lezer/[email protected]':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/highlight': 1.2.5
|
||||
|
||||
'@lezer/[email protected]':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
'@lezer/[email protected]':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
'@lezer/[email protected]':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
'@lezer/[email protected]':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
'@lezer/[email protected]':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
'@lezer/[email protected]':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
@@ -3200,12 +3200,12 @@ snapshots:
|
||||
dependencies:
|
||||
'@codemirror/autocomplete': 6.20.3
|
||||
'@codemirror/language': 6.13.1
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@plutojl/lezer-julia': 1.2.0
|
||||
|
||||
'@plutojl/[email protected]':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
|
||||
+73
-7
@@ -155,6 +155,23 @@ fn flash_taskbar_unless_focused(app: &AppHandle) {
|
||||
});
|
||||
}
|
||||
|
||||
/// Sends `event` to `peers` (failures ignored: a window may be closing) and then to `owner`,
|
||||
/// whose result is returned. The event is serialised once; `send` gets each window's copy of the
|
||||
/// JSON, which Tauri's `emit_to` would otherwise re-serialise per window (large for
|
||||
/// diagnostics of a big file).
|
||||
fn fan_out<T: serde::Serialize>(
|
||||
event: &T,
|
||||
peers: &[String],
|
||||
owner: &str,
|
||||
mut send: impl FnMut(&str, String) -> tauri::Result<()>,
|
||||
) -> tauri::Result<()> {
|
||||
let json = serde_json::to_string(event)?;
|
||||
for peer in peers {
|
||||
let _ = send(peer, json.clone());
|
||||
}
|
||||
send(owner, json)
|
||||
}
|
||||
|
||||
impl EventSink for TauriSink {
|
||||
fn emit(&self, event: IdeEvent) {
|
||||
if matches!(
|
||||
@@ -180,13 +197,12 @@ impl EventSink for TauriSink {
|
||||
}
|
||||
let result = match &self.window {
|
||||
Some(label) => {
|
||||
for target in crate::windows::document_windows(&self.app, label)
|
||||
.into_iter()
|
||||
.filter(|_| !matches!(&event, IdeEvent::McpRequest { .. } | IdeEvent::McpRequestClosed { .. }))
|
||||
{
|
||||
let _ = self.app.emit_to(target.as_str(), IDE_EVENT, &event);
|
||||
}
|
||||
self.app.emit_to(label.as_str(), IDE_EVENT, &event)
|
||||
let peers = if matches!(&event, IdeEvent::McpRequest { .. } | IdeEvent::McpRequestClosed { .. }) {
|
||||
Vec::new()
|
||||
} else {
|
||||
crate::windows::document_windows(&self.app, label)
|
||||
};
|
||||
fan_out(&event, &peers, label, |window, json| self.app.emit_str_to(window, IDE_EVENT, json))
|
||||
}
|
||||
None => self.app.emit(IDE_EVENT, &event),
|
||||
};
|
||||
@@ -240,6 +256,56 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Counts how often it is serialised.
|
||||
struct CountingEvent<'a> {
|
||||
event: &'a IdeEvent,
|
||||
serialised: AtomicUsize,
|
||||
}
|
||||
|
||||
impl serde::Serialize for CountingEvent<'_> {
|
||||
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
self.serialised.fetch_add(1, Ordering::Relaxed);
|
||||
self.event.serialize(serializer)
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fan_out_serialises_once_for_every_window() {
|
||||
let event = diagnostics("/p/a.rs", "rust-analyzer", "unused");
|
||||
let counting = CountingEvent { event: &event, serialised: AtomicUsize::new(0) };
|
||||
let peers: Vec<String> = (1..=7).map(|n| format!("comparison-project-1-{n}")).collect();
|
||||
let mut sent = Vec::new();
|
||||
|
||||
fan_out(&counting, &peers, "project-1", |window, json| {
|
||||
sent.push((window.to_owned(), json));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(counting.serialised.load(Ordering::Relaxed), 1);
|
||||
let expected = serde_json::to_string(&event).unwrap();
|
||||
let windows: Vec<&str> = sent.iter().map(|(window, _)| window.as_str()).collect();
|
||||
assert_eq!(windows.len(), 8);
|
||||
assert_eq!(windows.last(), Some(&"project-1"));
|
||||
assert_eq!(windows[..7], peers.iter().map(String::as_str).collect::<Vec<_>>()[..]);
|
||||
assert!(sent.iter().all(|(_, json)| json == &expected));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fan_out_ignores_peer_failures_and_returns_the_owners_result() {
|
||||
let event = task("indexing", false);
|
||||
let peers = vec!["comparison-project-1-1".to_owned(), "comparison-project-1-2".to_owned()];
|
||||
let mut reached = Vec::new();
|
||||
|
||||
let result = fan_out(&event, &peers, "project-1", |window, _| {
|
||||
reached.push(window.to_owned());
|
||||
if window == "project-1" { Err(tauri::Error::WebviewNotFound) } else { Err(tauri::Error::WindowNotFound) }
|
||||
});
|
||||
|
||||
assert!(matches!(result, Err(tauri::Error::WebviewNotFound)));
|
||||
assert_eq!(reached, ["comparison-project-1-1", "comparison-project-1-2", "project-1"]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn coalesces_diagnostics_by_path_and_source() {
|
||||
let (sink, events) = setup();
|
||||
|
||||
@@ -286,6 +286,7 @@ fs_read_range always project_host bin
|
||||
fs_read_text always project_host bindings async
|
||||
fs_rename always project_host bindings async
|
||||
fs_resolve_reference always project_host bindings async
|
||||
fs_scratches_dir always project_host bindings sync
|
||||
fs_set_writable always project_host bindings sync
|
||||
fs_synchronize_directories always project_host bindings async
|
||||
fs_undo_delete always project_host bindings async
|
||||
|
||||
@@ -707,6 +707,11 @@ export const commands = {
|
||||
fsRename: (from: string, to: string) => typedError<null, IdeError>(__TAURI_INVOKE("fs_rename", { from, to })),
|
||||
/** The existing file or directory a path written in `from` names (`href`, `url()`, a string literal). */
|
||||
fsResolveReference: (from: IpcPath, value: string) => typedError<string | null, IdeError>(__TAURI_INVOKE("fs_resolve_reference", { from, value })),
|
||||
/**
|
||||
* The scratch files' folder of this host (`<data dir>/scratches`), created. A remote window
|
||||
* keeps its scratches on the server, where its file commands run.
|
||||
*/
|
||||
fsScratchesDir: () => typedError<IpcPath, IdeError>(__TAURI_INVOKE("fs_scratches_dir")),
|
||||
/**
|
||||
* Toggle Read-only Attribute: sets the writable bit (and the open document's
|
||||
* state). Returns whether the file is read-only now.
|
||||
@@ -2529,6 +2534,8 @@ chosen: string | null } | { type: "thought"; text: string;
|
||||
startedMs?: number | null } | { type: "tool"; id: string; title: string;
|
||||
/** ACP tool kind: `read`, `edit`, `execute`, `search`, `fetch`, `think`… */
|
||||
kind: string; status: AgentToolStatus; locations: IpcPath[];
|
||||
/** Images returned by the tool, kept separately from its truncated text. */
|
||||
images?: AgentImage[];
|
||||
/** Text the tool reported (command output…), truncated. */
|
||||
output: string | null; diffs: AgentToolDiff[];
|
||||
/** When the call started and ended (ms since the epoch); `None` in tasks saved before. */
|
||||
|
||||
@@ -238,11 +238,13 @@ function buildDecorations(state: EditorState): DecorationSet {
|
||||
|
||||
const lensTheme = EditorView.theme({
|
||||
// IDEA paints code vision with the colour scheme's Inline hints attribute.
|
||||
// At least 16px, and taller when the hint font needs it: the row grows with its items, so a
|
||||
// large editor font or a fallback font that inks below the baseline (CJK) is never cut off.
|
||||
".cm-openidea-lens": {
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: "12px",
|
||||
height: "16px",
|
||||
minHeight: "16px",
|
||||
color: "var(--fg-inlay, var(--fg-muted))",
|
||||
WebkitUserSelect: "none",
|
||||
userSelect: "none",
|
||||
@@ -276,7 +278,10 @@ const lensTheme = EditorView.theme({
|
||||
// Pinned to the line, the hint may run past the editor's edge (IDEA clips it there); cap it so a
|
||||
// long one cannot stretch across the whole window first.
|
||||
maxWidth: "min(60ch, 50vw)",
|
||||
overflow: "hidden",
|
||||
// The box is 1em tall (the anchor's `lineHeight: 1`): clip only past the side, so a glyph that
|
||||
// inks above or below its em box (CJK fallback fonts) still shows whole.
|
||||
overflowX: "clip",
|
||||
overflowY: "visible",
|
||||
pointerEvents: "auto",
|
||||
},
|
||||
".cm-openidea-lensItem": {
|
||||
@@ -293,6 +298,9 @@ const lensTheme = EditorView.theme({
|
||||
fontFamily: "var(--font-ui)",
|
||||
fontSize: "calc(1em - 1px)",
|
||||
},
|
||||
// The row's items size to the fonts their text is drawn with (fallback fonts included), not to the
|
||||
// editor's line height, which `font: inherit` brings along.
|
||||
".cm-openidea-lens > .cm-openidea-lensItem": { lineHeight: "normal" },
|
||||
".cm-openidea-lensAction": { cursor: "pointer" },
|
||||
".cm-openidea-lensAction:hover": { color: "var(--accent)", textDecoration: "underline" },
|
||||
".cm-openidea-lensIcon-run": { color: "var(--success)" },
|
||||
|
||||
@@ -417,6 +417,79 @@ function leadingCommentStart(state: EditorState, a: number): number {
|
||||
|
||||
export type StatementMove = { spec: TransactionSpec } | "noop" | "line";
|
||||
|
||||
/** A `case` / `default` label whose branch body follows as its siblings (Go, JavaScript, Java). */
|
||||
const CASE_LABEL = /^(Case|CaseLabel|DefaultLabel|SwitchLabel)$/;
|
||||
|
||||
/**
|
||||
* Move Statement on a `case` label of a switch whose branches are flat
|
||||
* (label, then the body as siblings): the branch, from its first stacked
|
||||
* label to its last non-blank line, swaps with the neighbouring branch, as
|
||||
* IDEA's case block mover does. `noop` at the first / last branch.
|
||||
*/
|
||||
function planCaseMove(state: EditorState, label: Node, up: boolean): StatementMove {
|
||||
const doc = state.doc;
|
||||
const block = label.parent!;
|
||||
const close = doc.lineAt(block.to).number;
|
||||
const isLabel = (l: number) => {
|
||||
const n = statementStartingAt(state, l);
|
||||
return !!n && CASE_LABEL.test(n.type.name) && n.parent?.from === block.from && n.parent.to === block.to;
|
||||
};
|
||||
const start = (l: number) => {
|
||||
while (l > 1 && isLabel(l - 1)) l--;
|
||||
return l;
|
||||
};
|
||||
// The line where the branch starting at `l` ends: its last non-blank line before the next branch or the closing brace.
|
||||
const end = (l: number) => {
|
||||
let k = l + 1;
|
||||
while (k < close && isLabel(k)) k++;
|
||||
while (k < close && !isLabel(k)) k++;
|
||||
k--;
|
||||
while (k > l && firstToken(state, k) === null) k--;
|
||||
return k;
|
||||
};
|
||||
const a = start(doc.lineAt(label.from).number);
|
||||
const b = end(a);
|
||||
let s: number;
|
||||
let e: number;
|
||||
if (up) {
|
||||
let p = a - 1;
|
||||
while (p > 0 && doc.line(p).from > block.from && !isLabel(p)) p--;
|
||||
if (p < 1 || doc.line(p).from <= block.from || !isLabel(p)) return "noop";
|
||||
s = start(p);
|
||||
e = end(s);
|
||||
} else {
|
||||
let n = b + 1;
|
||||
while (n < close && !isLabel(n)) n++;
|
||||
if (n >= close) return "noop";
|
||||
s = n;
|
||||
e = end(n);
|
||||
}
|
||||
const [first, second] = up
|
||||
? [
|
||||
{ s, e },
|
||||
{ s: a, e: b },
|
||||
]
|
||||
: [
|
||||
{ s: a, e: b },
|
||||
{ s, e },
|
||||
];
|
||||
const from = doc.line(first.s).from;
|
||||
const to = doc.line(second.e).to;
|
||||
const textFirst = state.sliceDoc(from, doc.line(first.e).to);
|
||||
const textSecond = state.sliceDoc(doc.line(second.s).from, to);
|
||||
const between = state.sliceDoc(doc.line(first.e).to, doc.line(second.s).from);
|
||||
const head = state.selection.main.head;
|
||||
const movedFrom = up ? from : from + textSecond.length + between.length;
|
||||
return {
|
||||
spec: {
|
||||
changes: { from, to, insert: textSecond + between + textFirst },
|
||||
selection: EditorSelection.cursor(movedFrom + (head - doc.line(a).from)),
|
||||
scrollIntoView: true,
|
||||
userEvent: "move.line",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Move Statement as in IDEA: the statement around the caret (whole lines)
|
||||
* moves past the next statement; into a block when the neighbour is a block
|
||||
@@ -429,6 +502,7 @@ export function planStatementMove(state: EditorState, up: boolean): StatementMov
|
||||
const head = state.selection.main.head;
|
||||
const cur = statementAround(state, head);
|
||||
if (!cur) return "line";
|
||||
if (CASE_LABEL.test(cur.type.name) && cur.parent) return planCaseMove(state, cur, up);
|
||||
const doc = state.doc;
|
||||
if (/^[{}]$/.test(cur.type.name)) {
|
||||
for (let g: Node | null = cur.parent; g; g = g.parent)
|
||||
|
||||
@@ -67,6 +67,7 @@ function show(view: EditorView): string {
|
||||
|
||||
const javascript = await languages.find((l) => l.name === "JavaScript")!.load();
|
||||
const yaml = await languages.find((l) => l.name === "YAML")!.load();
|
||||
const goLang = await languages.find((l) => l.name === "Go")!.load();
|
||||
|
||||
describe("Move Statement", () => {
|
||||
it("moves a multi-line statement as a whole, never one of its lines", () => {
|
||||
@@ -94,6 +95,34 @@ describe("Move Statement", () => {
|
||||
expect(v.state.doc.toString()).toBe("function f() {\n a();\n}\nb();");
|
||||
});
|
||||
|
||||
it("moves a Go switch case with its whole body past the neighbouring case", () => {
|
||||
const go = make(
|
||||
"func f(n int) int {\n\tswitch n {\n\tcase 0:\n\t\treturn 0\n\tca|se 1:\n\t\tv := 1\n\t\treturn v\n\tdefault:\n\t\treturn -1\n\t}\n}",
|
||||
goLang,
|
||||
);
|
||||
moveStatementUp(go);
|
||||
expect(show(go)).toBe(
|
||||
"func f(n int) int {\n\tswitch n {\n\tca|se 1:\n\t\tv := 1\n\t\treturn v\n\tcase 0:\n\t\treturn 0\n\tdefault:\n\t\treturn -1\n\t}\n}",
|
||||
);
|
||||
moveStatementUp(go);
|
||||
expect(go.state.doc.toString()).toContain("switch n {\n\tcase 1:\n\t\tv := 1");
|
||||
moveStatementDown(go);
|
||||
moveStatementDown(go);
|
||||
expect(show(go)).toBe(
|
||||
"func f(n int) int {\n\tswitch n {\n\tcase 0:\n\t\treturn 0\n\tdefault:\n\t\treturn -1\n\tca|se 1:\n\t\tv := 1\n\t\treturn v\n\t}\n}",
|
||||
);
|
||||
moveStatementDown(go);
|
||||
expect(go.state.doc.toString()).toContain("\t\treturn v\n\t}\n}");
|
||||
});
|
||||
|
||||
it("moves a JavaScript case with its stacked labels and blank line kept between branches", () => {
|
||||
const v = make("switch (x) {\n case 1:\n a();\n break;\n\n case 2:\n |case 3:\n b();\n}", javascript);
|
||||
moveStatementUp(v);
|
||||
expect(v.state.doc.toString()).toBe(
|
||||
"switch (x) {\n case 2:\n case 3:\n b();\n\n case 1:\n a();\n break;\n}",
|
||||
);
|
||||
});
|
||||
|
||||
it("passes a neighbouring function as a whole", () => {
|
||||
const v = make("|a();\nfunction f() {\n b();\n}", javascript);
|
||||
moveStatementDown(v);
|
||||
|
||||
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
|
||||
import { ensureSyntaxTree, syntaxTree } from "@codemirror/language";
|
||||
import { javascript } from "@codemirror/lang-javascript";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { TreeFragment } from "@lezer/common";
|
||||
|
||||
/** Functions with long doc comments: re-parsing reuses a whole comment as one node. */
|
||||
const source = Array.from(
|
||||
@@ -25,3 +26,63 @@ describe("incremental parsing (#4468)", () => {
|
||||
expect(tree.topNode.firstChild?.from).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
/** `count` documented classes: as many top-level statements, each after a doc comment longer than the parser's look-ahead margin. */
|
||||
function documentedClasses(count: number): string {
|
||||
return Array.from(
|
||||
{ length: count },
|
||||
(_, i) =>
|
||||
`/** Repository for entity ${i}, with a comment long enough to look ahead of. */\n` +
|
||||
`export class Repository${i}<T extends { id: number }> {\n` +
|
||||
` find(id: number): T | undefined {\n return this.items.get(id)\n }\n}\n\n`,
|
||||
).join("");
|
||||
}
|
||||
|
||||
const parser = javascript({ typescript: true }).language.parser;
|
||||
|
||||
/** Inserts `insert` at `at`, re-parsing incrementally from `tree`; returns the new tree and how many parser steps that took. */
|
||||
function reparse(doc: string, tree: ReturnType<typeof parser.parse>, at: number, insert: string) {
|
||||
const fragments = TreeFragment.applyChanges(TreeFragment.addTree(tree), [
|
||||
{ fromA: at, toA: at, fromB: at, toB: at + insert.length },
|
||||
]);
|
||||
const edited = doc.slice(0, at) + insert + doc.slice(at);
|
||||
const parse = parser.startParse(edited, fragments);
|
||||
let steps = 0;
|
||||
let result = null;
|
||||
while (!(result = parse.advance())) steps++;
|
||||
return { doc: edited, tree: result, steps };
|
||||
}
|
||||
|
||||
describe("incremental parsing of long statement lists", () => {
|
||||
// A repeat group's look-ahead was that of the whole list, ending at the last doc comment: no group before an
|
||||
// edit could be reused, so typing cost grew with the position in the file, one statement at a time.
|
||||
it("takes as many parser steps in a long file as in a short one", () => {
|
||||
const steps = (count: number) => {
|
||||
const doc = documentedClasses(count);
|
||||
const at = doc.indexOf("return", doc.length >> 1);
|
||||
return reparse(doc, parser.parse(doc), at, "a").steps;
|
||||
};
|
||||
const short = steps(100);
|
||||
const long = steps(1600);
|
||||
expect(long).toBeLessThan(short * 2);
|
||||
});
|
||||
|
||||
it("matches a fresh parse wherever the edit is", () => {
|
||||
const doc = documentedClasses(300);
|
||||
const tree = parser.parse(doc);
|
||||
const edits: Array<[string, string]> = [
|
||||
["/**", "a"],
|
||||
["return", "a"],
|
||||
["export class Repository150", "// "],
|
||||
["}\n\n/** Repository for entity 299", "}"],
|
||||
["find(id", "static "],
|
||||
];
|
||||
for (const [anchor, insert] of edits) {
|
||||
const at = doc.indexOf(anchor) + (anchor.startsWith("}") ? 0 : 0);
|
||||
const result = reparse(doc, tree, at, insert);
|
||||
expect(result.tree.toString(), `after inserting ${JSON.stringify(insert)} before ${JSON.stringify(anchor)}`).toBe(
|
||||
parser.parse(result.doc).toString(),
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* Paints an inline mark's background capped at `1lh` so a font taller than the line height
|
||||
* does not bleed into the rows above and below. When the inline box is shorter than `1lh`,
|
||||
* its own border box clips the gradient. Safari before 16.4 has no `lh` and drops the
|
||||
* shorthand, keeping the plain colour before it.
|
||||
*/
|
||||
export function inlineBackground(color: string) {
|
||||
return {
|
||||
backgroundColor: color,
|
||||
background: `linear-gradient(${color}, ${color}) center / 100% 1lh no-repeat`,
|
||||
WebkitBoxDecorationBreak: "clone",
|
||||
boxDecorationBreak: "clone",
|
||||
};
|
||||
}
|
||||
|
||||
/** Fallback style for an inline mark with a 1px frame (`inlineFramedModern` caps it at `1lh`). */
|
||||
export function inlineFramedFallback(fill: string, frame: string) {
|
||||
return {
|
||||
backgroundColor: fill,
|
||||
outline: `1px solid ${frame}`,
|
||||
outlineOffset: "-1px",
|
||||
WebkitBoxDecorationBreak: "clone",
|
||||
boxDecorationBreak: "clone",
|
||||
};
|
||||
}
|
||||
|
||||
/** `@supports (height: 1lh)` override for `inlineFramedFallback`: caps both fill and 1px frame at `1lh`. */
|
||||
export function inlineFramedModern(fill: string, frame: string) {
|
||||
return {
|
||||
outline: "none",
|
||||
background: [
|
||||
`linear-gradient(to bottom, ${frame} 0 1px, transparent 1px calc(100% - 1px), ${frame} calc(100% - 1px) 100%) center / 100% min(100%, 1lh) no-repeat`,
|
||||
`linear-gradient(to right, ${frame} 0 1px, transparent 1px calc(100% - 1px), ${frame} calc(100% - 1px) 100%) center / 100% min(100%, 1lh) no-repeat`,
|
||||
`linear-gradient(${fill}, ${fill}) center / calc(100% - 2px) calc(min(100%, 1lh) - 2px) no-repeat`,
|
||||
].join(", "),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { EditorView, runScopeHandlers } from "@codemirror/view";
|
||||
import { applySnippet, hasLinkedSnippetField } from "./linkedSnippet";
|
||||
|
||||
let view: EditorView;
|
||||
afterEach(() => view.destroy());
|
||||
|
||||
function expand(snippet: string) {
|
||||
view = new EditorView({
|
||||
state: EditorState.create({ extensions: [EditorState.allowMultipleSelections.of(true)] }),
|
||||
parent: document.body,
|
||||
});
|
||||
applySnippet(view, [{ from: 0, to: 0, snippet }]);
|
||||
}
|
||||
|
||||
const selected = () => view.state.selection.ranges.map(({ from, to }) => view.state.sliceDoc(from, to));
|
||||
const doc = () => view.state.doc.toString();
|
||||
const type = (text: string) => view.dispatch(view.state.replaceSelection(text));
|
||||
const press = (key: string) => runScopeHandlers(view, new KeyboardEvent("keydown", { key }), "editor");
|
||||
|
||||
describe("linked snippets", () => {
|
||||
it("selects the first occurrence of each variable and mirrors edits within its group", () => {
|
||||
expand("${1:x}/${1:x} ${2:y}/${2:y}${0}");
|
||||
expect(selected()).toEqual(["x"]);
|
||||
expect(view.state.selection.main.from).toBe(0);
|
||||
type("name");
|
||||
expect(doc()).toBe("name/name y/y");
|
||||
expect(press("Tab")).toBe(true);
|
||||
expect(selected()).toEqual(["y"]);
|
||||
expect(view.state.selection.main.from).toBe("name/name ".length);
|
||||
type("label");
|
||||
expect(doc()).toBe("name/name label/label");
|
||||
});
|
||||
|
||||
it("tracks adjacent empty occurrences and the next variable independently", () => {
|
||||
expand("${1}${1}${2:end}${0}");
|
||||
expect(selected()).toEqual([""]);
|
||||
type("x");
|
||||
type("y");
|
||||
expect(doc()).toBe("xyxyend");
|
||||
expect(press("Tab")).toBe(true);
|
||||
expect(selected()).toEqual(["end"]);
|
||||
type("!");
|
||||
expect(doc()).toBe("xyxy!");
|
||||
});
|
||||
|
||||
it.each(["Escape", "Tab"])("ends mirroring on %s", (key) => {
|
||||
expand("${1:x}/${1:x}${0}");
|
||||
if (key === "Escape") {
|
||||
expect(press(key)).toBe(true);
|
||||
expect(hasLinkedSnippetField(view.state, 1)).toBe(true);
|
||||
}
|
||||
expect(press(key)).toBe(true);
|
||||
expect(hasLinkedSnippetField(view.state, 1)).toBe(false);
|
||||
const { head } = view.state.selection.main;
|
||||
expect(head).toBe(key === "Escape" ? 1 : doc().length);
|
||||
view.dispatch({ changes: { from: 0, to: 1, insert: "changed" } });
|
||||
expect(doc()).toBe("changed/x");
|
||||
});
|
||||
|
||||
it("keeps a repeated last placeholder active until the end of the snippet", () => {
|
||||
expand("${1:one} ${2:two}/${2:two}");
|
||||
expect(press("Tab")).toBe(true);
|
||||
expect(selected()).toEqual(["two"]);
|
||||
type("new");
|
||||
expect(doc()).toBe("one new/new");
|
||||
expect(press("Tab")).toBe(true);
|
||||
expect(view.state.selection.main.head).toBe(doc().length);
|
||||
});
|
||||
|
||||
it("keeps fields linked after a separate edit before the snippet", () => {
|
||||
expand("call(${1:arg}, ${1:arg})${0}");
|
||||
const prefix = "import call;\n";
|
||||
view.dispatch({ changes: { from: 0, insert: prefix }, userEvent: "input.complete" });
|
||||
expect(selected()).toEqual(["arg"]);
|
||||
type("value");
|
||||
expect(doc()).toBe(prefix + "call(value, value)");
|
||||
expect(press("Tab")).toBe(true);
|
||||
expect(view.state.selection.main.head).toBe(doc().length);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,346 @@
|
||||
import {
|
||||
clearSnippet,
|
||||
closeCompletion,
|
||||
completionStatus,
|
||||
pickedCompletion,
|
||||
snippet,
|
||||
type Completion,
|
||||
} from "@codemirror/autocomplete";
|
||||
import { isolateHistory } from "@codemirror/commands";
|
||||
import { indentUnit } from "@codemirror/language";
|
||||
import {
|
||||
ChangeSet,
|
||||
EditorSelection,
|
||||
EditorState,
|
||||
MapMode,
|
||||
Prec,
|
||||
StateEffect,
|
||||
StateField,
|
||||
Text,
|
||||
type ChangeSpec,
|
||||
type Transaction,
|
||||
} from "@codemirror/state";
|
||||
import { Decoration, EditorView, keymap, WidgetType, type Command } from "@codemirror/view";
|
||||
import { isExternalChange } from "@/editor/api";
|
||||
|
||||
interface SnippetSite {
|
||||
from: number;
|
||||
to: number;
|
||||
snippet: string;
|
||||
}
|
||||
|
||||
interface SnippetRange {
|
||||
from: number;
|
||||
to: number;
|
||||
field: number;
|
||||
}
|
||||
|
||||
interface Segment extends SnippetRange {
|
||||
site: number;
|
||||
primary: boolean;
|
||||
}
|
||||
|
||||
interface ActiveSnippet {
|
||||
segments: readonly Segment[];
|
||||
active: number;
|
||||
last: number;
|
||||
mainSite: number;
|
||||
completion: boolean;
|
||||
}
|
||||
|
||||
const setSnippet = StateEffect.define<ActiveSnippet | null>();
|
||||
const fieldMark = Decoration.mark({ class: "cm-snippetField" });
|
||||
const fieldCursor = Decoration.widget({
|
||||
widget: new (class extends WidgetType {
|
||||
toDOM() {
|
||||
const span = document.createElement("span");
|
||||
span.className = "cm-snippetFieldPosition";
|
||||
return span;
|
||||
}
|
||||
ignoreEvent() {
|
||||
return false;
|
||||
}
|
||||
})(),
|
||||
});
|
||||
|
||||
function primarySegments(value: ActiveSnippet, field = value.active) {
|
||||
return value.segments.filter((segment) => segment.field === field && segment.primary);
|
||||
}
|
||||
|
||||
function contains(range: SnippetRange, from: number, to: number): boolean {
|
||||
return range.from <= from && to <= range.to;
|
||||
}
|
||||
|
||||
function selectionInField(value: ActiveSnippet, selection: EditorSelection): boolean {
|
||||
const primaries = primarySegments(value);
|
||||
return selection.ranges.every(({ from, to }) => primaries.some((segment) => contains(segment, from, to)));
|
||||
}
|
||||
|
||||
const fields = StateField.define<ActiveSnippet | null>({
|
||||
create: () => null,
|
||||
update(value, tr) {
|
||||
const next = tr.effects.find((effect) => effect.is(setSnippet));
|
||||
if (next) return next.value;
|
||||
if (!value) return null;
|
||||
if (tr.docChanged) {
|
||||
const segments: Segment[] = [];
|
||||
for (const segment of value.segments) {
|
||||
const from = tr.changes.mapPos(segment.from, -1, MapMode.TrackDel);
|
||||
const to = tr.changes.mapPos(segment.to, 1, MapMode.TrackDel);
|
||||
if (from === null || to === null || from < (segments.at(-1)?.to ?? 0)) return null;
|
||||
segments.push({ ...segment, from, to });
|
||||
}
|
||||
value = { ...value, segments };
|
||||
}
|
||||
return tr.selection && !selectionInField(value, tr.selection) ? null : value;
|
||||
},
|
||||
provide: (field) =>
|
||||
EditorView.decorations.from(field, (value) =>
|
||||
value
|
||||
? Decoration.set(
|
||||
value.segments.map(({ from, to }) => (from === to ? fieldCursor : fieldMark).range(from, to)),
|
||||
true,
|
||||
)
|
||||
: Decoration.none,
|
||||
),
|
||||
});
|
||||
|
||||
// Keep the edit and its mirrors in one history entry.
|
||||
const mirrorEdits = EditorState.transactionFilter.of((tr) => {
|
||||
const value = tr.startState.field(fields, false);
|
||||
if (
|
||||
!value ||
|
||||
!tr.docChanged ||
|
||||
isExternalChange(tr) ||
|
||||
tr.isUserEvent("undo") ||
|
||||
tr.isUserEvent("redo") ||
|
||||
tr.effects.some((effect) => effect.is(setSnippet))
|
||||
)
|
||||
return tr;
|
||||
|
||||
const primaries = primarySegments(value);
|
||||
const edited = new Map<Segment, number>();
|
||||
let outside = false;
|
||||
let touchesOtherSegment = false;
|
||||
tr.changes.iterChangedRanges((from, to, newFrom, newTo) => {
|
||||
const segment = primaries.find((range) => contains(range, from, to));
|
||||
if (segment) edited.set(segment, (edited.get(segment) ?? 0) + (newTo - newFrom) - (to - from));
|
||||
else {
|
||||
outside = true;
|
||||
touchesOtherSegment ||= value.segments.some((range) => from <= range.to && to >= range.from);
|
||||
}
|
||||
}, true);
|
||||
if (outside) return edited.size || touchesOtherSegment ? [tr, { effects: setSnippet.of(null) }] : tr;
|
||||
|
||||
const changes: ChangeSpec[] = [];
|
||||
const replacements = new Map<number, Text>();
|
||||
let typedOffset = 0;
|
||||
let mirrorOffset = 0;
|
||||
// Map in source order so neighboring stops keep their own boundaries even when they touch.
|
||||
const segments = value.segments.map((segment) => {
|
||||
const start = segment.from + typedOffset;
|
||||
const from = start + mirrorOffset;
|
||||
let length = segment.to - segment.from;
|
||||
const delta = edited.get(segment);
|
||||
if (delta !== undefined) {
|
||||
length += delta;
|
||||
replacements.set(segment.site, tr.newDoc.slice(start, start + length));
|
||||
typedOffset += delta;
|
||||
} else if (segment.field === value.active && !segment.primary) {
|
||||
const insert = replacements.get(segment.site);
|
||||
if (insert && !insert.eq(tr.newDoc.slice(start, start + length))) {
|
||||
changes.push({ from: start, to: start + length, insert });
|
||||
mirrorOffset += insert.length - length;
|
||||
length = insert.length;
|
||||
}
|
||||
}
|
||||
return { ...segment, from, to: from + length };
|
||||
});
|
||||
const mirrors = ChangeSet.of(changes, tr.newDoc.length);
|
||||
const next = { ...value, segments };
|
||||
const staysInField = selectionInField(next, tr.newSelection.map(mirrors));
|
||||
return [tr, { changes: mirrors, effects: setSnippet.of(staysInField ? next : null), sequential: true }];
|
||||
});
|
||||
|
||||
function clearLinkedSnippet(view: EditorView): boolean {
|
||||
if (!view.state.field(fields, false)) return false;
|
||||
view.dispatch({ effects: setSnippet.of(null) });
|
||||
return true;
|
||||
}
|
||||
|
||||
export const escapeSnippet: Command = (view) => {
|
||||
const sel = view.state.selection;
|
||||
if (sel.ranges.some((r) => !r.empty)) {
|
||||
closeCompletion(view);
|
||||
view.dispatch({
|
||||
selection: EditorSelection.create(
|
||||
sel.ranges.map((r) => EditorSelection.cursor(r.head)),
|
||||
sel.mainIndex,
|
||||
),
|
||||
});
|
||||
return true;
|
||||
}
|
||||
if (completionStatus(view.state) === "active") return closeCompletion(view);
|
||||
return clearLinkedSnippet(view) || clearSnippet(view);
|
||||
};
|
||||
|
||||
function fieldSelection(value: ActiveSnippet, field: number): EditorSelection {
|
||||
return EditorSelection.create(
|
||||
primarySegments(value, field).map(({ from, to }) => EditorSelection.range(from, to)),
|
||||
value.mainSite,
|
||||
);
|
||||
}
|
||||
|
||||
function selectField(view: EditorView, value: ActiveSnippet, active: number): boolean {
|
||||
if (active < 0 || active > value.last) return false;
|
||||
view.dispatch({
|
||||
selection: fieldSelection(value, active),
|
||||
effects: setSnippet.of(active === value.last ? null : { ...value, active }),
|
||||
scrollIntoView: true,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
export function hasLinkedSnippetField(state: EditorState, direction: 1 | -1): boolean {
|
||||
const value = state.field(fields, false);
|
||||
return !!value && (direction === 1 ? value.active < value.last : value.active > 0);
|
||||
}
|
||||
|
||||
export const nextLiveSnippetField: Command = (view) => {
|
||||
const value = view.state.field(fields, false);
|
||||
return !!value && !value.completion && selectField(view, value, value.active + 1);
|
||||
};
|
||||
|
||||
const linkedSnippetExtension = [
|
||||
fields,
|
||||
mirrorEdits,
|
||||
Prec.highest(
|
||||
keymap.of([
|
||||
{
|
||||
key: "Tab",
|
||||
run: (view) => {
|
||||
const value = view.state.field(fields);
|
||||
return (
|
||||
!!value &&
|
||||
!view.state.readOnly &&
|
||||
completionStatus(view.state) !== "active" &&
|
||||
selectField(view, value, value.active + 1)
|
||||
);
|
||||
},
|
||||
shift: (view) => {
|
||||
const value = view.state.field(fields);
|
||||
return !!value && selectField(view, value, value.active - 1);
|
||||
},
|
||||
},
|
||||
{ key: "Escape", run: (view) => !!view.state.field(fields) && escapeSnippet(view) },
|
||||
]),
|
||||
),
|
||||
EditorView.domEventHandlers({
|
||||
mousedown(event, view) {
|
||||
const value = view.state.field(fields);
|
||||
if (!value || event.button !== 0) return false;
|
||||
const pos = view.posAtCoords({ x: event.clientX, y: event.clientY });
|
||||
if (pos === null) return false;
|
||||
const segment = value.segments.find((range) => contains(range, pos, pos));
|
||||
return !!segment && segment.field !== value.active && selectField(view, value, segment.field);
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
function codeMirrorSnippet(tr: Transaction): { active: number; ranges: SnippetRange[] } | undefined {
|
||||
// CodeMirror exposes the native snippet's unmerged ranges through its state effect.
|
||||
return tr.effects
|
||||
.map(({ value }) => value)
|
||||
.find((value) => {
|
||||
return value && typeof value.active === "number" && Array.isArray(value.ranges);
|
||||
});
|
||||
}
|
||||
|
||||
export function snippetFieldMoved(tr: Transaction): number | undefined {
|
||||
const linked = tr.effects.find((effect) => effect.is(setSnippet));
|
||||
if (linked) return linked.value?.completion ? undefined : linked.value?.active;
|
||||
return codeMirrorSnippet(tr)?.active;
|
||||
}
|
||||
|
||||
/** Render with CodeMirror to keep its snippet syntax and indentation. */
|
||||
function instantiate(source: EditorState, site: SnippetSite) {
|
||||
const line = source.doc.lineAt(site.from);
|
||||
const from = site.from - line.from;
|
||||
const to = site.to - line.from;
|
||||
const state = EditorState.create({
|
||||
doc: source.doc.slice(line.from, source.doc.lineAt(site.to).to),
|
||||
selection: EditorSelection.cursor(to),
|
||||
extensions: [indentUnit.of(source.facet(indentUnit))],
|
||||
});
|
||||
let insert = Text.empty;
|
||||
let ranges: SnippetRange[] = [];
|
||||
// An extra anonymous stop exposes the range effect even when a snippet has only one field.
|
||||
snippet(site.snippet + "#{}")(
|
||||
{
|
||||
state,
|
||||
dispatch(tr) {
|
||||
tr.changes.iterChanges((_from, _to, _start, _end, text) => {
|
||||
insert = text;
|
||||
});
|
||||
ranges = codeMirrorSnippet(tr)?.ranges ?? [];
|
||||
},
|
||||
},
|
||||
null,
|
||||
from,
|
||||
to,
|
||||
);
|
||||
const end = ranges.at(-1);
|
||||
const seen = new Set<number>();
|
||||
const segments = ranges.slice(0, -1).map((range) => {
|
||||
const primary = !seen.has(range.field);
|
||||
seen.add(range.field);
|
||||
return { ...range, primary };
|
||||
});
|
||||
return { ...site, offset: from, insert, segments, end };
|
||||
}
|
||||
|
||||
export function applySnippet(view: EditorView, sites: readonly SnippetSite[], completion: Completion | null = null) {
|
||||
const { state } = view;
|
||||
const { main } = state.selection;
|
||||
const entries = sites.map((site) =>
|
||||
instantiate(state, { ...site, to: sites.length === 1 && site.to === main.from ? main.to : site.to }),
|
||||
);
|
||||
if (entries.length === 1 && entries[0]!.segments.every((segment) => segment.primary)) {
|
||||
const { snippet: source, from, to } = sites[0]!;
|
||||
clearLinkedSnippet(view);
|
||||
snippet(source)(view, completion, from, to);
|
||||
return;
|
||||
}
|
||||
|
||||
const changes = state.changes(entries.map(({ from, to, insert }) => ({ from, to, insert })));
|
||||
let last = Math.max(...entries[0]!.segments.map(({ field }) => field));
|
||||
const needsEnd = entries.some(({ segments }) =>
|
||||
segments.some((segment) => segment.field === last && !segment.primary),
|
||||
);
|
||||
if (needsEnd) last++;
|
||||
const segments = entries.flatMap((entry, site) => {
|
||||
const offset = changes.mapPos(entry.from, -1) - entry.offset;
|
||||
const ranges = [...entry.segments];
|
||||
if (needsEnd && entry.end) ranges.push({ ...entry.end, primary: true });
|
||||
return ranges.map((segment) => ({ ...segment, site, from: segment.from + offset, to: segment.to + offset }));
|
||||
});
|
||||
const value = {
|
||||
segments,
|
||||
active: 0,
|
||||
last,
|
||||
mainSite: sites.length === 1 ? 0 : state.selection.mainIndex,
|
||||
completion: !!completion,
|
||||
};
|
||||
clearSnippet(view);
|
||||
view.dispatch({
|
||||
changes,
|
||||
selection: fieldSelection(value, 0),
|
||||
effects: [
|
||||
setSnippet.of(last > 0 ? value : null),
|
||||
...(state.field(fields, false) === undefined ? [StateEffect.appendConfig.of(linkedSnippetExtension)] : []),
|
||||
],
|
||||
annotations: completion ? pickedCompletion.of(completion) : isolateHistory.of("full"),
|
||||
userEvent: completion ? "input.complete" : undefined,
|
||||
scrollIntoView: true,
|
||||
});
|
||||
}
|
||||
@@ -68,18 +68,30 @@ function type(view: EditorView, text: string) {
|
||||
);
|
||||
}
|
||||
|
||||
/** One Backspace before every caret. */
|
||||
/** One Backspace at every caret, or over every selection. */
|
||||
function backspace(view: EditorView) {
|
||||
const { state } = view;
|
||||
view.dispatch(
|
||||
state.changeByRange((r) => ({
|
||||
changes: { from: Math.max(0, r.head - 1), to: r.head },
|
||||
range: EditorSelection.cursor(Math.max(0, r.head - 1)),
|
||||
})),
|
||||
state.changeByRange((r) => {
|
||||
const from = r.empty ? Math.max(0, r.head - 1) : r.from;
|
||||
return { changes: { from, to: r.to }, range: EditorSelection.cursor(from) };
|
||||
}),
|
||||
{ userEvent: "delete.backward" },
|
||||
);
|
||||
}
|
||||
|
||||
/** One Delete after every caret. */
|
||||
function deleteForward(view: EditorView) {
|
||||
const { state } = view;
|
||||
view.dispatch(
|
||||
state.changeByRange((r) => ({
|
||||
changes: { from: r.head, to: Math.min(state.doc.length, r.head + 1) },
|
||||
range: EditorSelection.cursor(r.head),
|
||||
})),
|
||||
{ userEvent: "delete.forward" },
|
||||
);
|
||||
}
|
||||
|
||||
describe("linked html tags", () => {
|
||||
it("renames the closing tag while the opening one is typed", () => {
|
||||
const v = make('<div| class="container">\n Content\n</div>');
|
||||
@@ -192,6 +204,84 @@ describe("linked html tags", () => {
|
||||
expect(closing.state.doc.toString()).toBe("<div>content</di>v>");
|
||||
});
|
||||
|
||||
// #5314: removing a tag piece by piece is a deletion, not a rename. Once its `>` (or `</`)
|
||||
// is gone the tag is incomplete, and the name edits after that must not follow.
|
||||
describe("deleting a whole tag", () => {
|
||||
it("leaves the opening tag alone while the closing tag is backspaced away", () => {
|
||||
const v = make("<div>x</div>|");
|
||||
for (let i = 0; i < "</div>".length; i++) backspace(v);
|
||||
expect(show(v)).toBe("<div>x|");
|
||||
});
|
||||
|
||||
it("leaves the closing tag alone while the opening tag is backspaced away", () => {
|
||||
const v = make("<div>|x</div>");
|
||||
for (let i = 0; i < "<div>".length; i++) backspace(v);
|
||||
expect(show(v)).toBe("|x</div>");
|
||||
});
|
||||
|
||||
it("leaves the opening tag alone when the closing tag is deleted forwards", () => {
|
||||
const v = make("<div>x|</div>\n<p>y</p>");
|
||||
for (let i = 0; i < "</div>".length; i++) deleteForward(v);
|
||||
expect(v.state.doc.toString()).toBe("<div>x\n<p>y</p>");
|
||||
});
|
||||
|
||||
it("leaves the closing tag alone while an opening tag followed by children is backspaced away", () => {
|
||||
const v = make("<div>|\n <span>y</span>\n</div>");
|
||||
for (let i = 0; i < "<div>".length; i++) backspace(v);
|
||||
expect(show(v)).toBe("|\n <span>y</span>\n</div>");
|
||||
const inline = make("<div>|<span>y</span></div>");
|
||||
for (let i = 0; i < "<div>".length; i++) backspace(inline);
|
||||
expect(show(inline)).toBe("|<span>y</span></div>");
|
||||
});
|
||||
|
||||
it("leaves the other tag alone when a selection covering a tag is deleted", () => {
|
||||
const v = make("<div>x[</div>]");
|
||||
backspace(v);
|
||||
expect(show(v)).toBe("<div>x|");
|
||||
const open = make("[<div>]x</div>");
|
||||
backspace(open);
|
||||
expect(show(open)).toBe("|x</div>");
|
||||
});
|
||||
|
||||
it("leaves the other tag alone when a cut runs from inside the name past the tag", () => {
|
||||
const v = make("<div>x</d[iv>\n]<p>y</p>");
|
||||
backspace(v);
|
||||
expect(v.state.doc.toString()).toBe("<div>x</d<p>y</p>");
|
||||
});
|
||||
|
||||
it("does not rename into or out of a tag that lost its `>`", () => {
|
||||
const v = make("<div|>x</div");
|
||||
type(v, "s");
|
||||
expect(v.state.doc.toString()).toBe("<divs>x</div");
|
||||
const open = make("<div\n x</di|v>");
|
||||
backspace(open);
|
||||
expect(open.state.doc.toString()).toBe("<div\n x</dv>");
|
||||
});
|
||||
|
||||
it("deletes the closing tags at every caret, leaving the opening tags alone", () => {
|
||||
const v = make("<p>a</p>|\n<b>c</b>|");
|
||||
for (let i = 0; i < "</p>".length; i++) backspace(v);
|
||||
expect(show(v)).toBe("<p>a|\n<b>c|");
|
||||
});
|
||||
|
||||
it("undo brings back the deleted closing tag and keeps the opening one", () => {
|
||||
const v = make("<div>x[</div>]", history());
|
||||
backspace(v);
|
||||
expect(v.state.doc.toString()).toBe("<div>x");
|
||||
expect(undo(v)).toBe(true);
|
||||
expect(v.state.doc.toString()).toBe("<div>x</div>");
|
||||
});
|
||||
|
||||
it("still renames after the `>` is typed back", () => {
|
||||
const v = make("<div>x</div|");
|
||||
type(v, ">");
|
||||
expect(v.state.doc.toString()).toBe("<div>x</div>");
|
||||
v.dispatch({ selection: { anchor: "<div".length } });
|
||||
type(v, "s");
|
||||
expect(v.state.doc.toString()).toBe("<divs>x</divs>");
|
||||
});
|
||||
});
|
||||
|
||||
it("undoes the pair as one step and redoes it", () => {
|
||||
const v = make("<div|></div>", history());
|
||||
type(v, "x");
|
||||
@@ -219,6 +309,12 @@ describe("linked html tags", () => {
|
||||
type(v, "s");
|
||||
expect(v.state.doc.toString()).toBe('<divs class="a">x</divs>');
|
||||
});
|
||||
|
||||
it(`leaves the opening tag alone while the closing tag is backspaced away in ${name}`, () => {
|
||||
const v = makeWith([language(), linkedTags], '<div class="a">x</div>|');
|
||||
for (let i = 0; i < "</div>".length; i++) backspace(v);
|
||||
expect(v.state.doc.toString()).toBe('<div class="a">x');
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
@@ -261,6 +357,18 @@ describe("linked html tags", () => {
|
||||
expect(f.state.doc.toString()).toBe("const a = <p>x</>;");
|
||||
});
|
||||
|
||||
it("leaves the other tag alone while a tag is backspaced away", () => {
|
||||
const v = tsx("const a = <div>x</div>|;");
|
||||
for (let i = 0; i < "</div>".length; i++) backspace(v);
|
||||
expect(v.state.doc.toString()).toBe("const a = <div>x;");
|
||||
const m = tsx("const a = (\n <div>|\n <span>y</span>\n </div>\n);");
|
||||
for (let i = 0; i < "<div>".length; i++) backspace(m);
|
||||
expect(m.state.doc.toString()).toBe("const a = (\n \n <span>y</span>\n </div>\n);");
|
||||
const w = tsx("const a = <Foo>|x</Foo>;");
|
||||
for (let i = 0; i < "<Foo>".length; i++) backspace(w);
|
||||
expect(w.state.doc.toString()).toBe("const a = x</Foo>;");
|
||||
});
|
||||
|
||||
it("undoes both tags in one step", () => {
|
||||
const v = tsx("const a = <div|></div>;");
|
||||
type(v, "x");
|
||||
|
||||
@@ -10,9 +10,9 @@
|
||||
* A transaction whose change lies inside one tag's name is extended with
|
||||
* the same edit at the same offset in the counterpart's name — one
|
||||
* transaction, so undo takes both back together. Without a matching tag (void
|
||||
* and self-closing tags, unclosed elements, a stray close tag) or with the two
|
||||
* names already different (malformed markup) nothing follows: the tags stay as
|
||||
* they are.
|
||||
* and self-closing tags, unclosed elements, a stray close tag), with either tag
|
||||
* missing its `>` (a tag being deleted piece by piece), or with the two names
|
||||
* already different (malformed markup) nothing follows: the tags stay as they are.
|
||||
*/
|
||||
import { EditorState, type Extension, type Transaction } from "@codemirror/state";
|
||||
import { syntaxTree } from "@codemirror/language";
|
||||
@@ -39,21 +39,31 @@ function tagNameAround(tree: Tree, from: number, to: number): SyntaxNode | null
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The matching tag's name of the same element, or null without one. */
|
||||
/**
|
||||
* Whether a tag still ends in its `>`. A tag that lost it — `</div` while Backspace
|
||||
* works through `</div>` — is being deleted, not renamed.
|
||||
*/
|
||||
function isComplete(tag: SyntaxNode | null): tag is SyntaxNode {
|
||||
const last = tag?.lastChild?.name;
|
||||
return last === "EndTag" || last === "JSXEndTag";
|
||||
}
|
||||
|
||||
/** The matching tag's name of the same element, or null without one or while either tag is incomplete. */
|
||||
function counterpartName(name: SyntaxNode): SyntaxNode | null {
|
||||
const tag = name.parent;
|
||||
const element = tag?.parent;
|
||||
if (!tag || !element) return null;
|
||||
if (!isComplete(tag) || !element) return null;
|
||||
if (element.name === "JSXElement") {
|
||||
const other = element.getChild(tag.name === "JSXOpenTag" ? "JSXCloseTag" : "JSXOpenTag");
|
||||
for (let c = other?.firstChild; c; c = c.nextSibling) if (JSX_NAMES.has(c.name)) return c;
|
||||
if (!isComplete(other)) return null;
|
||||
for (let c = other.firstChild; c; c = c.nextSibling) if (JSX_NAMES.has(c.name)) return c;
|
||||
return null;
|
||||
}
|
||||
if (element.name !== "Element") return null;
|
||||
const other = element.getChild(
|
||||
/^Open/.test(tag.name) ? tag.name.replace("Open", "Close") : tag.name.replace("Close", "Open"),
|
||||
);
|
||||
return other?.getChild("TagName") ?? null;
|
||||
return isComplete(other) ? other.getChild("TagName") : null;
|
||||
}
|
||||
|
||||
/** Insertions at a name's edge must extend the name; structural characters end it. */
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { StreamLanguage } from "@codemirror/language";
|
||||
import { javascript } from "@codemirror/lang-javascript";
|
||||
import { kotlin } from "@codemirror/legacy-modes/mode/clike";
|
||||
import { highlightTree } from "@lezer/highlight";
|
||||
import { lineLiteralAt, literalAt, literalsExtension } from "./literals";
|
||||
import { setSyntaxHighlights } from "./syntaxHighlight";
|
||||
|
||||
vi.mock("@lezer/highlight", async (importOriginal) => {
|
||||
const original = await importOriginal<typeof import("@lezer/highlight")>();
|
||||
return { ...original, highlightTree: vi.fn(original.highlightTree) };
|
||||
});
|
||||
|
||||
const highlighted = vi.mocked(highlightTree);
|
||||
beforeEach(() => {
|
||||
highlighted.mockClear();
|
||||
});
|
||||
|
||||
/** The `[from, to]` window of every `highlightTree` call since the last `beforeEach`. */
|
||||
const windows = () => highlighted.mock.calls.map(([tree, , , from = 0, to = tree.length]) => [from, to]);
|
||||
|
||||
const code = (lines: number) =>
|
||||
Array.from({ length: lines }, (_, i) => `const v${i} = "value ${i}"; // note ${i}\nlet n${i} = ${i};`).join("\n") +
|
||||
"\nconst text = `first\nsecond`;\n";
|
||||
|
||||
const typescript = () => [javascript({ typescript: true })];
|
||||
|
||||
describe("lineLiteralAt", () => {
|
||||
it("finds the string literal or comment at a position, as literalAt does", () => {
|
||||
const state = EditorState.create({ doc: code(20), extensions: typescript() });
|
||||
const at = (needle: string, shift = 0) => state.doc.toString().indexOf(needle) + shift;
|
||||
for (const [pos, kind] of [
|
||||
[at('"value 7"', 3), "string"],
|
||||
[at("// note 7", 4), "comment"],
|
||||
[at("const v7", 2), null],
|
||||
[at("n7 = 7", 4), null],
|
||||
] as const) {
|
||||
expect(lineLiteralAt(state, pos)?.kind ?? null).toBe(kind);
|
||||
expect(lineLiteralAt(state, pos)).toEqual(literalAt(state, pos));
|
||||
}
|
||||
});
|
||||
|
||||
it("returns a literal that goes on past the line cut at the line break", () => {
|
||||
const state = EditorState.create({ doc: code(3), extensions: typescript() });
|
||||
const doc = state.doc.toString();
|
||||
const open = doc.indexOf("`first");
|
||||
const lit = lineLiteralAt(state, open + 2)!;
|
||||
expect(lit.kind).toBe("string");
|
||||
expect(lit.from).toBe(open);
|
||||
expect(state.doc.lineAt(lit.to).number).not.toBe(state.doc.lineAt(lit.from).number);
|
||||
const second = doc.indexOf("second");
|
||||
const rest = lineLiteralAt(state, second + 2)!;
|
||||
expect(state.doc.lineAt(rest.from).number).not.toBe(state.doc.lineAt(rest.to).number);
|
||||
});
|
||||
|
||||
it("highlights the line and its line breaks, not the document", () => {
|
||||
// `literalAt` asks for the whole document: a rebuilt scan of every line for each Enter typed.
|
||||
const sizes = [200, 4000].map((lines) => {
|
||||
const state = EditorState.create({ doc: code(lines), extensions: typescript() });
|
||||
const pos = state.doc.toString().indexOf('"value 150"') + 3;
|
||||
const line = state.doc.lineAt(pos);
|
||||
highlighted.mockClear();
|
||||
expect(lineLiteralAt(state, pos)?.kind).toBe("string");
|
||||
const covered = windows().map(([from, to]) => to! - from!);
|
||||
expect(Math.max(...covered)).toBeLessThanOrEqual(line.length + 2);
|
||||
return covered.length;
|
||||
});
|
||||
expect(sizes[1]).toBe(sizes[0]);
|
||||
});
|
||||
|
||||
it("finds literals of languages with a stream parser", () => {
|
||||
const doc = 'val a = 1\nval s = "hi there" // done\n';
|
||||
const state = EditorState.create({ doc, extensions: [StreamLanguage.define(kotlin)] });
|
||||
expect(lineLiteralAt(state, doc.indexOf("hi") + 1)).toEqual({
|
||||
from: doc.indexOf('"hi'),
|
||||
to: doc.indexOf(" //"),
|
||||
kind: "string",
|
||||
});
|
||||
expect(lineLiteralAt(state, doc.indexOf("done"))?.kind).toBe("comment");
|
||||
expect(lineLiteralAt(state, doc.indexOf("val a"))).toBeNull();
|
||||
});
|
||||
|
||||
it("falls back to the highlights of the backend for languages without a parser", () => {
|
||||
const doc = "plain\nx = 'quoted'\n";
|
||||
const state = EditorState.create({ doc, extensions: [literalsExtension] }).update({
|
||||
effects: setSyntaxHighlights.of({ kinds: ["string"], data: [doc.indexOf("'q"), doc.indexOf("'\n") + 1, 0] }),
|
||||
}).state;
|
||||
expect(lineLiteralAt(state, doc.indexOf("quoted"))).toEqual({
|
||||
from: doc.indexOf("'q"),
|
||||
to: doc.indexOf("'\n") + 1,
|
||||
kind: "string",
|
||||
});
|
||||
expect(lineLiteralAt(state, 2)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -6,6 +6,7 @@
|
||||
*/
|
||||
import { StateField, type EditorState } from "@codemirror/state";
|
||||
import { ensureSyntaxTree, syntaxTree } from "@codemirror/language";
|
||||
import type { Tree } from "@lezer/common";
|
||||
import { highlightTree, tagHighlighter, tags as t } from "@lezer/highlight";
|
||||
import type { SyntaxHighlightKind } from "@/platform/ipc";
|
||||
import type { LiteralKind } from "@/platform/search";
|
||||
@@ -64,17 +65,29 @@ const cache = new WeakMap<object, readonly LiteralRange[]>();
|
||||
/** How long counting may wait for the parser to reach the end of the document. */
|
||||
const PARSE_BUDGET_MS = 50;
|
||||
|
||||
/** Comments and string literals of `tree` between `from` and `to`; a literal reaching past either end is cut there. */
|
||||
function highlightedLiterals(tree: Tree, from: number, to: number): LiteralRange[] {
|
||||
const out: LiteralRange[] = [];
|
||||
highlightTree(
|
||||
tree,
|
||||
highlighter,
|
||||
(start, end, cls) => {
|
||||
const kind: LiteralKind | null = cls.includes("comment") ? "comment" : cls.includes("string") ? "string" : null;
|
||||
if (kind) push(out, start, end, kind);
|
||||
},
|
||||
from,
|
||||
to,
|
||||
);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Comments and string literals of `state` (cached per syntax tree). */
|
||||
export function literalRanges(state: EditorState): readonly LiteralRange[] {
|
||||
const tree = ensureSyntaxTree(state, state.doc.length, PARSE_BUDGET_MS) ?? syntaxTree(state);
|
||||
if (tree.length === 0) return state.field(treeSitterLiterals, false) ?? [];
|
||||
const hit = cache.get(tree);
|
||||
if (hit) return hit;
|
||||
const out: LiteralRange[] = [];
|
||||
highlightTree(tree, highlighter, (from, to, cls) => {
|
||||
const kind: LiteralKind | null = cls.includes("comment") ? "comment" : cls.includes("string") ? "string" : null;
|
||||
if (kind) push(out, from, to, kind);
|
||||
});
|
||||
const out = highlightedLiterals(tree, 0, tree.length);
|
||||
cache.set(tree, out);
|
||||
return out;
|
||||
}
|
||||
@@ -86,7 +99,22 @@ export function literalKindAt(state: EditorState, pos: number): LiteralKind | nu
|
||||
|
||||
/** The comment or string literal `pos` lies in, if any. */
|
||||
export function literalAt(state: EditorState, pos: number): LiteralRange | null {
|
||||
const ranges = literalRanges(state);
|
||||
return rangeAt(literalRanges(state), pos);
|
||||
}
|
||||
|
||||
/**
|
||||
* Like `literalAt`, for a caller that only wants literals within one line: it parses and highlights
|
||||
* the line of `pos` and the line breaks around it, not the document. A literal that goes on past
|
||||
* the line comes back cut at the line break, so it still reaches into another line.
|
||||
*/
|
||||
export function lineLiteralAt(state: EditorState, pos: number): LiteralRange | null {
|
||||
const line = state.doc.lineAt(pos);
|
||||
const tree = ensureSyntaxTree(state, line.to, PARSE_BUDGET_MS) ?? syntaxTree(state);
|
||||
if (tree.length === 0) return literalAt(state, pos);
|
||||
return rangeAt(highlightedLiterals(tree, Math.max(0, line.from - 1), Math.min(tree.length, line.to + 1)), pos);
|
||||
}
|
||||
|
||||
function rangeAt(ranges: readonly LiteralRange[], pos: number): LiteralRange | null {
|
||||
let lo = 0;
|
||||
let hi = ranges.length - 1;
|
||||
while (lo <= hi) {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { EditorSelection, EditorState, Prec, type Extension } from "@codemirror/state";
|
||||
import { Decoration, EditorView } from "@codemirror/view";
|
||||
import { inlineBackground, inlineFramedFallback, inlineFramedModern } from "./inlineBg";
|
||||
import { selectionMarks } from "./selectionMarks";
|
||||
|
||||
const views: EditorView[] = [];
|
||||
@@ -54,4 +55,22 @@ describe("selectionMarks", () => {
|
||||
v.dispatch({ selection: EditorSelection.cursor(3) });
|
||||
expect(v.contentDOM.querySelector(".cm-openidea-selected")).toBeNull();
|
||||
});
|
||||
|
||||
it("caps inline highlight backgrounds and 1px frames at 1lh with pre-16.4 fallbacks", () => {
|
||||
expect(inlineBackground("var(--editor-search)")).toEqual({
|
||||
backgroundColor: "var(--editor-search)",
|
||||
background: "linear-gradient(var(--editor-search), var(--editor-search)) center / 100% 1lh no-repeat",
|
||||
WebkitBoxDecorationBreak: "clone",
|
||||
boxDecorationBreak: "clone",
|
||||
});
|
||||
expect(inlineFramedFallback("var(--fill)", "var(--frame)")).toMatchObject({
|
||||
backgroundColor: "var(--fill)",
|
||||
outline: "1px solid var(--frame)",
|
||||
outlineOffset: "-1px",
|
||||
});
|
||||
const modern = inlineFramedModern("var(--fill)", "var(--frame)");
|
||||
expect(modern.outline).toBe("none");
|
||||
expect(modern.background).toContain("100% min(100%, 1lh)");
|
||||
expect(modern.background).toContain("calc(100% - 2px) calc(min(100%, 1lh) - 2px)");
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Prec, RangeSetBuilder, type Extension } from "@codemirror/state";
|
||||
import { Decoration, EditorView, ViewPlugin, type DecorationSet, type ViewUpdate } from "@codemirror/view";
|
||||
import { inlineBackground } from "./inlineBg";
|
||||
|
||||
/**
|
||||
* `drawSelection` paints the selection in a layer behind the text, so any mark with its own
|
||||
@@ -38,12 +39,7 @@ const plugin = ViewPlugin.fromClass(
|
||||
const theme = EditorView.baseTheme({
|
||||
".cm-openidea-selected": {
|
||||
"--openidea-selected-bg": "var(--editor-selection-inactive, var(--bg-editor-selection-inactive))",
|
||||
// Capped at `1lh` so a font taller than the line height does not bleed into the rows above and below.
|
||||
// Safari before 16.4 has no `lh` and drops the shorthand, keeping the plain colour before it.
|
||||
backgroundColor: "var(--openidea-selected-bg)",
|
||||
background: "linear-gradient(var(--openidea-selected-bg), var(--openidea-selected-bg)) center / 100% 1lh no-repeat",
|
||||
WebkitBoxDecorationBreak: "clone",
|
||||
boxDecorationBreak: "clone",
|
||||
...inlineBackground("var(--openidea-selected-bg)"),
|
||||
// Unset (the default `inherit`): the declaration drops and the syntax colours show through.
|
||||
color: "var(--fg-editor-selection)",
|
||||
WebkitTextFillColor: "var(--fg-editor-selection)",
|
||||
@@ -51,6 +47,12 @@ const theme = EditorView.baseTheme({
|
||||
"&.cm-focused .cm-openidea-selected": {
|
||||
"--openidea-selected-bg": "var(--editor-selection, var(--bg-editor-selection))",
|
||||
},
|
||||
// Leave the 1px frame painted by `inlineFramedModern` visible around selected text inside it.
|
||||
"@supports (height: 1lh)": {
|
||||
":is(.cm-openidea-findMatch-current, .cm-lsp-inplace-primary) .cm-openidea-selected": {
|
||||
backgroundSize: "calc(100% - 2px) calc(min(100%, 1lh) - 2px)",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
export const selectionMarks: Extension = [Prec.highest(plugin), theme];
|
||||
@@ -101,6 +101,14 @@ describe("Enter in a string literal", () => {
|
||||
expect(enter("char c = 'a|';", "java", java())).toBeNull();
|
||||
});
|
||||
|
||||
it("splits a string of a language without a Lezer string node, and not a multi-line one", () => {
|
||||
const kt = StreamLanguage.define(interpolationParser(kotlin, "Kotlin"));
|
||||
expect(enter('fun f() {\n val t = "hello|world"\n}', "kotlin", kt)).toBe(
|
||||
'fun f() {\n val t = "hello" +\n "|world"\n}',
|
||||
);
|
||||
expect(enter('val t = """\n a|b\n """', "kotlin", kt)).toBeNull();
|
||||
});
|
||||
|
||||
it("splits after an escaped backslash", () => {
|
||||
expect(enter('String t = "a\\\\|b";', "java", java())).toBe('String t = "a\\\\" +\n "|b";');
|
||||
});
|
||||
|
||||
@@ -23,7 +23,7 @@ import {
|
||||
import type { SyntaxNode } from "@lezer/common";
|
||||
import { indentMore } from "@codemirror/commands";
|
||||
import { visibleColumn } from "./visibleColumn";
|
||||
import { literalAt } from "./literals";
|
||||
import { lineLiteralAt, literalAt } from "./literals";
|
||||
import { SEMICOLON_LANGS, codeEnd, lineCommentToken } from "./editing";
|
||||
|
||||
// --- Tab -------------------------------------------------------------------------------
|
||||
@@ -552,7 +552,7 @@ const PLUS_CONCAT_LANGS = new Set([
|
||||
function stringLiteralAt(state: EditorState, pos: number): { from: number; to: number } | null {
|
||||
for (let n: SyntaxNode | null = syntaxTree(state).resolveInner(pos, -1); n; n = n.parent)
|
||||
if (/^(StringLiteral|String)$/.test(n.name)) return { from: n.from, to: n.to };
|
||||
const lit = literalAt(state, pos);
|
||||
const lit = lineLiteralAt(state, pos);
|
||||
return lit?.kind === "string" ? lit : null;
|
||||
}
|
||||
|
||||
|
||||
+16
-13
@@ -9,6 +9,7 @@ import { EditorView } from "@codemirror/view";
|
||||
import { BRACKET_COLORS } from "./rainbowBrackets";
|
||||
import { LINE_INSET } from "./lineInset";
|
||||
import { GUIDE_COLORS } from "./indentGuides";
|
||||
import { inlineBackground, inlineFramedFallback, inlineFramedModern } from "./inlineBg";
|
||||
|
||||
/** How much of its palette colour a rainbow indent guide takes. */
|
||||
const RAINBOW_GUIDE_STRENGTH = "55%";
|
||||
@@ -19,10 +20,12 @@ export const findLocals = {
|
||||
"--editor-search-current": "var(--bg-search-match-current, color-mix(in srgb, var(--warning) 48%, transparent))",
|
||||
};
|
||||
|
||||
const FIND_CURRENT_FRAME = "color-mix(in srgb, var(--editor-search-current) 60%, var(--fg-strong))";
|
||||
|
||||
/** Find in file highlights (cm/find.ts), also for viewers with their own theme (diff). */
|
||||
export const findStyles = {
|
||||
".cm-openidea-findMatch": {
|
||||
backgroundColor: "var(--editor-search)",
|
||||
...inlineBackground("var(--editor-search)"),
|
||||
color: "var(--fg-search-match, inherit)",
|
||||
// Its own colour, over the text fill of an identifier highlight around the match.
|
||||
WebkitTextFillColor: "currentcolor",
|
||||
@@ -32,13 +35,13 @@ export const findStyles = {
|
||||
textDecoration: "line-through",
|
||||
textDecorationColor: "var(--fg-muted)",
|
||||
},
|
||||
".cm-openidea-findScope": {
|
||||
backgroundColor: "var(--editor-selection-inactive, var(--bg-editor-selection-inactive))",
|
||||
},
|
||||
".cm-openidea-findScope": inlineBackground("var(--editor-selection-inactive, var(--bg-editor-selection-inactive))"),
|
||||
".cm-openidea-findMatch-current": {
|
||||
backgroundColor: "var(--editor-search-current)",
|
||||
...inlineFramedFallback("var(--editor-search-current)", FIND_CURRENT_FRAME),
|
||||
color: "var(--fg-search-match, inherit)",
|
||||
outline: "1px solid color-mix(in srgb, var(--editor-search-current) 60%, var(--fg-strong))",
|
||||
},
|
||||
"@supports (height: 1lh)": {
|
||||
".cm-openidea-findMatch-current": inlineFramedModern("var(--editor-search-current)", FIND_CURRENT_FRAME),
|
||||
},
|
||||
};
|
||||
|
||||
@@ -222,25 +225,25 @@ export const openideaTheme = EditorView.theme({
|
||||
background: "var(--openidea-line-bg)",
|
||||
pointerEvents: "none",
|
||||
},
|
||||
".cm-selectionMatch": {
|
||||
backgroundColor: "var(--bg-identifier-under-caret, color-mix(in srgb, var(--fg) 9%, transparent))",
|
||||
},
|
||||
".cm-selectionMatch": inlineBackground(
|
||||
"var(--bg-identifier-under-caret, color-mix(in srgb, var(--fg) 9%, transparent))",
|
||||
),
|
||||
// IDEA paints these with IDENTIFIER_UNDER_CARET_ATTRIBUTES, except the selection itself.
|
||||
".cm-selectionMatch:not(.cm-selectionMatch-main)": { WebkitTextFillColor: "var(--fg-identifier-under-caret)" },
|
||||
// IDEA's MATCHED_BRACE_ATTRIBUTES (bold in dark schemes only) and MATCHED_TAG_NAME (never bold).
|
||||
".cm-matchingBracket, &.cm-focused .cm-matchingBracket": {
|
||||
backgroundColor: "var(--editor-brace)",
|
||||
...inlineBackground("var(--editor-brace)"),
|
||||
color: "inherit",
|
||||
fontWeight: "var(--matched-brace-weight, var(--fw-code-bold, 700))",
|
||||
borderRadius: "1px",
|
||||
},
|
||||
".cm-matchingTag, &.cm-focused .cm-matchingTag": {
|
||||
backgroundColor: "var(--bg-matched-tag, var(--editor-brace))",
|
||||
...inlineBackground("var(--bg-matched-tag, var(--editor-brace))"),
|
||||
fontWeight: "inherit",
|
||||
},
|
||||
".cm-nonmatchingBracket, &.cm-focused .cm-nonmatchingBracket": {
|
||||
color: "var(--danger)",
|
||||
backgroundColor: "color-mix(in srgb, var(--danger) 14%, transparent)",
|
||||
...inlineBackground("color-mix(in srgb, var(--danger) 14%, transparent)"),
|
||||
},
|
||||
".cm-specialChar": { color: "var(--danger)" },
|
||||
|
||||
@@ -363,7 +366,7 @@ export const openideaTheme = EditorView.theme({
|
||||
...findStyles,
|
||||
...markWidgetStyles,
|
||||
// Find in Files preview matches (search/find/parts.tsx)
|
||||
".cm-openidea-searchResult": { backgroundColor: "var(--bg-search-result)" },
|
||||
".cm-openidea-searchResult": inlineBackground("var(--bg-search-result)"),
|
||||
|
||||
// Overlays
|
||||
".cm-tooltip": {
|
||||
|
||||
@@ -8,6 +8,7 @@ import { resetDistractionFree, setDistractionFree } from "@/workbench/distractio
|
||||
import * as contributions from "@/workbench/contributions";
|
||||
import {
|
||||
registerEditorKind,
|
||||
registerMenuGroup,
|
||||
registerTextEditorWrapper,
|
||||
setProjectViewLead,
|
||||
useProjectViewLead,
|
||||
@@ -579,6 +580,46 @@ describe("EditorController", () => {
|
||||
useProject.setState({ project: null, settings: null });
|
||||
});
|
||||
|
||||
it("offers contributed Copy Path links in the tab menu like the other copy menus", async () => {
|
||||
useProject.setState({
|
||||
project: { name: "p", root: "/p", trusted: true, isGit: true, settings: {} } as never,
|
||||
settings: {} as never,
|
||||
});
|
||||
const dispose = registerActions(
|
||||
["project.copyAbsolutePath", "project.copyFileName", "project.copyRelativePath"].map((id) => ({
|
||||
id,
|
||||
title: id,
|
||||
run: () => undefined,
|
||||
})),
|
||||
);
|
||||
const links = registerMenuGroup({
|
||||
id: "test.link",
|
||||
menus: ["copyPath"],
|
||||
items: () => [{ id: "test.copyLink", label: "GitHub Link", verbatim: true, run: () => undefined }],
|
||||
});
|
||||
try {
|
||||
ctrl = new EditorController(createMemoryBackend({ "/p/a.ts": "" }));
|
||||
ctrl.start();
|
||||
await ctrl.openFile("/p/a.ts", { focus: false });
|
||||
const s = useTabs.getState();
|
||||
const pane = s.panes[s.activePane]!;
|
||||
const submenu = resolveMenuItems(ctrl.tabMenu(pane.id, pane.tabs[0]!)).find(
|
||||
(i) => i.label === "Copy Path/Reference…",
|
||||
)!.submenu!;
|
||||
expect(resolveMenuItems(submenu).map((i) => (i.kind === "separator" ? "-" : i.label))).toEqual([
|
||||
"Absolute Path",
|
||||
"File Name",
|
||||
"Path From Content Root",
|
||||
"-",
|
||||
"GitHub Link",
|
||||
]);
|
||||
} finally {
|
||||
dispose();
|
||||
links();
|
||||
useProject.setState({ project: null, settings: null });
|
||||
}
|
||||
});
|
||||
|
||||
it.each(["editor", "tab"])(
|
||||
"offers grouped Git actions in the %s menu and preserves action enablement",
|
||||
async (menu) => {
|
||||
|
||||
@@ -2324,6 +2324,9 @@ export class EditorController implements SlotHost {
|
||||
},
|
||||
] as MenuItem[])
|
||||
: []),
|
||||
// The links the project view and the editor chooser offer (features/vcs: GitHub Link).
|
||||
{ kind: "separator" },
|
||||
...menuGroupItems("copyPath", { paths: [path] }),
|
||||
],
|
||||
},
|
||||
{ kind: "separator" },
|
||||
|
||||
@@ -64,6 +64,11 @@
|
||||
content-visibility: hidden;
|
||||
z-index: -1;
|
||||
}
|
||||
/* WebKit leaves a stale selection highlight on a subtree whose rendering was skipped when the selection cleared. */
|
||||
.keptHidden[data-selection] {
|
||||
content-visibility: visible;
|
||||
opacity: 0;
|
||||
}
|
||||
.host {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
|
||||
@@ -6,7 +6,16 @@ import { useFilePresentations } from "@/ui/filePresentation";
|
||||
* decorations, middle-click close, Alt+click close others, double-click to
|
||||
* keep a preview / maximize the editor, context menu) and the active editor.
|
||||
*/
|
||||
import { Fragment, useEffect, useMemo, useRef, useState, type FocusEvent, type ReactNode } from "react";
|
||||
import {
|
||||
Fragment,
|
||||
useEffect,
|
||||
useLayoutEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type FocusEvent,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import clsx from "clsx";
|
||||
import { useShallow } from "zustand/react/shallow";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
@@ -46,6 +55,7 @@ import {
|
||||
Tabs,
|
||||
showContextMenu,
|
||||
registerDropTarget,
|
||||
useSelectionVisibility,
|
||||
FILES_DRAG,
|
||||
type TabItem,
|
||||
type TabsDnd,
|
||||
@@ -497,7 +507,13 @@ function PaneContent({ paneId, tab, tabsVisible }: { paneId: string; tab: Tab; t
|
||||
)}
|
||||
<FindBar paneId={paneId} />
|
||||
{crumbs && (
|
||||
<PaneBreadcrumbs key={wrapper?.id} wrapper={wrapper} path={tab.input.path!} tabId={tab.id} position="top" />
|
||||
<PaneBreadcrumbs
|
||||
key={`top:${wrapper?.id}`}
|
||||
wrapper={wrapper}
|
||||
path={tab.input.path!}
|
||||
tabId={tab.id}
|
||||
position="top"
|
||||
/>
|
||||
)}
|
||||
{wrapper ? (
|
||||
<wrapper.component
|
||||
@@ -513,7 +529,7 @@ function PaneContent({ paneId, tab, tabsVisible }: { paneId: string; tab: Tab; t
|
||||
)}
|
||||
{crumbs && (
|
||||
<PaneBreadcrumbs
|
||||
key={wrapper?.id}
|
||||
key={`bottom:${wrapper?.id}`}
|
||||
wrapper={wrapper}
|
||||
path={tab.input.path!}
|
||||
tabId={tab.id}
|
||||
@@ -544,12 +560,24 @@ function keptTabs(tabs: Tab[], mru: string[], kinds: Map<string, EditorKindContr
|
||||
* its content can't be focused or hit while skipped.
|
||||
*/
|
||||
function KindEditor({ tab, shown, kept = false }: { tab: Tab; shown: boolean; kept?: boolean }) {
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
useSelectionVisibility(ref, kept);
|
||||
useLayoutEffect(() => {
|
||||
const el = ref.current;
|
||||
if (!kept || shown || !el) return;
|
||||
const sel = el.ownerDocument.getSelection();
|
||||
if (sel && !sel.isCollapsed && sel.rangeCount > 0 && sel.getRangeAt(0).intersectsNode(el)) {
|
||||
el.setAttribute("data-selection", "");
|
||||
sel.removeAllRanges();
|
||||
}
|
||||
}, [kept, shown]);
|
||||
const kinds = useContributions((s) => s.editorKinds);
|
||||
const kind = kinds.get(tab.input.kind);
|
||||
if (!kind) return <EmptyState icon="file" title={tx`No editor for “${tab.input.kind}”`} />;
|
||||
const Component = kind.component;
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
className={clsx(styles.kind, kept && styles.kept, !shown && styles.keptHidden)}
|
||||
data-editor-focus={shown ? "" : undefined}
|
||||
tabIndex={-1}
|
||||
|
||||
@@ -640,6 +640,7 @@ export function FindPanel({ target, version, replace, seq, onReplaceShown, onClo
|
||||
aria-label="Find"
|
||||
invalid={invalid || none}
|
||||
multiline
|
||||
maxRows={3}
|
||||
onHistory={() => setHistoryMenu("find")}
|
||||
onKeyDown={(e) => onKeyDown(e, "find")}
|
||||
className={styles.findInput}
|
||||
@@ -710,6 +711,7 @@ export function FindPanel({ target, version, replace, seq, onReplaceShown, onClo
|
||||
placeholder="Replace"
|
||||
aria-label="Replace"
|
||||
multiline
|
||||
maxRows={3}
|
||||
onHistory={() => setHistoryMenu("replace")}
|
||||
onKeyDown={(e) => onKeyDown(e, "replace")}
|
||||
toggles={[
|
||||
|
||||
@@ -95,4 +95,43 @@ describe("keep-alive editor kinds", () => {
|
||||
expect(shown("k2")).toBe(false);
|
||||
expect(shown("k6")).toBe(true);
|
||||
});
|
||||
|
||||
it("clears a kept tab's selection on hide while keeping data-selection for one frame so WebKit clears the highlight", () => {
|
||||
const frames: FrameRequestCallback[] = [];
|
||||
const raf = vi.spyOn(window, "requestAnimationFrame").mockImplementation((cb) => frames.push(cb));
|
||||
const caf = vi.spyOn(window, "cancelAnimationFrame").mockImplementation(() => {
|
||||
frames.length = 0;
|
||||
});
|
||||
try {
|
||||
const tabs = [tab("a", "kept"), tab("b", "plain")];
|
||||
show(tabs, "a");
|
||||
render(<EditorAreaView />);
|
||||
const node = screen.getByTestId("a").firstChild!;
|
||||
const wrapper = screen.getByTestId("a").parentElement!;
|
||||
const sel = window.getSelection()!;
|
||||
sel.setBaseAndExtent(node, 0, node, 1);
|
||||
act(() => {
|
||||
document.dispatchEvent(new Event("selectionchange"));
|
||||
});
|
||||
expect(wrapper).toHaveAttribute("data-selection");
|
||||
|
||||
show(tabs, "b");
|
||||
expect(shown("a")).toBe(false);
|
||||
expect(sel.rangeCount).toBe(0);
|
||||
expect(wrapper).toHaveAttribute("data-selection");
|
||||
|
||||
act(() => {
|
||||
document.dispatchEvent(new Event("selectionchange"));
|
||||
});
|
||||
expect(wrapper).toHaveAttribute("data-selection");
|
||||
act(() => frames.shift()?.(performance.now()));
|
||||
expect(wrapper).toHaveAttribute("data-selection");
|
||||
act(() => frames.shift()?.(performance.now()));
|
||||
expect(wrapper).not.toHaveAttribute("data-selection");
|
||||
} finally {
|
||||
raf.mockRestore();
|
||||
caf.mockRestore();
|
||||
window.getSelection()?.removeAllRanges();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -297,6 +297,23 @@ describe("applying completions", () => {
|
||||
await vi.waitFor(() => expect(view.state.selection.main.head).toBe(17));
|
||||
});
|
||||
|
||||
it("edits repeated LSP placeholders from one selection", () => {
|
||||
const { view, req } = setup("lo|", "", [EditorState.allowMultipleSelections.of(true)]);
|
||||
const completion = makeCompletion(
|
||||
item({ kind: "snippet", insertText: "log(${1:value}, $1, ${2:label})$0", isSnippet: true }),
|
||||
req,
|
||||
);
|
||||
apply(view, completion, 0);
|
||||
expect(view.state.selection.ranges).toHaveLength(1);
|
||||
expect(view.state.doc.toString()).toBe("log(value, value, label)");
|
||||
view.dispatch(view.state.replaceSelection("name"));
|
||||
expect(view.state.doc.toString()).toBe("log(name, name, label)");
|
||||
expect(runScopeHandlers(view, new KeyboardEvent("keydown", { key: "Enter" }), "editor")).toBe(false);
|
||||
expect(runScopeHandlers(view, new KeyboardEvent("keydown", { key: "Tab" }), "editor")).toBe(true);
|
||||
const { from, to } = view.state.selection.main;
|
||||
expect(view.state.sliceDoc(from, to)).toBe("label");
|
||||
});
|
||||
|
||||
it("leaves an item its server inserts to the server, and puts the caret after what it inserted", async () => {
|
||||
const executed: string[] = [];
|
||||
setInvokeRoute((cmd) => {
|
||||
|
||||
@@ -16,7 +16,6 @@ import {
|
||||
moveCompletionSelection,
|
||||
pickedCompletion,
|
||||
selectedCompletion,
|
||||
snippet,
|
||||
startCompletion,
|
||||
type Completion,
|
||||
type CompletionContext,
|
||||
@@ -53,6 +52,7 @@ import {
|
||||
typeColumnText,
|
||||
withoutDuplicates,
|
||||
} from "./completionItems";
|
||||
import { applySnippet } from "@/editor/core/cm/linkedSnippet";
|
||||
import { lspSnippetToCm, lspSnippetToPlainWithCaret, snippetVariables } from "./snippet";
|
||||
import { docOf, isUnavailable, lspDoc, lspRequest, reportLspError } from "./lsp";
|
||||
import { offsetToPos, posToOffset, textEditsToChanges } from "./positions";
|
||||
@@ -296,7 +296,8 @@ export function applyLspCompletion(
|
||||
start = tr.changes.mapPos(start, 1);
|
||||
end = tr.changes.mapPos(end, 1);
|
||||
}
|
||||
snippet(lspSnippetToCm(item.insertText, snippetVariables(req.path)))(view, completion, start, end);
|
||||
const source = lspSnippetToCm(item.insertText, snippetVariables(req.path));
|
||||
applySnippet(view, [{ from: start, to: end, snippet: source }], completion);
|
||||
// A call snippet without a stop (`ArrayList<>()`): the caret goes inside until
|
||||
// signature help says there is nothing to pass.
|
||||
const head = view.state.selection.main.head;
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { Text } from "@codemirror/state";
|
||||
import { javascriptLanguage, typescriptLanguage } from "@codemirror/lang-javascript";
|
||||
import { TreeFragment, type Tree } from "@lezer/common";
|
||||
import { semanticRanges } from "../index";
|
||||
import { decoratorRanges } from "./index";
|
||||
|
||||
// tsserver's legend (vtsls and typescript-language-server send the same one).
|
||||
const tokenTypes = ["class", "variable", "function", "member", "property"];
|
||||
@@ -85,3 +87,64 @@ describe("JavaScript and TypeScript semantic tokens (#4059)", () => {
|
||||
expect(at(1, "parseInt")).toBe("cm-sem-function cm-sem-builtin");
|
||||
});
|
||||
});
|
||||
|
||||
describe("decorator names after an edit", () => {
|
||||
const parser = typescriptLanguage.parser;
|
||||
const decorated = "@Component({ selector: 'a' })\nexport class Home {\n @Input() title = ''\n}\n\n";
|
||||
const plain = (count: number) =>
|
||||
Array.from(
|
||||
{ length: count },
|
||||
(_, i) =>
|
||||
`/** Service ${i}, documented. */\nexport class Service${i} {\n load(id: number) {\n return id\n }\n}\n\n`,
|
||||
).join("");
|
||||
|
||||
/** The decorator names by walking the whole tree: what each edit used to cost. */
|
||||
function everyDecorator(tree: Tree): Array<[number, number]> {
|
||||
const out: Array<[number, number]> = [];
|
||||
tree.iterate({
|
||||
enter(ref) {
|
||||
if (ref.name !== "Decorator") return;
|
||||
let head = ref.node.firstChild?.nextSibling ?? null;
|
||||
while (head) {
|
||||
if (head.name === "CallExpression") head = head.firstChild;
|
||||
else if (head.name === "MemberExpression") {
|
||||
if (head.lastChild?.name === "PropertyName") out.push([head.lastChild.from, head.lastChild.to]);
|
||||
head = head.firstChild;
|
||||
} else {
|
||||
if (head.name === "VariableName") out.push([head.from, head.to]);
|
||||
head = null;
|
||||
}
|
||||
}
|
||||
},
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Scans the tree of a file that is `count` services after its decorated classes, then the tree of the same file after one typed letter. */
|
||||
function scanAfterTyping(count: number) {
|
||||
const doc = decorated + plain(count) + decorated;
|
||||
const tree = parser.parse(doc);
|
||||
decoratorRanges(tree);
|
||||
const at = doc.indexOf("return", doc.length >> 1);
|
||||
const fragments = TreeFragment.applyChanges(TreeFragment.addTree(tree), [
|
||||
{ fromA: at, toA: at, fromB: at, toB: at + 1 },
|
||||
]);
|
||||
const edited = parser.parse(doc.slice(0, at) + "a" + doc.slice(at), fragments);
|
||||
const probe = { visited: 0 };
|
||||
const ranges = decoratorRanges(edited, probe);
|
||||
return { edited, ranges, visited: probe.visited };
|
||||
}
|
||||
|
||||
it("finds the decorators of the whole file", () => {
|
||||
const { edited, ranges } = scanAfterTyping(50);
|
||||
expect(ranges.map((r) => [r.from, r.to])).toEqual(everyDecorator(edited));
|
||||
expect(ranges).toHaveLength(4);
|
||||
});
|
||||
|
||||
it("looks at as many tree nodes in a long file as in a short one", () => {
|
||||
// The nodes an edit leaves alone were already known to hold no decorator.
|
||||
const short = scanAfterTyping(100).visited;
|
||||
const long = scanAfterTyping(1600).visited;
|
||||
expect(long).toBeLessThan(short * 2);
|
||||
});
|
||||
});
|
||||
@@ -4,32 +4,71 @@
|
||||
* function the server reports; a variable or function without tsserver's `local`
|
||||
* modifier is a module-level global.
|
||||
*/
|
||||
import type { Tree } from "@lezer/common";
|
||||
import { Tree, TreeBuffer, type NodeSet, type SyntaxNode } from "@lezer/common";
|
||||
import { registerLanguageSemantics, type LanguageSemantics, type SemanticRange } from "../languages";
|
||||
|
||||
/** The names of decorators, left of their arguments: `@A`, `@a.B`, `@A()`, `@a.B<T>()`. */
|
||||
export function decoratorRanges(tree: Tree): SemanticRange[] {
|
||||
const decoratorTypes = new WeakMap<NodeSet, number>();
|
||||
|
||||
function decoratorType(set: NodeSet): number {
|
||||
let id = decoratorTypes.get(set);
|
||||
if (id === undefined) decoratorTypes.set(set, (id = set.types.find((t) => t.name === "Decorator")?.id ?? -1));
|
||||
return id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Subtrees without a decorator. An incremental parse keeps most of the old tree's nodes as they are,
|
||||
* so after an edit only the nodes on the changed path are scanned again, not the whole file.
|
||||
*/
|
||||
const decoratorFree = new WeakSet<Tree | TreeBuffer>();
|
||||
|
||||
/** Appends the start of every `Decorator` node in `node` (which starts at `offset`) to `out`. */
|
||||
function findDecorators(node: Tree | TreeBuffer, offset: number, out: number[], probe?: { visited: number }): void {
|
||||
if (decoratorFree.has(node)) return;
|
||||
if (probe) probe.visited++;
|
||||
const before = out.length;
|
||||
if (node instanceof Tree) {
|
||||
if (node.type.name === "Decorator") out.push(offset);
|
||||
for (let i = 0; i < node.children.length; i++)
|
||||
findDecorators(node.children[i]!, offset + node.positions[i]!, out, probe);
|
||||
} else {
|
||||
// [type, from, to, end of children] per node; `from` is relative to the buffer.
|
||||
const type = decoratorType(node.set);
|
||||
if (type >= 0)
|
||||
for (let i = 0; i < node.buffer.length; i += 4)
|
||||
if (node.buffer[i] === type) out.push(offset + node.buffer[i + 1]!);
|
||||
}
|
||||
if (out.length === before) decoratorFree.add(node);
|
||||
}
|
||||
|
||||
/**
|
||||
* The names of decorators, left of their arguments: `@A`, `@a.B`, `@A()`, `@a.B<T>()`.
|
||||
* `probe` counts the tree nodes looked at (tests).
|
||||
*/
|
||||
export function decoratorRanges(tree: Tree, probe?: { visited: number }): SemanticRange[] {
|
||||
const starts: number[] = [];
|
||||
findDecorators(tree, 0, starts, probe);
|
||||
const out: SemanticRange[] = [];
|
||||
tree.iterate({
|
||||
enter(ref) {
|
||||
if (ref.name !== "Decorator") return;
|
||||
// The node after `@`.
|
||||
let head = ref.node.firstChild?.nextSibling ?? null;
|
||||
while (head) {
|
||||
if (head.name === "CallExpression") head = head.firstChild;
|
||||
else if (head.name === "MemberExpression") {
|
||||
const name = head.lastChild;
|
||||
if (name?.name === "PropertyName")
|
||||
out.push({ from: name.from, to: name.to, className: "cm-sem-annotation", source: "syntax" });
|
||||
head = head.firstChild;
|
||||
} else {
|
||||
if (head.name === "VariableName")
|
||||
out.push({ from: head.from, to: head.to, className: "cm-sem-annotation", source: "syntax" });
|
||||
head = null;
|
||||
}
|
||||
for (const from of starts) {
|
||||
// The innermost node starting there is the `@` token.
|
||||
let decorator: SyntaxNode | null = tree.resolve(from, 1);
|
||||
while (decorator && decorator.name !== "Decorator") decorator = decorator.parent;
|
||||
if (!decorator) continue;
|
||||
// The node after `@`.
|
||||
let head = decorator.firstChild?.nextSibling ?? null;
|
||||
while (head) {
|
||||
if (head.name === "CallExpression") head = head.firstChild;
|
||||
else if (head.name === "MemberExpression") {
|
||||
const name = head.lastChild;
|
||||
if (name?.name === "PropertyName")
|
||||
out.push({ from: name.from, to: name.to, className: "cm-sem-annotation", source: "syntax" });
|
||||
head = head.firstChild;
|
||||
} else {
|
||||
if (head.name === "VariableName")
|
||||
out.push({ from: head.from, to: head.to, className: "cm-sem-annotation", source: "syntax" });
|
||||
head = null;
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
* it follows the caret and closes when the server reports no signature;
|
||||
* ⇥ / ⇧⇥ move to the next / previous argument.
|
||||
*/
|
||||
import { hasLinkedSnippetField } from "@/editor/core/cm/linkedSnippet";
|
||||
import { EditorSelection, Prec, StateEffect, StateField, type Extension } from "@codemirror/state";
|
||||
import { completionStatus, hasNextSnippetField, hasPrevSnippetField } from "@codemirror/autocomplete";
|
||||
import {
|
||||
@@ -289,7 +290,8 @@ function moveToArgument(view: EditorView, dir: 1 | -1): boolean {
|
||||
if (!state.field(signatureField, false) || state.readOnly) return false;
|
||||
if (state.selection.ranges.length > 1 || completionStatus(state) === "active") return false;
|
||||
// Snippet / template fields and the in-place rename own ⇥.
|
||||
if (dir > 0 ? hasNextSnippetField(state) : hasPrevSnippetField(state)) return false;
|
||||
if (hasLinkedSnippetField(state, dir) || (dir > 0 ? hasNextSnippetField(state) : hasPrevSnippetField(state)))
|
||||
return false;
|
||||
if (inplaceRenameActive(state)) return false;
|
||||
const head = state.selection.main.head;
|
||||
const to = argumentStop(state.doc.toString(), head, dir);
|
||||
|
||||
@@ -193,11 +193,17 @@ export function lspSnippetToCm(snippet: string, vars: SnippetVariables = {}): st
|
||||
const hasField = nodes.some(
|
||||
(n) => n.t === "tab" || n.t === "choice" || (n.t === "var" && vars[n.name] === undefined && !n.children),
|
||||
);
|
||||
const defaults = new Map<number, string>();
|
||||
for (const node of nodes) {
|
||||
if (node.t === "text" || node.t === "var" || node.n === 0 || defaults.has(node.n)) continue;
|
||||
if (node.t === "choice") defaults.set(node.n, node.options[0] ?? "");
|
||||
else if (node.children) defaults.set(node.n, flatten(node.children, vars));
|
||||
}
|
||||
let out = "";
|
||||
for (const n of nodes) {
|
||||
if (n.t === "text") out += escapeText(n.v);
|
||||
else if (n.t === "tab") out += field(n.n, n.children ? flatten(n.children, vars) : "");
|
||||
else if (n.t === "choice") out += field(n.n, n.options[0] ?? "");
|
||||
else if (n.t === "tab") out += field(n.n, defaults.get(n.n) ?? (n.children ? flatten(n.children, vars) : ""));
|
||||
else if (n.t === "choice") out += field(n.n, defaults.get(n.n) ?? n.options[0] ?? "");
|
||||
else {
|
||||
const v = vars[n.name];
|
||||
if (v !== undefined) out += escapeText(v);
|
||||
|
||||
+11
-7
@@ -1,5 +1,6 @@
|
||||
/** Editor-side styling for LSP features (CodeMirror theme; tokens only). */
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { inlineBackground, inlineFramedFallback, inlineFramedModern } from "@/editor/core/cm/inlineBg";
|
||||
import { RAINBOW_COLORS } from "./semantic";
|
||||
|
||||
const tooltipSurface = {
|
||||
@@ -200,7 +201,6 @@ export const lspTheme = EditorView.theme({
|
||||
flex: "0 1 auto",
|
||||
minWidth: "0",
|
||||
marginLeft: "auto",
|
||||
paddingLeft: "16px",
|
||||
textAlign: "right",
|
||||
color: "var(--fg-subtle)",
|
||||
overflow: "hidden",
|
||||
@@ -402,7 +402,8 @@ export const lspTheme = EditorView.theme({
|
||||
".cm-lsp-occurrence-write, .cm-lsp-occurrence-tail-write": {
|
||||
"--lsp-occurrence-bg": "var(--bg-identifier-under-caret-write, color-mix(in srgb, var(--danger) 12%, transparent))",
|
||||
},
|
||||
".cm-lsp-occurrence": { backgroundColor: "var(--lsp-occurrence-bg)" },
|
||||
".cm-line.cm-lsp-occurrence": { backgroundColor: "var(--lsp-occurrence-bg)" },
|
||||
"span.cm-lsp-occurrence": inlineBackground("var(--lsp-occurrence-bg)"),
|
||||
// Text fill, not `color`: it reaches the syntax and semantic spans nested inside, and with the
|
||||
// variable unset the declaration drops, so they keep their own colours.
|
||||
"span.cm-lsp-occurrence, .cm-lsp-occurrence-text": { WebkitTextFillColor: "var(--fg-identifier-under-caret)" },
|
||||
@@ -436,18 +437,21 @@ export const lspTheme = EditorView.theme({
|
||||
borderBottomColor: "var(--bg-popup)",
|
||||
},
|
||||
// Chooser highlight (tempHighlight.ts): the expression / occurrences a choice would take.
|
||||
".cm-lsp-chooser-highlight": { backgroundColor: "var(--bg-text-search-result)" },
|
||||
".cm-lsp-chooser-removed": { backgroundColor: "var(--diff-deleted)" },
|
||||
".cm-lsp-chooser-highlight": inlineBackground("var(--bg-text-search-result)"),
|
||||
".cm-lsp-chooser-removed": inlineBackground("var(--diff-deleted)"),
|
||||
|
||||
// --- in-place rename (inplaceRename.ts) ------------------------------------
|
||||
".cm-lsp-inplace": {
|
||||
backgroundColor: "var(--bg-identifier-under-caret, color-mix(in srgb, var(--accent) 14%, transparent))",
|
||||
"--lsp-inplace-bg": "var(--bg-identifier-under-caret, color-mix(in srgb, var(--accent) 14%, transparent))",
|
||||
...inlineBackground("var(--lsp-inplace-bg)"),
|
||||
},
|
||||
".cm-lsp-inplace-primary": {
|
||||
outline: "1px solid var(--focus-ring)",
|
||||
outlineOffset: "-1px",
|
||||
...inlineFramedFallback("var(--lsp-inplace-bg)", "var(--focus-ring)"),
|
||||
borderRadius: "2px",
|
||||
},
|
||||
"@supports (height: 1lh)": {
|
||||
".cm-lsp-inplace-primary": inlineFramedModern("var(--lsp-inplace-bg)", "var(--focus-ring)"),
|
||||
},
|
||||
".cm-lsp-inplace-hint": {
|
||||
color: "var(--fg-secondary)",
|
||||
fontSize: "var(--fs-small)",
|
||||
|
||||
@@ -25,6 +25,7 @@ import { isNavigating, onNavigation } from "@/editor/lsp/foreground";
|
||||
import { readManyFileLines, withDocument } from "@/editor/lsp/files";
|
||||
import { locationItems, navigateTo, pinToFind } from "@/editor/lsp/navigation";
|
||||
import { openPopup } from "@/editor/lsp/popupStore";
|
||||
import type { DeclarationTarget } from "@/editor/lsp/syntaxFallback";
|
||||
import {
|
||||
commands,
|
||||
isCancelled,
|
||||
@@ -542,13 +543,32 @@ async function markerTargets(marker: LineMarker, doc: DocId | null): Promise<Loc
|
||||
}
|
||||
}
|
||||
|
||||
/** Opens the single target, or the chooser over several. */
|
||||
/** Resolves each declaration's targets before opening the shared chooser. */
|
||||
export async function openMarkerTargets(
|
||||
marker: LineMarker,
|
||||
markers: readonly [LineMarker, ...LineMarker[]],
|
||||
anchor: { x: number; y: number },
|
||||
doc: DocId | null = null,
|
||||
) {
|
||||
const targets = await markerTargets(marker, doc);
|
||||
const [first] = markers;
|
||||
const merged = markers.length > 1;
|
||||
let targets: DeclarationTarget[] = (
|
||||
await Promise.all(
|
||||
markers.map(async (marker) => {
|
||||
const locations = await markerTargets(marker, doc);
|
||||
// Generated methods can share a source location. Keep their names visible in the chooser.
|
||||
return merged && marker.method ? locations.map((target) => ({ ...target, name: marker.name })) : locations;
|
||||
}),
|
||||
)
|
||||
).flat();
|
||||
if (merged) {
|
||||
const seen = new Set<string>();
|
||||
targets = targets.filter(({ path, range, name }) => {
|
||||
const key = JSON.stringify([path, range.start.line, range.start.col, name]);
|
||||
if (seen.has(key)) return false;
|
||||
seen.add(key);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
if (targets.length === 1) {
|
||||
await navigateTo(targets[0]!);
|
||||
return;
|
||||
@@ -556,9 +576,9 @@ export async function openMarkerTargets(
|
||||
openPopup({
|
||||
kind: "list",
|
||||
anchor,
|
||||
title: marker.chooserTitle,
|
||||
title: merged ? tx`Choose Inheritance Target (${targets.length} found)` : first.chooserTitle,
|
||||
items: await locationItems(targets),
|
||||
pin: pinToFind(marker.name, targets),
|
||||
pin: pinToFind([...new Set(markers.map((m) => m.name))].join(", "), targets),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -587,41 +607,50 @@ function place(doc: Text, markers: readonly LineMarker[]): PlacedMarker[] {
|
||||
}
|
||||
|
||||
const sameMarkers = (a: readonly PlacedMarker[], b: readonly PlacedMarker[]) =>
|
||||
a.length === b.length &&
|
||||
a.every(
|
||||
(m, i) => m.pos === b[i]!.pos && m.marker.kind === b[i]!.marker.kind && m.marker.tooltip === b[i]!.marker.tooltip,
|
||||
);
|
||||
a.length === b.length && a.every((m, i) => m.pos === b[i]!.pos && m.marker === b[i]!.marker);
|
||||
|
||||
class InheritanceMarker extends GutterMarker {
|
||||
constructor(readonly marker: LineMarker) {
|
||||
readonly kind: LineMarker["kind"];
|
||||
readonly tooltip: string;
|
||||
|
||||
constructor(readonly markers: readonly [LineMarker, ...LineMarker[]]) {
|
||||
super();
|
||||
const [first] = markers;
|
||||
this.kind = first.kind;
|
||||
this.tooltip =
|
||||
markers.length === 1 ? first.tooltip : [...new Set(markers.map((m) => `${m.name} — ${m.tooltip}`))].join("\n");
|
||||
}
|
||||
|
||||
override eq(other: GutterMarker): boolean {
|
||||
return (
|
||||
other instanceof InheritanceMarker &&
|
||||
other.marker.kind === this.marker.kind &&
|
||||
other.marker.tooltip === this.marker.tooltip
|
||||
);
|
||||
return other instanceof InheritanceMarker && other.kind === this.kind && other.tooltip === this.tooltip;
|
||||
}
|
||||
|
||||
override toDOM(): Node {
|
||||
const el = document.createElement("div");
|
||||
el.className = `${styles.marker} cm-openidea-lineMarker-${this.marker.kind}`;
|
||||
el.dataset.kind = this.marker.kind;
|
||||
el.title = this.marker.tooltip;
|
||||
el.className = `${styles.marker} cm-openidea-lineMarker-${this.kind}`;
|
||||
el.dataset.kind = this.kind;
|
||||
el.title = this.tooltip;
|
||||
el.setAttribute("role", "button");
|
||||
el.setAttribute("aria-label", this.marker.tooltip);
|
||||
el.innerHTML = gutterIconMarkup(MARKER_ICONS[this.marker.kind]) ?? "";
|
||||
el.setAttribute("aria-label", this.tooltip);
|
||||
el.innerHTML = gutterIconMarkup(MARKER_ICONS[this.kind]) ?? "";
|
||||
return el;
|
||||
}
|
||||
}
|
||||
|
||||
const gutterMarkers = new WeakMap<readonly PlacedMarker[], RangeSet<GutterMarker>>();
|
||||
const gutterMarkers = new WeakMap<readonly PlacedMarker[], RangeSet<InheritanceMarker>>();
|
||||
|
||||
function markerSet(placed: readonly PlacedMarker[]): RangeSet<GutterMarker> {
|
||||
function markerSet(placed: readonly PlacedMarker[]): RangeSet<InheritanceMarker> {
|
||||
let set = gutterMarkers.get(placed);
|
||||
if (!set) {
|
||||
const groups = new Map<string, { pos: number; markers: [LineMarker, ...LineMarker[]] }>();
|
||||
for (const { pos, marker } of placed) {
|
||||
const key = `${pos}:${marker.kind}`;
|
||||
const group = groups.get(key);
|
||||
if (group) group.markers.push(marker);
|
||||
else groups.set(key, { pos, markers: [marker] });
|
||||
}
|
||||
set = RangeSet.of(
|
||||
placed.map((m) => new InheritanceMarker(m.marker).range(m.pos)),
|
||||
[...groups.values()].map(({ pos, markers }) => new InheritanceMarker(markers).range(pos)),
|
||||
true,
|
||||
);
|
||||
gutterMarkers.set(placed, set);
|
||||
@@ -829,10 +858,14 @@ export function markerDeps(
|
||||
};
|
||||
}
|
||||
|
||||
function markerAt(view: EditorView, lineFrom: number, el: Element | null): LineMarker | null {
|
||||
const onLine = view.state.field(markersField).filter((m) => m.pos === lineFrom);
|
||||
const kind = (el?.closest(`.${styles.marker}`) as HTMLElement | null)?.dataset.kind;
|
||||
return (onLine.find((m) => m.marker.kind === kind) ?? (onLine.length === 1 ? onLine[0] : null))?.marker ?? null;
|
||||
function markerAt(view: EditorView, lineFrom: number, kind: string | undefined): InheritanceMarker | undefined {
|
||||
let match: InheritanceMarker | undefined;
|
||||
markerSet(view.state.field(markersField)).between(lineFrom, lineFrom, (pos, _to, marker) => {
|
||||
if (pos !== lineFrom || marker.kind !== kind) return;
|
||||
match = marker;
|
||||
return false;
|
||||
});
|
||||
return match;
|
||||
}
|
||||
|
||||
export function implementationGutter(ctx: EditorDocContext): Extension {
|
||||
@@ -846,13 +879,13 @@ export function implementationGutter(ctx: EditorDocContext): Extension {
|
||||
markers: (view) => markerSet(view.state.field(markersField)),
|
||||
mousedown: (view, block, e) => {
|
||||
if (e.button !== 0) return false;
|
||||
const target = e.target instanceof Element ? e.target : null;
|
||||
if (!target?.closest(`.${styles.marker}`)) return false;
|
||||
const marker = markerAt(view, block.from, target);
|
||||
const target = e.target instanceof Element ? e.target.closest<HTMLElement>(`.${styles.marker}`) : null;
|
||||
if (!target) return false;
|
||||
const marker = markerAt(view, block.from, target.dataset.kind);
|
||||
if (!marker) return false;
|
||||
e.preventDefault();
|
||||
const rect = (target.closest(`.${styles.marker}`) ?? target).getBoundingClientRect();
|
||||
void openMarkerTargets(marker, { x: rect.left, y: rect.bottom + 2 }, ctx.doc);
|
||||
const rect = target.getBoundingClientRect();
|
||||
void openMarkerTargets(marker.markers, { x: rect.left, y: rect.bottom + 2 }, ctx.doc);
|
||||
return true;
|
||||
},
|
||||
}),
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { fireEvent } from "@testing-library/react";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { iconAreaExtension } from "@/editor/core/cm/iconArea";
|
||||
import { lspDoc } from "@/editor/lsp/lsp";
|
||||
import type { DeclarationTarget } from "@/editor/lsp/syntaxFallback";
|
||||
import {
|
||||
IpcError,
|
||||
commands,
|
||||
@@ -14,14 +19,15 @@ const nav = vi.hoisted(() => ({ navigateTo: vi.fn(async () => {}), openPopup: vi
|
||||
vi.mock("@/editor/lsp/navigation", async (orig) => ({
|
||||
...(await orig<typeof import("@/editor/lsp/navigation")>()),
|
||||
navigateTo: nav.navigateTo,
|
||||
locationItems: async (locs: Location[]) => locs.map((l, i) => ({ id: `${i}`, label: l.path, run: () => {} })),
|
||||
locationItems: async (locs: DeclarationTarget[]) =>
|
||||
locs.map((l, i) => ({ id: `${i}`, label: l.name ?? l.path, run: () => {} })),
|
||||
}));
|
||||
vi.mock("@/editor/lsp/popupStore", async (orig) => ({
|
||||
...(await orig<typeof import("@/editor/lsp/popupStore")>()),
|
||||
openPopup: nav.openPopup,
|
||||
}));
|
||||
|
||||
import { candidateKey, markerCandidates, type MarkerCandidate } from "./lineMarkers";
|
||||
import { candidateKey, markerCandidates, type LineMarker, type MarkerCandidate } from "./lineMarkers";
|
||||
import { Text } from "@codemirror/state";
|
||||
import {
|
||||
affectsMarkers,
|
||||
@@ -29,6 +35,7 @@ import {
|
||||
emptyCache,
|
||||
enabledGroups,
|
||||
fillMarkers,
|
||||
implementationGutter,
|
||||
libraryCandidates,
|
||||
markerBatches,
|
||||
markerDeps,
|
||||
@@ -539,16 +546,18 @@ describe("clicking a marker", () => {
|
||||
it("navigates to a single target", async () => {
|
||||
const target = loc("/p/Circle.java", 0, 13);
|
||||
await openMarkerTargets(
|
||||
{
|
||||
kind: "implemented",
|
||||
line: 0,
|
||||
col: 17,
|
||||
method: false,
|
||||
name: "Shape",
|
||||
targets: [target],
|
||||
tooltip: "",
|
||||
chooserTitle: "",
|
||||
},
|
||||
[
|
||||
{
|
||||
kind: "implemented",
|
||||
line: 0,
|
||||
col: 17,
|
||||
method: false,
|
||||
name: "Shape",
|
||||
targets: [target],
|
||||
tooltip: "",
|
||||
chooserTitle: "",
|
||||
},
|
||||
],
|
||||
{ x: 1, y: 2 },
|
||||
);
|
||||
expect(nav.navigateTo).toHaveBeenCalledWith(target);
|
||||
@@ -562,16 +571,18 @@ describe("clicking a marker", () => {
|
||||
const method = { ...zero, range: { start: { line: 5, col: 4 }, end: { line: 7, col: 5 } } };
|
||||
const spy = vi.spyOn(commands, "lspImplementationLocations").mockResolvedValue({ status: "ok", data: [method] });
|
||||
await openMarkerTargets(
|
||||
{
|
||||
kind: "implemented",
|
||||
line: 1,
|
||||
col: 9,
|
||||
method: true,
|
||||
name: "save",
|
||||
targets: [zero],
|
||||
tooltip: "",
|
||||
chooserTitle: "",
|
||||
},
|
||||
[
|
||||
{
|
||||
kind: "implemented",
|
||||
line: 1,
|
||||
col: 9,
|
||||
method: true,
|
||||
name: "save",
|
||||
targets: [zero],
|
||||
tooltip: "",
|
||||
chooserTitle: "",
|
||||
},
|
||||
],
|
||||
{ x: 1, y: 2 },
|
||||
7,
|
||||
);
|
||||
@@ -585,16 +596,18 @@ describe("clicking a marker", () => {
|
||||
const targets = [loc("/p/Circle.java", 0, 13), loc("/p/Square.java", 0, 13)];
|
||||
expect(candidateKey(candidate())).toBe("0:17:Shape");
|
||||
await openMarkerTargets(
|
||||
{
|
||||
kind: "implemented",
|
||||
line: 0,
|
||||
col: 17,
|
||||
method: false,
|
||||
name: "Shape",
|
||||
targets,
|
||||
tooltip: "",
|
||||
chooserTitle: "Choose Implementation of Shape (2 found)",
|
||||
},
|
||||
[
|
||||
{
|
||||
kind: "implemented",
|
||||
line: 0,
|
||||
col: 17,
|
||||
method: false,
|
||||
name: "Shape",
|
||||
targets,
|
||||
tooltip: "",
|
||||
chooserTitle: "Choose Implementation of Shape (2 found)",
|
||||
},
|
||||
],
|
||||
{ x: 1, y: 2 },
|
||||
);
|
||||
expect(nav.navigateTo).not.toHaveBeenCalled();
|
||||
@@ -609,6 +622,98 @@ describe("clicking a marker", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("inheritance gutter", () => {
|
||||
it.each([
|
||||
{ kind: "overriding", language: "java", declaration: "@SuperBuilder" },
|
||||
{ kind: "overridden", language: "java", declaration: "@Data" },
|
||||
{ kind: "implementing", language: "go", declaration: "type Square struct{}" },
|
||||
{ kind: "implemented", language: "rust", declaration: "trait Shape { fn area(); fn label(); }" },
|
||||
] as const)("merges $language $kind markers by line and kind", async ({ kind, language, declaration }) => {
|
||||
vi.useFakeTimers();
|
||||
nav.navigateTo.mockClear();
|
||||
nav.openPopup.mockClear();
|
||||
const ctx = { doc: 1, path: `/p/gutter-${kind}`, language, uiMode: null, readOnly: false };
|
||||
const doc = Text.of([declaration, "another declaration"]);
|
||||
const markers = markersOf(ctx.path, doc);
|
||||
const otherKind = kind === "overridden" ? "overriding" : "overridden";
|
||||
const inputs = [
|
||||
{ kind, name: "build", line: 0 },
|
||||
{ kind: otherKind, name: "other", line: 0 },
|
||||
{ kind, name: "self", line: 0 },
|
||||
{ kind, name: "build", line: 0 },
|
||||
{ kind, name: "later", line: 1 },
|
||||
] as const;
|
||||
const candidates = inputs.map(({ name, line }, i): MarkerCandidate => ({
|
||||
name,
|
||||
line,
|
||||
symbol: `${name}(${i})`,
|
||||
col: 0,
|
||||
method: true,
|
||||
abstract: false,
|
||||
inheritable: false,
|
||||
overriding: false,
|
||||
owner: null,
|
||||
}));
|
||||
markers.outline = { items: [], candidates };
|
||||
inputs.forEach((input, i) => {
|
||||
const marker: LineMarker = {
|
||||
...input,
|
||||
col: 0,
|
||||
method: true,
|
||||
targets: [
|
||||
loc(
|
||||
language === "java" && input.kind === kind && input.line === 0 ? "/p/BaseOrder.java" : `/p/${input.name}`,
|
||||
2,
|
||||
),
|
||||
],
|
||||
tooltip: `Target for ${input.name}`,
|
||||
chooserTitle: input.name,
|
||||
};
|
||||
const group = marker.kind === "implemented" || marker.kind === "overridden" ? "inheritors" : "supers";
|
||||
markers.cache.entries.set(candidateKey(candidates[i]!), { [group]: marker });
|
||||
});
|
||||
const view = new EditorView({
|
||||
doc,
|
||||
extensions: [lspDoc.of(ctx), iconAreaExtension, implementationGutter(ctx)],
|
||||
parent: document.body,
|
||||
});
|
||||
try {
|
||||
await vi.advanceTimersByTimeAsync(500);
|
||||
const icons = [...view.dom.querySelectorAll<HTMLElement>(`.cm-openidea-lineMarker-${kind}`)];
|
||||
expect(icons).toHaveLength(2);
|
||||
expect(icons[0]!.title).toContain("Target for build");
|
||||
expect(icons[0]!.title).toContain("Target for self");
|
||||
expect(icons[0]!.title).not.toContain("Target for later");
|
||||
expect(icons[0]!.parentElement!.querySelector(`.cm-openidea-lineMarker-${otherKind}`)).not.toBeNull();
|
||||
|
||||
fireEvent.mouseDown(icons[0]!, { button: 0 });
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(nav.navigateTo).not.toHaveBeenCalled();
|
||||
expect(nav.openPopup.mock.calls[0]![0].items.map((item: { label: string }) => item.label)).toEqual([
|
||||
"build",
|
||||
"self",
|
||||
]);
|
||||
|
||||
// CodeMirror finds the clicked line by the gutter row's screen position.
|
||||
const block = view.lineBlockAt(doc.line(2).from);
|
||||
vi.spyOn(icons[1]!.parentElement!, "getBoundingClientRect").mockReturnValue(
|
||||
new DOMRect(0, view.documentTop + block.top, 10, block.height),
|
||||
);
|
||||
fireEvent.mouseDown(icons[1]!, { button: 0 });
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(nav.navigateTo).toHaveBeenCalledWith(loc("/p/later", 2));
|
||||
|
||||
view.dispatch({ changes: { from: doc.line(1).to, to: doc.line(2).from, insert: " " } });
|
||||
const joined = view.dom.querySelectorAll<HTMLElement>(`.cm-openidea-lineMarker-${kind}`);
|
||||
expect(joined).toHaveLength(1);
|
||||
expect(joined[0]!.title).toContain("Target for later");
|
||||
} finally {
|
||||
view.destroy();
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("overriders of a type's methods from its subtypes", () => {
|
||||
// Shapes and names as jdtls answers them (outline names carry the signature).
|
||||
const REPO = [
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* Settings › Agents › Coding Agents: one searchable list of every agent, those this machine can run first
|
||||
* Agent Setup lists every agent, with those this machine can run first
|
||||
* (built in, installed from the ACP Registry, or defined in an agent file), then those it
|
||||
* can install. The selected agent's page holds its actions, the settings its new tasks
|
||||
* start with, and how it is launched. Launch edits are staged until Apply; installs run in
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
/**
|
||||
* Settings › Tools › Agents › Command Permissions: whitelist (auto-approve)
|
||||
* and blacklist (auto-reject) command patterns evaluated on agent permission requests.
|
||||
* Command Rules defines the allow and block patterns for agent permission requests.
|
||||
*/
|
||||
import { useMemo, useState } from "react";
|
||||
import { tx } from "@/platform/i18n";
|
||||
@@ -47,7 +46,7 @@ export function AgentPolicyPage() {
|
||||
};
|
||||
|
||||
return (
|
||||
<section className={styles.body} aria-label="Command Permissions">
|
||||
<section className={styles.body} aria-label={tx("Command Rules")}>
|
||||
<p className={styles.notice}>
|
||||
<T>
|
||||
Allowed commands run without asking, with or without extra arguments. Blocked commands are always rejected,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/** Settings › Agents › Coding Agents. */
|
||||
/** Settings › Agents › Agent Setup. */
|
||||
import { AgentList } from "./AgentList";
|
||||
import { tauriCommands, tauriRegistry, type CommandsBackend, type RegistryBackend } from "./registry";
|
||||
import styles from "./AgentRegistry.module.css";
|
||||
|
||||
@@ -224,11 +224,12 @@
|
||||
flex: none;
|
||||
}
|
||||
|
||||
/* Import Sessions from Other Apps: filter above a fixed-height list, so the dialog doesn't grow. */
|
||||
/* Keep the import list height stable while filtering. */
|
||||
.chooser {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-2);
|
||||
padding: var(--space-3) var(--space-4) 0;
|
||||
}
|
||||
.chooserList {
|
||||
height: 312px;
|
||||
|
||||
@@ -281,8 +281,9 @@ describe("Agents docked view", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("lists Import Sessions from Other Apps in Find Action", () => {
|
||||
it("lists Import Sessions in Find Action", () => {
|
||||
const action = taskActions.find((a) => a.id === "agents.importSessions");
|
||||
expect(action?.title).toBe("Import Sessions…");
|
||||
expect(action?.hidden).toBeFalsy();
|
||||
expect(action?.when).toBe("projectOpen");
|
||||
act(() => void action?.run({} as never));
|
||||
@@ -502,17 +503,17 @@ describe("Agents pinned and grouped tasks", () => {
|
||||
expect(rows.some((text) => text.includes("one"))).toBe(true);
|
||||
});
|
||||
|
||||
it("offers the groups, a new one and a way out in Move to Group", () => {
|
||||
it("offers the groups, a new one and a way out in the Group submenu", () => {
|
||||
useAgents.setState({ organize: { groups: [frontend], groupOf: { two: "g1" }, pinned: [] } });
|
||||
const menu = taskMenu([useAgents.getState().tasks.get("two")!]);
|
||||
const move = menu.find((item) => "label" in item && item.label === "Move to Group");
|
||||
const move = menu.find((item) => "label" in item && item.label === "Group");
|
||||
expect(move).toBeDefined();
|
||||
const submenu = (move as { submenu: { label?: string; checked?: boolean }[] }).submenu;
|
||||
expect(submenu.map((item) => item.label ?? "separator")).toEqual([
|
||||
"Frontend",
|
||||
"separator",
|
||||
"New Group…",
|
||||
"Remove from Group",
|
||||
"No Group",
|
||||
]);
|
||||
expect(submenu[0]).toMatchObject({ checked: true });
|
||||
});
|
||||
@@ -520,7 +521,7 @@ describe("Agents pinned and grouped tasks", () => {
|
||||
it("moves a pinned task into a group, out of the pinned section", () => {
|
||||
useAgents.setState({ organize: { groups: [frontend], groupOf: {}, pinned: ["two"] } });
|
||||
const menu = taskMenu([useAgents.getState().tasks.get("two")!]);
|
||||
const move = menu.find((item) => "label" in item && item.label === "Move to Group") as {
|
||||
const move = menu.find((item) => "label" in item && item.label === "Group") as {
|
||||
submenu: { label?: string; run?: () => void }[];
|
||||
};
|
||||
act(() => move.submenu.find((item) => item.label === "Frontend")!.run!());
|
||||
|
||||
Loaded 100 of 247 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user