Compare commits

..
Author SHA1 Message Date
l0ng-ai 8d8bd996dd fix(github): keep the review composer readable 2026-11-23 14:01:47 +08:00
258 changed files with 1602 additions and 10476 deletions

No files matched your search

Binary file not shown.

Before

Width:  |  Height:  |  Size: 138 KiB

After

Width:  |  Height:  |  Size: 160 KiB

Generated
+2 -2
View File
@@ -1104,9 +1104,9 @@ checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b"
[[package]]
name = "cookie"
version = "0.18.3"
version = "0.18.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d55f2d6c30eeec7d5c6f98bd4395d4abb1895629eab97ee6522d340623615f8a"
checksum = "1a373e3602691c3cdea496d2f0ee5935151e6168fe87739483c463db1b2f2f87"
dependencies = [
"time",
"version_check",
-3
View File
@@ -536,9 +536,6 @@ 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>,
-30
View File
@@ -1007,16 +1007,11 @@ 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"));
}
@@ -1120,31 +1115,6 @@ 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,38 +531,6 @@ 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;
@@ -1130,24 +1098,6 @@ 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,22 +144,6 @@ 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);
@@ -246,43 +230,6 @@ 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,13 +458,6 @@ 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") => {
@@ -568,16 +561,6 @@ 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
+3 -42
View File
@@ -1,6 +1,6 @@
//! Folds ACP `session/update` notifications into a task's entries.
use crate::model::{AgentEntry, AgentImage, AgentPlanItem, AgentSubagentStatus, AgentToolDiff, AgentToolStatus};
use crate::model::{AgentEntry, AgentPlanItem, AgentSubagentStatus, AgentToolDiff, AgentToolStatus};
use ide_core::IpcPath;
use serde_json::Value;
use std::collections::HashMap;
@@ -84,7 +84,6 @@ 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,
@@ -151,7 +150,7 @@ impl Timeline {
}
fn merge_tool(&mut self, index: usize, update: &Value) {
let AgentEntry::Tool { title, kind, status, locations: locs, output, images, diffs, ended_ms, .. } =
let AgentEntry::Tool { title, kind, status, locations: locs, output, diffs, ended_ms, .. } =
&mut self.entries[index]
else {
return;
@@ -174,20 +173,10 @@ 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") => {
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 let Some(t) = content_text(item.get("content")) {
if !text.is_empty() {
text.push('\n');
}
@@ -214,9 +203,6 @@ 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
@@ -453,31 +439,6 @@ 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();
+1 -2
View File
@@ -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,
mut config: RunConfig,
config: RunConfig,
errors: &mut BuildErrors,
) -> IdeResult<Result<RunConfig, String>> {
if !JVM_APPLICATION_KINDS.contains(&config.kind.as_str()) {
@@ -544,7 +544,6 @@ async fn resolve_jvm_application(
(Some(exec), "java") => exec.clone(),
_ => config.command.clone(),
};
config.extras.module = Some(module);
Ok(Ok(RunConfig { command, args, ..config }))
}
+5 -10
View File
@@ -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).
pub(super) mod workspace;
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.
pub(super) fn with_profiles(mut model: BuildModel, cache: &Path) -> BuildModel {
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,18 +952,16 @@ 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 = workspace::cache_at(&root, &cache, member);
let member_cache =
if member == &root { cache.clone() } else { cache.join(crate::project::project_key(member)) };
let model = with_profiles(load(member, &member_cache, &settings), &member_cache);
launch_caches.push(member_cache);
let plan = prepare_plan(
compile::plan(
member,
@@ -987,7 +985,6 @@ 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,
@@ -1010,9 +1007,7 @@ pub async fn build_run(
});
if kind == BuildKind::Rebuild {
// The clean removed outputs that earlier launch snapshots still hold.
for cache in launch_caches {
launch_project.java_launches.for_cache(&cache).snapshots.lock().forget_reusable_snapshots();
}
launch_project.java_launch_snapshots.lock().forget_reusable_snapshots();
}
let result = result?;
if result.success && single && kind == BuildKind::Build {
+6 -23
View File
@@ -1,33 +1,12 @@
use super::*;
use std::path::PathBuf;
pub(in crate::ops) struct Scope {
pub(super) 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())
}
@@ -40,7 +19,11 @@ fn scopes_at(root: &Path, cache: &Path, config: &Path, settings: Settings) -> Id
.into_iter()
.filter(|p| p.is_dir())
.map(|root| Scope {
cache: cache_at(window_root, cache, &root),
cache: if root == window_root {
cache.to_owned()
} else {
cache.join(crate::project::project_key(&root))
},
settings: ide_workspace::SettingsStore::load(config, Some(&root)).effective(),
root,
})
-10
View File
@@ -228,15 +228,6 @@ 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)]
@@ -392,7 +383,6 @@ ide_command::domain!(
fs_read_dir,
fs_read_text,
fs_rename,
fs_scratches_dir,
fs_set_writable,
fs_synchronize_directories,
fs_undo_delete,
+62 -57
View File
@@ -4,7 +4,7 @@ pub(crate) mod cache;
use crate::Host;
use ide_command::command;
use super::build::{load, with_profiles, workspace};
use super::build::load;
use ide_build::BuildModel;
use ide_build::compile;
use ide_core::error::ErrorKind;
@@ -46,44 +46,37 @@ pub(crate) async fn resolve_launch(
) -> IdeResult<JavaLaunchInfo> {
let started = std::time::Instant::now();
let project = host.project(window)?;
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()))??
};
let module = project.root.join(module);
if !project.lsp.java_served_by_jdtls(&module) {
return resolve_launch_without_jdtls(host, &project, module, scope, test, policy, cancel).await;
return resolve_launch_without_jdtls(host, &project, module, test, policy, cancel).await;
}
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;
let waiting = project.java_launches_waiting.add(module.clone(), test, policy);
let settings = project.settings.effective();
// 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, is_maven) = {
let scope = scope.clone();
let launches = launches.clone();
let (model, external, mut delegated, prefer_maven, is_maven) = {
let project = project.clone();
let settings = settings.clone();
let module = module.clone();
tokio::task::spawn_blocking(move || {
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);
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;
let delegated = build
&& delegates_to_external_build(
is_maven,
policy,
non_java,
cache::has_record(root, &scope.cache, &module),
cache::has_record(&project.root, &project.build_cache_dir(), &module),
prefer_maven,
);
let external = non_java || delegated;
(model, external, delegated, is_maven)
(model, external, delegated, prefer_maven, is_maven)
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?
@@ -108,7 +101,7 @@ pub(crate) async fn resolve_launch(
}
let model = std::sync::Arc::new(model);
let members = if delegated {
build_members(&project, &scope, &model, &module, test, &waiting, cancel).await?
build_members(&project, &model, &module, test, prefer_maven, &waiting, cancel).await?
} else {
Vec::new()
};
@@ -117,8 +110,7 @@ pub(crate) async fn resolve_launch(
let cancel = cancel.clone();
tokio::task::spawn_blocking(move || {
let _external_build = external_build;
let (root, cache, settings) = (&scope.root, &scope.cache, &scope.settings);
let local_repo = ide_sdk::apply::maven_local_repository(root, settings);
let local_repo = ide_sdk::apply::maven_local_repository(&project.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.
@@ -126,8 +118,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 = launches.snapshots.lock().build(
root,
let outputs = project.java_launch_snapshots.lock().build(
&project.root,
&model,
&module,
cache::BuildOptions { test, policy, rebuild_on_jdt_errors, members },
@@ -140,7 +132,7 @@ pub(crate) async fn resolve_launch(
snapshotted = outputs.originals;
copies
} else if external {
let built = compile::build_for_launch(root, &model, &module, test, build_kind, &cancel)?;
let built = compile::build_for_launch(&project.root, &model, &module, test, build_kind, &cancel)?;
if let Some(failure) = built.failure {
if policy != BuildPolicy::MakeAndContinueOnErrors {
return Err(IdeError::internal(failure));
@@ -157,15 +149,24 @@ 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(root, &model, &probed, test, local_repo, cache, &cancel);
let maven_cp = compile::module_classpaths(
&project.root,
&model,
&probed,
test,
local_repo,
&project.build_cache_dir(),
&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, root, &settings.project_structure.libraries, test);
apply_library_classpath(&mut info, &project.root, &settings.project_structure.libraries, test);
if build && !delegated {
match compile::process_launch_resources(root, &model, cache, &info.class_paths, &cancel) {
let cache_dir = project.build_cache_dir();
match compile::process_launch_resources(&project.root, &model, &cache_dir, &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),
@@ -176,7 +177,7 @@ pub(crate) async fn resolve_launch(
}
}
let compile_ms = started.elapsed().as_millis() - lsp_ms;
finish_launch(&mut info, root, &module, settings, &model, &data_dir);
finish_launch(&mut info, &project.root, &module, &settings, &model, &data_dir);
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
@@ -193,36 +194,28 @@ 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 scope = std::sync::Arc::new(scope);
let settings = project.settings.effective();
let kind = if policy == BuildPolicy::Rebuild { compile::BuildKind::Rebuild } else { compile::BuildKind::Build };
let (model, built) = {
let (scope, module, cancel) = (scope.clone(), module.clone(), cancel.clone());
let (root, cache, settings, module, cancel) =
(project.root.clone(), project.build_cache_dir(), settings.clone(), module.clone(), cancel.clone());
tokio::task::spawn_blocking(move || {
let model = load_launch_model(&scope);
let model = load(&root, &cache, &settings);
let built = if policy == BuildPolicy::NoBuild {
None
} else {
Some(compile::build_for_launch(&scope.root, &model, &module, test, kind, &cancel))
Some(compile::build_for_launch(&root, &model, &module, test, kind, &cancel))
};
(model, built)
})
@@ -256,9 +249,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;
@@ -267,14 +260,26 @@ async fn resolve_launch_without_jdtls(
append_unique_class_paths(&mut class_paths, server.classpath.class_paths);
}
None => {
if !is_maven_module(root, &model, &module) {
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 {
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(root, settings);
let classpath = compile::module_classpath(root, &model, &module, test, local_repo, cache, &cancel)?;
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,
)?;
append_unique_class_paths(
&mut class_paths,
std::env::split_paths(&classpath).map(|p| p.to_string_lossy().into_owned()),
@@ -282,8 +287,8 @@ async fn resolve_launch_without_jdtls(
}
}
info.class_paths = class_paths;
apply_library_classpath(&mut info, root, &settings.project_structure.libraries, test);
finish_launch(&mut info, root, &module, settings, &model, &data_dir);
apply_library_classpath(&mut info, &project.root, &settings.project_structure.libraries, test);
finish_launch(&mut info, &project.root, &module, &settings, &model, &data_dir);
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
@@ -440,10 +445,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>> {
@@ -451,11 +456,10 @@ 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 (scope, model, module) = (scope.clone(), model.clone(), module.to_path_buf());
let (project, model, module) = (project.clone(), model.clone(), module.to_path_buf());
tokio::task::spawn_blocking(move || {
joining_launches(&scope.root, &scope.cache, &model, &module, test, others, prefer_maven)
joining_launches(&project.root, &project.build_cache_dir(), &model, &module, test, others, prefer_maven)
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?
@@ -496,7 +500,8 @@ fn joining_launches(
others
.into_iter()
.filter(|o| {
let is_maven = is_maven_module(root, model, &o.module);
let is_maven =
model.maven.as_ref().is_some_and(|m| m.projects.iter().any(|p| root.join(&p.dir) == o.module));
o.test == test
&& matches!(o.policy, BuildPolicy::Automatic | BuildPolicy::Make)
&& compile::launch_reactor(root, model, &o.module).as_ref() == Some(&reactor)
-24
View File
@@ -64,30 +64,6 @@ 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)]
+1 -4
View File
@@ -242,10 +242,7 @@ fn settings_only(
.cloned()
});
if workspace.as_ref().is_some_and(|w| w.is_container(&project.root)) || member.is_some() {
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 {
if config.extras.module.is_none() && !matches!(config.kind.as_str(), "application" | "spring-boot") {
config.extras.module = config.cwd.as_deref().map(ide_core::ipc_path::to_ipc);
}
ide_run::scope::rebase(config, &project.root, None);
+2 -7
View File
@@ -111,7 +111,7 @@ pub(crate) fn search_project(
};
let literals = |path: &Path, text: &str| literals_of(project, syntax, path, text);
let defaults = project.documents.file_defaults();
let fallback = |path: &Path| defaults.fallback_for(path).map(str::to_owned);
let decode = |path: &Path, bytes: &[u8]| ide_vfs::decode_text(bytes, defaults.fallback_for(path));
let mut total = SearchSummary::default();
for dir in std::iter::once(root).filter(|_| include_root).chain(&content_roots) {
let mut remaining = query.clone();
@@ -139,7 +139,7 @@ pub(crate) fn search_project(
&remaining,
Some(&filter),
Some(&literals),
ide_search::TextSource { overlay: &|p| project.documents.search_text_of(p), fallback: &fallback },
ide_search::TextSource { overlay: &|p| project.documents.search_text_of(p), decode: &decode },
cancel,
&|mut file| {
if let Some(prefix) = &prefix {
@@ -188,11 +188,6 @@ pub(crate) fn rebase_masks(masks: &[String], prefix: &str) -> Vec<String> {
#[cfg(test)]
mod tests {
#[test]
fn search_leaves_unread_the_texts_the_parser_does_not_take() {
assert_eq!(ide_search::MAX_LITERALS_TEXT_BYTES, ide_language::MAX_PARSE_BYTES);
}
#[test]
fn masks_follow_the_root_they_search() {
let masks = vec![".wt/a/src/**, src/**".into(), "*.rs".into(), "!.wt/a/out/**".into(), "**/build/**".into()];
+12 -4
View File
@@ -51,8 +51,10 @@ pub struct Project {
pub(crate) member_excludes: MemberExcludes,
/// Per-project cache directory (build tool sync results…).
pub cache_dir: PathBuf,
/// Pending launches and retained snapshots, scoped to each workspace project.
pub(crate) java_launches: crate::ops::java::cache::Sessions,
/// 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,
/// 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.
@@ -639,7 +641,10 @@ impl Host {
detected_roots,
member_excludes,
cache_dir: self.local_data_dir.join("cache").join(&project_key),
java_launches: Default::default(),
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(),
kotlin_debug_notices: Mutex::default(),
db,
http_history,
@@ -886,7 +891,10 @@ impl Host {
detected_roots: Arc::default(),
member_excludes: Arc::default(),
cache_dir: self.local_data_dir.join("cache").join(&project_key),
java_launches: Default::default(),
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(),
kotlin_debug_notices: Mutex::default(),
db,
http_history,
-7
View File
@@ -74,13 +74,6 @@ 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);
-101
View File
@@ -6,107 +6,6 @@ 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();
+1 -8
View File
@@ -646,10 +646,7 @@ 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.
/// 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.
/// Generated Maven sources are attached first, so that recheck sees them.
pub(crate) fn java_projects_updated(self: &Arc<Self>, server: Arc<Server>, generation: u64) {
let uris: Vec<String> = self
.docs
@@ -666,10 +663,6 @@ 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] });
-26
View File
@@ -3165,32 +3165,6 @@ 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();
-2
View File
@@ -1587,13 +1587,11 @@ 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)?;
+4 -59
View File
@@ -1365,15 +1365,8 @@ pub fn configure_server(cfg: &mut LanguageServerConfig, root: &Path, server_root
_ => {}
}
}
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.
// TypeScript 7 serves LSP itself: it replaces the tsserver-based server.
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();
@@ -1387,8 +1380,10 @@ 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_pkg
&& let Some(vue) = vue::server_package(&vue_command, &search_path())
{
let plugin = vue::tsserver_plugin(&vue);
merge_init_options(cfg, json!({ "vtsls": { "tsserver": { "globalPlugins": [plugin] } } }));
@@ -2458,56 +2453,6 @@ 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();
-10
View File
@@ -42,16 +42,6 @@ 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!({
+21 -68
View File
@@ -24,11 +24,6 @@ const CANCEL_CHECK_LINES: u32 = 256;
/// How many matches a file keeps before claiming them from the shared budget: each file
/// searched in parallel holds about this many unclaimed matches at most, not up to the whole budget.
const CLAIM_BATCH: u32 = 64;
/// Bytes at the start of a text that the searcher checks for binary content up front.
const BINARY_HEAD_LEN: usize = 64 * 1024;
/// Files longer than this hold no text the parser takes, whatever their encoding (UTF-16 halves
/// the bytes of ASCII text, nothing else comes close): their comments and strings are not looked for.
const MAX_LITERALS_FILE_BYTES: u64 = 2 * crate::MAX_LITERALS_TEXT_BYTES as u64;
pub(crate) struct Request<'a> {
pub root: &'a Path,
@@ -68,11 +63,9 @@ impl Control<'_> {
/// Also polls the cancellation token (which takes a lock).
fn should_stop(&self) -> bool {
self.stopped() || self.cancel_requested()
}
/// Polls the cancellation token only: a search stopped by its match limit is not cancelled.
fn cancel_requested(&self) -> bool {
if self.stopped() {
return true;
}
if self.cancel.is_cancelled() {
self.cancelled.store(true, Relaxed);
self.stop.store(true, Relaxed);
@@ -309,37 +302,22 @@ impl Ctx<'_> {
{
return;
}
// The search context needs the whole text to find comments and string literals. A file
// whose text is past the longest the parser takes has none, so it is not read for them.
// The search context needs the whole text to find comments and string literals.
let in_context = match self.literals {
Some(literals) => 'context: {
Some(literals) => {
let text = match (self.text.overlay)(path) {
Some(text) => text,
None => {
match std::fs::metadata(path) {
Ok(meta) if meta.len() > MAX_LITERALS_FILE_BYTES => {
if self.context.needs_literals() {
return;
}
break 'context None;
}
Ok(_) => {}
Err(_) => return,
}
match std::fs::read(path) {
Ok(bytes) => match String::from_utf8(bytes) {
Ok(text) => text,
// Binary content has nothing to classify.
Err(e) => {
match ide_vfs::decode_text(e.as_bytes(), (self.text.fallback)(path).as_deref()) {
Some(text) => text,
None => return,
}
}
None => match std::fs::read(path) {
Ok(bytes) => match String::from_utf8(bytes) {
Ok(text) => text,
// Binary content has nothing to classify.
Err(e) => match (self.text.decode)(path, e.as_bytes()) {
Some(text) => text,
None => return,
},
Err(_) => return,
}
}
},
Err(_) => return,
},
};
let ranges = literals(path, &text);
if ranges.is_none() && self.context.needs_literals() {
@@ -376,8 +354,7 @@ impl Ctx<'_> {
}
/// Streams the file's bytes; a file that turns out not to be UTF-8 (GBK,
/// UTF-16 …) is searched again in its text decoded as the editor opens it,
/// which is decoded as it is read.
/// UTF-16 …) is searched again in the text `decode` gives it.
fn search_disk<'s>(
&'s self,
path: &Path,
@@ -385,7 +362,7 @@ impl Ctx<'_> {
searcher: &mut Searcher,
sink: &mut FileSink<'s>,
) -> io::Result<()> {
let mut reader = Utf8Probe::new(StopReader { inner: std::fs::File::open(path)?, ctl: &self.ctl, hard: true });
let mut reader = Utf8Probe::new(StopReader { inner: std::fs::File::open(path)?, ctl: &self.ctl });
let result = searcher.search_reader(matcher, &mut reader, &mut *sink);
// NUL bytes in the head of UTF-16 text stop the byte search; later ones mark binary.
let decode = if sink.binary {
@@ -397,29 +374,14 @@ impl Ctx<'_> {
if !decode || (self.ctl.stopped() && sink.claimed == 0) {
return result;
}
// Only cancellation ends the reading: a search that hit the match limit still fills its claim.
let open = || Ok(StopReader { inner: std::fs::File::open(path)?, ctl: &self.ctl, hard: false });
let Some(text) = ide_vfs::decode_stream(open, (self.text.fallback)(path).as_deref())? else {
let Some(text) = (self.text.decode)(path, &std::fs::read(path)?) else {
sink.binary = true;
return Ok(());
};
let mut text = text;
// Text held whole gets the searcher's binary check only on its first 64 KiB and on the
// lines that match; this keeps that for the text read piece by piece.
let mut head = Vec::with_capacity(BINARY_HEAD_LEN);
(&mut text).take(BINARY_HEAD_LEN as u64).read_to_end(&mut head)?;
if head.contains(&0) {
sink.binary = true;
return Ok(());
}
let claimed = sink.claimed;
*sink = FileSink::new(matcher, &self.ctl, None);
sink.claimed = claimed;
sink.binary_in_matches = true;
searcher.set_binary_detection(BinaryDetection::none());
let result = searcher.search_reader(matcher, io::Cursor::new(head).chain(text), sink);
searcher.set_binary_detection(BinaryDetection::quit(0));
result
searcher.search_slice(matcher, text.as_bytes(), sink)
}
}
@@ -442,8 +404,6 @@ struct FileSink<'a> {
/// file is searched again under the claim of its byte search.
claimed: u32,
binary: bool,
/// A NUL byte in a matching line marks the file binary (the searcher's own check is off).
binary_in_matches: bool,
ticks: u32,
/// Scratch buffers reused across lines.
found: Vec<(usize, usize)>,
@@ -465,7 +425,6 @@ impl<'a> FileSink<'a> {
count: 0,
claimed: 0,
binary: false,
binary_in_matches: false,
ticks: 0,
found: Vec::new(),
ranges: Vec::new(),
@@ -508,10 +467,6 @@ impl Sink for FileSink<'_> {
type Error = io::Error;
fn matched(&mut self, _searcher: &Searcher, m: &SinkMatch<'_>) -> Result<bool, io::Error> {
if self.binary_in_matches && memchr::memchr(0, m.bytes()).is_some() {
self.binary = true;
return Ok(false);
}
self.ticks += 1;
let stop = self.ctl.stopped() || (self.ticks.is_multiple_of(CANCEL_CHECK_LINES) && self.ctl.should_stop());
// Unless cancelled, a decoded file still fills the claim its byte search took.
@@ -579,17 +534,15 @@ impl Sink for FileSink<'_> {
}
}
/// Aborts disk reads once the search is cancelled, or with `hard` once it is stopped.
/// Aborts disk reads once the search is stopped or cancelled.
struct StopReader<'a, R> {
inner: R,
ctl: &'a Control<'a>,
hard: bool,
}
impl<R: Read> Read for StopReader<'_, R> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
let stop = if self.hard { self.ctl.should_stop() } else { self.ctl.cancel_requested() };
if stop {
if self.ctl.should_stop() {
return Err(io::Error::other("search stopped"));
}
self.inner.read(buf)
+6 -14
View File
@@ -112,14 +112,8 @@ impl SearchContext {
}
}
/// The longest file text, in bytes, that is searched for comments and string literals: the
/// parser's limit (`ide_language::MAX_PARSE_BYTES`), above which a [`Literals`] finds none.
/// The search leaves a longer text unread by it.
pub const MAX_LITERALS_TEXT_BYTES: usize = 16 * 1024 * 1024;
/// Comments and string literals of a file's text (sorted, non-overlapping),
/// or `None` when its language has no syntax tree or the text is longer than
/// [`MAX_LITERALS_TEXT_BYTES`].
/// or `None` when its language has no syntax tree.
pub type Literals<'a> = &'a (dyn Fn(&Path, &str) -> Option<Vec<LiteralRange>> + Sync);
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
@@ -204,23 +198,21 @@ pub struct SearchSummary {
/// Text of unsaved open documents takes precedence over disk content.
pub type Overlay<'a> = &'a (dyn Fn(&Path) -> Option<String> + Sync);
/// The encoding to read a file with when it is not UTF-8 and the encoding detected for it is not
/// trusted to be right (GBK, UTF-16 …): its label, or `None` to go by what is detected.
pub type FallbackEncoding<'a> = &'a (dyn Fn(&Path) -> Option<String> + Sync);
/// Text of a file whose bytes are not UTF-8 (GBK, UTF-16 …); `None` for binary content.
pub type Decode<'a> = &'a (dyn Fn(&Path, &[u8]) -> Option<String> + Sync);
/// Where a search reads file text from: the open document when `overlay` has
/// it, else the file on disk, decoded as the editor opens it when it is not UTF-8
/// (`fallback` picks the encoding that [`ide_vfs::decode_text`] takes).
/// it, else the file on disk, decoded by `decode` when it is not UTF-8.
#[derive(Clone, Copy)]
pub struct TextSource<'a> {
pub overlay: Overlay<'a>,
pub fallback: FallbackEncoding<'a>,
pub decode: Decode<'a>,
}
impl<'a> TextSource<'a> {
/// Non-UTF-8 files decode as detected, without a configured fallback encoding.
pub fn detected(overlay: Overlay<'a>) -> Self {
Self { overlay, fallback: &|_| None }
Self { overlay, decode: &|_, bytes| ide_vfs::decode_text(bytes, None) }
}
}
-159
View File
@@ -1,159 +0,0 @@
//! Searching a big file holds a bounded amount of it in memory, whatever its encoding and the
//! search context. Allocations of the whole process are counted, so this is one test with
//! sequential scenarios.
use ide_core::CancellationToken;
use ide_search::{
FileMatches, Literals, SearchContext, SearchQuery, SearchScope, SearchSummary, TextSource, search_in_context,
};
use std::alloc::{GlobalAlloc, Layout, System};
use std::path::Path;
use std::sync::Mutex;
use std::sync::atomic::{AtomicUsize, Ordering::Relaxed};
struct Counting;
static LIVE: AtomicUsize = AtomicUsize::new(0);
static PEAK: AtomicUsize = AtomicUsize::new(0);
fn grow(by: usize) {
let live = LIVE.fetch_add(by, Relaxed) + by;
PEAK.fetch_max(live, Relaxed);
}
unsafe impl GlobalAlloc for Counting {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
grow(layout.size());
unsafe { System.alloc(layout) }
}
unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
grow(layout.size());
unsafe { System.alloc_zeroed(layout) }
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
LIVE.fetch_sub(layout.size(), Relaxed);
unsafe { System.dealloc(ptr, layout) }
}
unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
if new_size >= layout.size() {
grow(new_size - layout.size());
} else {
LIVE.fetch_sub(layout.size() - new_size, Relaxed);
}
unsafe { System.realloc(ptr, layout, new_size) }
}
}
#[global_allocator]
static ALLOC: Counting = Counting;
const MIB: usize = 1024 * 1024;
/// What a search may hold at once: a few buffers of the reader and the decoder. The files are
/// 16 to 40 MiB, so a search that reads one whole (or decodes it whole) is far over.
const BOUND: usize = 4 * MIB;
fn query(context: SearchContext) -> SearchQuery {
SearchQuery {
pattern: "needle".into(),
is_regex: false,
case_sensitive: true,
whole_word: false,
include: vec![],
exclude: vec![],
scope: SearchScope::Project,
max_matches: 1_000_000,
context,
include_excluded: false,
}
}
/// Runs a search and returns its result with the most memory it held over what was live before.
fn measured(
root: &Path,
context: SearchContext,
literals: Option<Literals<'_>>,
) -> (Vec<FileMatches>, SearchSummary, usize) {
let out = Mutex::new(Vec::new());
let before = LIVE.load(Relaxed);
PEAK.store(before, Relaxed);
let summary = search_in_context(
root,
&query(context),
None,
literals,
TextSource::detected(&|_| None),
&CancellationToken::new(),
&|f| out.lock().unwrap().push(f),
)
.unwrap();
let held = PEAK.load(Relaxed).saturating_sub(before);
// The results are in `out` and count against the search; they are small.
(out.into_inner().unwrap(), summary, held)
}
fn write_repeated(path: &Path, bom: &[u8], block: &[u8], size: usize) {
use std::io::Write;
let mut file = std::io::BufWriter::new(std::fs::File::create(path).unwrap());
file.write_all(bom).unwrap();
for _ in 0..size / block.len() + 1 {
file.write_all(block).unwrap();
}
}
fn utf16le(text: &str) -> Vec<u8> {
text.encode_utf16().flat_map(u16::to_le_bytes).collect()
}
#[test]
fn searching_a_big_file_holds_a_bounded_part_of_it() {
let block = "2026-11-22 13:00:01 INFO caf\u{e9} \u{4e2d}\u{6587} request ok\n".repeat(50)
+ "2026-11-22 13:00:02 ERROR needle marker found\n";
let latin_text = block.replace(['\u{4e2d}', '\u{6587}'], "x");
let (latin1, _, _) = encoding_rs::WINDOWS_1252.encode(&latin_text);
let (gbk, _, _) = encoding_rs::GBK.encode(&block);
let parsed = Mutex::new(Vec::new());
let literals = |path: &Path, _: &str| {
parsed.lock().unwrap().push(path.file_name().unwrap().to_string_lossy().into_owned());
None
};
let dir = tempfile::tempdir().unwrap();
let mut expected = Vec::new();
for (name, bom, bytes, size) in [
("latin1.log", &b""[..], &latin1[..], 16 * MIB),
("gbk.log", &b""[..], &gbk[..], 16 * MIB),
("utf16.log", &[0xFF, 0xFE][..], &utf16le(&block)[..], 24 * MIB),
("utf8.log", &b""[..], block.as_bytes(), 40 * MIB),
] {
let one = tempfile::tempdir_in(dir.path()).unwrap();
write_repeated(&one.path().join(name), bom, bytes, size);
// Plain search: the byte search, then the decoded search of a non-UTF-8 file.
let (files, summary, held) = measured(one.path(), SearchContext::Any, None);
assert_eq!(files.len(), 1, "{name}");
assert!(summary.matches > 100, "{name}");
assert!(held < BOUND, "{name}: plain search held {} MiB", held / MIB);
expected.push((name, summary.matches, one));
}
// Searching with a context reads a file whole only to find its comments and strings, and
// past the parser's limit it has none: the file is searched as it is read.
for (name, matches, one) in &expected {
for context in [SearchContext::ExceptComments, SearchContext::ExceptCommentsAndStringLiterals] {
let (files, summary, held) = measured(one.path(), context, Some(&literals));
if *name == "utf8.log" {
assert_eq!(summary.matches, *matches, "{name} {context:?}");
assert_eq!(files.len(), 1);
assert!(held < BOUND, "{name}: {context:?} held {} MiB", held / MIB);
}
}
}
let (_, only_in, held) = measured(expected[3].2.path(), SearchContext::InComments, Some(&literals));
assert_eq!(only_in.matches, 0, "a file without comments has no match in them");
assert!(held < BOUND, "held {} MiB", held / MIB);
let parsed = parsed.into_inner().unwrap();
assert!(parsed.iter().any(|name| name == "gbk.log"), "files within the limit are still analysed");
assert!(!parsed.iter().any(|name| name == "utf8.log"), "a 40 MiB text is never handed to the parser");
}
+2 -1
View File
@@ -890,7 +890,8 @@ fn non_utf8_files_use_the_given_decoder() {
// Text too short to detect reliably decodes with the configured encoding.
let p = project(&[("a.txt", &gbk("中文\n"))]);
let out = Mutex::new(Vec::new());
let source = TextSource { overlay: &|_| None, fallback: &|_| Some("gbk".into()) };
let decode = |_: &Path, bytes: &[u8]| ide_vfs::decode_text(bytes, Some("gbk"));
let source = TextSource { overlay: &|_| None, decode: &decode };
ide_search::search_in_context(p.path(), &query("中文"), None, None, source, &CancellationToken::new(), &|f| {
out.lock().unwrap().push(f)
})
-200
View File
@@ -1,200 +0,0 @@
//! Files that are not UTF-8 are decoded while they are searched. Searching the text decoded whole
//! (what an unsaved editor buffer of the file is) is the reference: the matches must be the same.
use ide_core::CancellationToken;
use ide_search::{FileMatches, SearchQuery, SearchScope, SearchSummary, TextSource, search_in_context};
use std::path::Path;
use std::sync::Mutex;
fn query(pattern: &str, is_regex: bool) -> SearchQuery {
SearchQuery {
pattern: pattern.into(),
is_regex,
case_sensitive: false,
whole_word: false,
include: vec![],
exclude: vec![],
scope: SearchScope::Project,
max_matches: 1_000_000,
context: Default::default(),
include_excluded: false,
}
}
fn run(root: &Path, q: &SearchQuery, source: TextSource<'_>) -> (Vec<FileMatches>, SearchSummary) {
let out = Mutex::new(Vec::new());
let summary =
search_in_context(root, q, None, None, source, &CancellationToken::new(), &|f| out.lock().unwrap().push(f))
.unwrap();
let mut files = out.into_inner().unwrap();
files.sort_by(|a, b| a.rel_path.cmp(&b.rel_path));
(files, summary)
}
/// The matches of every file in `root`, read from disk and from its whole decoded text.
fn both_ways(root: &Path, q: &SearchQuery, fallback: Option<&str>) -> (String, String) {
let streamed = run(root, q, TextSource { overlay: &|_| None, fallback: &|_| fallback.map(str::to_owned) });
let whole = run(
root,
q,
TextSource {
overlay: &|path| ide_vfs::decode_text(&std::fs::read(path).unwrap(), fallback),
fallback: &|_| None,
},
);
let show = |(files, summary): (Vec<FileMatches>, SearchSummary)| {
format!("{:#?}\nmatches {} limit {}", files, summary.matches, summary.limit_hit)
};
(show(streamed), show(whole))
}
fn first_difference(a: &str, b: &str) -> String {
let (a, b): (Vec<_>, Vec<_>) = (a.lines().collect(), b.lines().collect());
let at = a.iter().zip(&b).take_while(|(x, y)| x == y).count();
format!(
"line {at}:\nstreamed {:?}\nwhole {:?}",
&a[at.saturating_sub(3)..a.len().min(at + 3)],
&b[at.saturating_sub(3)..b.len().min(at + 3)]
)
}
fn utf16(text: &str, bom: bool, big: bool) -> Vec<u8> {
let mut bytes = if bom { vec![if big { 0xFE } else { 0xFF }, if big { 0xFF } else { 0xFE }] } else { Vec::new() };
for unit in text.encode_utf16() {
bytes.extend(if big { unit.to_be_bytes() } else { unit.to_le_bytes() });
}
bytes
}
/// Lines of mixed width: ASCII, accents, CJK, astral characters (surrogate pairs), CRLF.
fn lines(count: usize) -> String {
let mut text = String::new();
for i in 0..count {
match i % 6 {
0 => text.push_str(&format!("{i} needle in plain ascii\n")),
1 => text.push_str(&format!("{i} caf\u{e9} needle cr\u{e8}me\n")),
2 => text.push_str(&format!("{i} \u{4e2d}\u{6587} needle \u{6d4b}\u{8bd5}\n")),
3 => text.push_str(&format!("{i} \u{1f600} needle \u{1f4a9}\n")),
4 => text.push_str(&format!("{i} crlf needle\r\n")),
_ => text.push_str(&format!("{i} nothing here\n")),
}
}
text
}
fn write(dir: &Path, name: &str, bytes: &[u8]) {
std::fs::write(dir.join(name), bytes).unwrap();
}
#[test]
fn decoded_files_give_the_matches_of_their_whole_text() {
let wide = lines(12_000);
let gbk_text = wide.replace(['\u{1f600}', '\u{1f4a9}', '\u{e9}', '\u{e8}'], "");
let latin_text = wide.replace(|c: char| c as u32 > 0xff, "");
let dir = tempfile::tempdir().unwrap();
// (BOM-less UTF-16 is not searched in decoded text, and not covered here: only the byte search sees it.)
// Each file is well past the sizes the decoder reads at a time (64 KiB).
assert!(wide.len() > 250_000);
write(dir.path(), "utf16le_bom.txt", &utf16(&wide, true, false));
write(dir.path(), "utf16be_bom.txt", &utf16(&wide, true, true));
write(dir.path(), "gbk.txt", &encoding_rs::GBK.encode(&gbk_text).0);
write(dir.path(), "latin1.txt", &encoding_rs::WINDOWS_1252.encode(&latin_text).0);
write(dir.path(), "utf8.txt", wide.as_bytes());
let queries = [
query("needle", false),
query("caf\u{e9}", false),
query("\u{1f600}", false),
query("\u{4e2d}\u{6587} needle", false),
query(r"\d+ \S+ needle", true),
query(r"needle\r?$", true),
// A multi-line pattern reads the whole text, however it arrives.
query("needle in plain ascii\n1 caf", false),
SearchQuery { case_sensitive: true, whole_word: true, ..query("needle", false) },
];
for q in &queries {
for fallback in [None, Some("gbk"), Some("windows-1252")] {
let (streamed, whole) = both_ways(dir.path(), q, fallback);
assert!(
streamed == whole,
"{:?} fallback {fallback:?}\n{}",
q.pattern,
first_difference(&streamed, &whole)
);
assert!(streamed.len() > 100, "{:?} found nothing", q.pattern);
}
}
// The match limit keeps the first matches of a file, and files take their share in any order:
// one file at a time.
for name in ["utf16le_bom.txt", "utf16be_bom.txt", "gbk.txt", "latin1.txt"] {
for max_matches in [7, 64, 65, 5_000] {
let q = SearchQuery { max_matches, include: vec![name.into()], ..query("needle", false) };
let (streamed, whole) = both_ways(dir.path(), &q, None);
assert!(streamed == whole, "{name} limit {max_matches}\n{}", first_difference(&streamed, &whole));
assert!(streamed.contains(&format!("matches {max_matches} limit true")), "{name} {max_matches}");
}
}
}
#[test]
fn decoded_files_keep_their_multibyte_characters_across_every_read_boundary() {
// A character sits on each of the 64 KiB read boundaries, at all alignments.
let dir = tempfile::tempdir().unwrap();
for pad in 0..8usize {
let mut gbk = "x".repeat(64 * 1024 - 5 + pad);
let mut utf16_text = gbk.clone();
for i in 0..40 {
gbk.push_str("\u{4e2d}\u{6587}");
utf16_text.push_str(if i % 2 == 0 { "\u{1f600}" } else { "\u{4e2d}" });
gbk.push_str(&"y".repeat(i % 3));
utf16_text.push_str(&"y".repeat(i % 3));
}
gbk.push_str("yy needle\n");
utf16_text.push_str("yy needle\n");
write(dir.path(), &format!("gbk{pad}.txt"), &encoding_rs::GBK.encode(&gbk).0);
write(dir.path(), &format!("utf16_{pad}.txt"), &utf16(&utf16_text, true, pad % 2 == 0));
write(
dir.path(),
&format!("latin{pad}.txt"),
&[gbk.as_bytes()[..64 * 1024 - 7 + pad].to_vec(), b"\xe9\xe8 needle\n".to_vec()].concat(),
);
}
for pattern in ["needle", "y+ needle", "\u{4e2d}\u{6587}"] {
let q = query(pattern, pattern.contains('+'));
let (streamed, whole) = both_ways(dir.path(), &q, None);
assert!(streamed == whole, "{pattern}\n{}", first_difference(&streamed, &whole));
assert!(streamed.len() > 100, "{pattern} found nothing");
}
}
#[test]
fn nul_characters_in_decoded_text_mark_it_binary_as_in_the_whole_text() {
// Text held whole is binary when a NUL is in its first 64 KiB or in a line that matches,
// which is not the same as a NUL anywhere.
let text = lines(20_000);
let with_nul = |at: &str| text.replacen(at, &format!("\0{at}"), 1);
let cases = [
("early", with_nul("5 nothing here"), false),
("late in a line that does not match", with_nul("19997 nothing here"), true),
("late in a line that matches", with_nul("19998 needle"), false),
];
for (name, text, found) in cases {
let dir = tempfile::tempdir().unwrap();
write(dir.path(), "a.txt", &utf16(&text, true, false));
let (streamed, whole) = both_ways(dir.path(), &query("needle", false), None);
assert!(streamed == whole, "{name}\n{}", first_difference(&streamed, &whole));
assert_eq!(streamed.contains("a.txt"), found, "{name}");
}
}
#[test]
fn a_file_is_decoded_when_its_search_reaches_the_byte_that_is_not_utf8() {
// Valid UTF-8 up to the last line: the whole file is read as the detected Windows-1252.
let dir = tempfile::tempdir().unwrap();
write(dir.path(), "late.txt", &[lines(1500).as_bytes(), b"caf\xe9 needle\n"].concat());
for q in [query("needle", false), query("caf", false)] {
let (streamed, whole) = both_ways(dir.path(), &q, None);
assert!(streamed == whole, "{}", first_difference(&streamed, &whole));
assert!(streamed.contains("café"), "decoded as Windows-1252");
}
}
-22
View File
@@ -81,12 +81,6 @@ 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))
@@ -106,8 +100,6 @@ 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)
};
@@ -249,20 +241,6 @@ 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() {
+5 -15
View File
@@ -478,11 +478,12 @@ pub(crate) fn log(r: &Repo, q: &LogQuery, cancel: &CancellationToken) -> IdeResu
all.request = None;
all.stop_at = None;
let repo = r.gix()?;
let (decorations, generation) = r.ref_decorations(&repo)?;
let decorations = 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 key = format!("{}:{generation}:{shallow_vec:?}", serde_json::to_string(&all).map_err(gx)?);
let refs = r.log_refs()?;
let key = format!("{}:{refs:?}:{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
@@ -645,7 +646,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, _) = r.ref_decorations(&repo)?;
let decorations = 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();
@@ -740,7 +741,7 @@ fn log_indexed_rows(
if tips.is_empty() && range.is_none() && ranges.is_empty() {
return Ok(Vec::new());
}
let (decorations, _) = r.ref_decorations(&repo)?;
let decorations = decorations(&repo)?;
let paths: Vec<String> = q
.path
.iter()
@@ -1405,19 +1406,8 @@ 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());
+5 -5
View File
@@ -939,7 +939,6 @@ 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;
@@ -1079,7 +1078,6 @@ 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>>,
@@ -1139,9 +1137,11 @@ 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 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.
// 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);
}
if paths.is_empty() {
return status::status_paths(self, &[]);
}
-264
View File
@@ -1,264 +0,0 @@
//! 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"]);
}
}
-1
View File
@@ -88,7 +88,6 @@ 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(),
-56
View File
@@ -583,60 +583,4 @@ 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");
}
}
+2 -11
View File
@@ -591,17 +591,8 @@ fn select_into(
encoding: &dyn Fn(&Path) -> IdeResult<TextEncoding>,
) -> IdeResult<Vec<String>> {
let index = r.git_dir.join("index");
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()),
if index.exists() {
std::fs::copy(&index, &tmp.0)?;
}
let env = [("GIT_INDEX_FILE", tmp.0.as_os_str())];
fill_commit_index(r, &env, options, encoding)
-9
View File
@@ -2017,17 +2017,11 @@ 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) };
@@ -2038,9 +2032,6 @@ 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();
-366
View File
@@ -1,366 +0,0 @@
//! [`decode_text`](crate::decode_text) for files too large to hold: the same
//! decisions, taken while reading a chunk at a time.
use crate::encoding::{SNIFF_LEN, sniff_utf16};
use encoding_rs::{Decoder, Encoding, UTF_8, UTF_16BE, UTF_16LE};
use std::io::{self, Read};
/// Raw bytes read per step; a step holds this plus its UTF-8 expansion (at most 3x).
const CHUNK: usize = 64 * 1024;
/// The text of a file as UTF-8 bytes, decoded as it is read.
pub struct DecodedReader<R> {
reader: R,
decoder: Decoder,
raw: Vec<u8>,
/// Decoded bytes of the last step; `out[pos..len]` is unread.
out: Vec<u8>,
pos: usize,
len: usize,
done: bool,
}
/// Decodes the file `open` reads like [`decode_text`](crate::decode_text) does (BOM, UTF-8 and
/// UTF-16 as detected, other text as `fallback` or else the detected encoding) without holding
/// it: `None` for binary content, else a reader of the text as UTF-8.
///
/// Deciding the encoding of text that is neither BOM-marked nor UTF-8 needs a pass over the whole
/// file before the decoding pass, so `open` gives a fresh reader of the file up to twice.
pub fn decode_stream<R: Read>(
open: impl FnMut() -> io::Result<R>,
fallback: Option<&str>,
) -> io::Result<Option<DecodedReader<R>>> {
decode_stream_in(open, fallback, CHUNK)
}
fn decode_stream_in<R: Read>(
mut open: impl FnMut() -> io::Result<R>,
fallback: Option<&str>,
chunk: usize,
) -> io::Result<Option<DecodedReader<R>>> {
let Some((detected, bom_len, has_bom)) = detect(&mut open, chunk)? else { return Ok(None) };
let fallback = fallback.and_then(|label| Encoding::for_label(label.trim().as_bytes()));
let encoding = match fallback {
Some(enc)
if !has_bom && enc != detected && detected != UTF_8 && detected != UTF_16LE && detected != UTF_16BE =>
{
enc
}
_ => detected,
};
let mut reader = open()?;
io::copy(&mut (&mut reader).take(bom_len as u64), &mut io::sink())?;
let decoder = encoding.new_decoder_without_bom_handling();
let out = vec![0; decoder.max_utf8_buffer_length(chunk).unwrap_or(chunk * 3)];
Ok(Some(DecodedReader { reader, decoder, raw: vec![0; chunk], out, pos: 0, len: 0, done: false }))
}
/// The encoding [`decode`](crate::encoding::decode) finds for the file, its BOM length and
/// whether it has a BOM; `None` for binary content.
fn detect<R: Read>(
open: &mut impl FnMut() -> io::Result<R>,
chunk: usize,
) -> io::Result<Option<(&'static Encoding, usize, bool)>> {
let mut reader = open()?;
let mut head = vec![0; SNIFF_LEN];
let n = read_full(&mut reader, &mut head)?;
head.truncate(n);
if let Some((enc, bom_len)) = Encoding::for_bom(&head) {
return Ok(Some((enc, bom_len, true)));
}
if head.contains(&0) {
return Ok(sniff_utf16(&head).map(|enc| (enc, 0, false)));
}
let mut detector = chardetng::EncodingDetector::new();
let mut utf8 = Utf8Check::default();
detector.feed(&head, false);
utf8.feed(&head);
if n == SNIFF_LEN {
let mut buf = vec![0; chunk];
loop {
let n = read_retry(&mut reader, &mut buf)?;
if n == 0 {
break;
}
detector.feed(&buf[..n], false);
utf8.feed(&buf[..n]);
}
}
detector.feed(&[], true);
let encoding = if utf8.is_valid() { UTF_8 } else { detector.guess(None, true) };
Ok(Some((encoding, 0, false)))
}
/// Reads until `buf` is full or the reader ends.
fn read_full(reader: &mut impl Read, buf: &mut [u8]) -> io::Result<usize> {
let mut filled = 0;
while filled < buf.len() {
match read_retry(reader, &mut buf[filled..])? {
0 => break,
n => filled += n,
}
}
Ok(filled)
}
fn read_retry(reader: &mut impl Read, buf: &mut [u8]) -> io::Result<usize> {
loop {
match reader.read(buf) {
Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
result => return result,
}
}
}
/// Checks that bytes fed in pieces form valid UTF-8, as `std::str::from_utf8` does for the whole.
#[derive(Default)]
struct Utf8Check {
/// The start of a character cut by the end of the previous piece.
tail: Vec<u8>,
invalid: bool,
}
impl Utf8Check {
fn feed(&mut self, mut bytes: &[u8]) {
if self.invalid {
return;
}
while !self.tail.is_empty() && !bytes.is_empty() {
self.tail.push(bytes[0]);
bytes = &bytes[1..];
match std::str::from_utf8(&self.tail) {
Ok(_) => self.tail.clear(),
Err(e) if e.error_len().is_none() => {}
Err(_) => {
self.invalid = true;
return;
}
}
}
if !self.tail.is_empty() {
return;
}
match std::str::from_utf8(bytes) {
Ok(_) => {}
Err(e) if e.error_len().is_none() => self.tail.extend_from_slice(&bytes[e.valid_up_to()..]),
Err(_) => self.invalid = true,
}
}
/// Whether everything fed so far was UTF-8 (a truncated final character is not).
fn is_valid(&self) -> bool {
!self.invalid && self.tail.is_empty()
}
}
impl<R: Read> Read for DecodedReader<R> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
while self.pos == self.len {
if self.done {
return Ok(0);
}
let n = read_retry(&mut self.reader, &mut self.raw)?;
let last = n == 0;
let needed = self.decoder.max_utf8_buffer_length(n).unwrap_or(n * 3 + 16);
if self.out.len() < needed {
self.out.resize(needed, 0);
}
// Malformed input becomes U+FFFD, as in `decode_without_bom_handling`.
let (_, _, written, _) = self.decoder.decode_to_utf8(&self.raw[..n], &mut self.out, last);
self.pos = 0;
self.len = written;
self.done = last;
}
let n = buf.len().min(self.len - self.pos);
buf[..n].copy_from_slice(&self.out[self.pos..self.pos + n]);
self.pos += n;
Ok(n)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::decode_text;
/// Hands out at most `step` bytes per read, so chunk edges fall everywhere.
struct Trickle<'a> {
bytes: &'a [u8],
step: usize,
}
impl Read for Trickle<'_> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
let n = buf.len().min(self.step).min(self.bytes.len());
buf[..n].copy_from_slice(&self.bytes[..n]);
self.bytes = &self.bytes[n..];
Ok(n)
}
}
fn streamed(bytes: &[u8], fallback: Option<&str>, chunk: usize, step: usize) -> Option<Vec<u8>> {
let reader = decode_stream_in(|| Ok(Trickle { bytes, step }), fallback, chunk).unwrap()?;
let mut out = Vec::new();
let mut reader = reader;
// Small reads too: the consumer's buffer is not the chunk either.
let mut buf = [0; 7];
loop {
let n = reader.read(&mut buf).unwrap();
if n == 0 {
return Some(out);
}
out.extend_from_slice(&buf[..n]);
}
}
fn utf16(text: &str, bom: bool, big: bool) -> Vec<u8> {
let mut bytes =
if bom { vec![if big { 0xFE } else { 0xFF }, if big { 0xFF } else { 0xFE }] } else { Vec::new() };
for unit in text.encode_utf16() {
bytes.extend(if big { unit.to_be_bytes() } else { unit.to_le_bytes() });
}
bytes
}
/// Text with multi-byte characters and surrogate pairs at every alignment.
fn sample(len: usize) -> String {
let mut text = String::new();
let pieces = [
"ascii line\n",
"caf\u{e9} cr\u{e8}me\n",
"\u{4e2d}\u{6587}\u{6d4b}\u{8bd5}\n",
"\u{1f600}\u{1f4a9} x\n",
"\u{20ac}5\r\n",
];
let mut i = 0;
while text.len() < len {
text.push_str(pieces[i * 7 % pieces.len()]);
i += 1;
}
text
}
fn inputs() -> Vec<(String, Vec<u8>)> {
let text = sample(1500);
let mut inputs = vec![
("utf8".to_string(), text.clone().into_bytes()),
("utf8 bom".to_string(), [&[0xEF, 0xBB, 0xBF][..], text.as_bytes()].concat()),
("utf16le bom".to_string(), utf16(&text, true, false)),
("utf16be bom".to_string(), utf16(&text, true, true)),
("utf16le".to_string(), utf16(&sample(1500).replace(|c: char| !c.is_ascii(), "e"), false, false)),
("utf16be".to_string(), utf16(&sample(1500).replace(|c: char| !c.is_ascii(), "e"), false, true)),
(
"gbk".to_string(),
encoding_rs::GBK
.encode(&sample(1500).replace(['\u{1f600}', '\u{1f4a9}', '\u{20ac}'], ""))
.0
.into_owned(),
),
(
"latin1".to_string(),
encoding_rs::WINDOWS_1252
.encode(&sample(1500).replace(|c: char| c as u32 > 0xff && c != '\u{20ac}', ""))
.0
.into_owned(),
),
("empty".to_string(), Vec::new()),
("binary".to_string(), b"\x7FELF\x02\x01\x01\x00\x00\x00 and text".repeat(100)),
("late nul".to_string(), [&b"abc caf\xe9 ".repeat(1200)[..], b"\0 tail"].concat()),
("truncated utf8".to_string(), text.as_bytes()[..text.len() - 1].to_vec()),
("truncated utf16".to_string(), utf16(&text, true, false)[..utf16(&text, true, false).len() - 1].to_vec()),
(
"lone surrogate".to_string(),
[&[0xFF, 0xFE][..], &[0x3D, 0xD8, b'a', 0][..], &utf16(&text, false, false)[..]].concat(),
),
("invalid in the middle".to_string(), [text.as_bytes(), b"\xff\xfe\xc3", text.as_bytes()].concat()),
(
"shift jis".to_string(),
encoding_rs::SHIFT_JIS
.encode(
"\u{3053}\u{3093}\u{306b}\u{3061}\u{306f}\u{4e16}\u{754c}\u{ff76}\u{ff85}\n"
.repeat(200)
.as_str(),
)
.0
.into_owned(),
),
];
// The evidence for the encoding comes long after the sniffed head.
let chinese = "\u{4e2d}\u{6587}\u{6d4b}\u{8bd5}\u{4e00}\u{6bb5}\u{6587}\u{672c}\n".repeat(300);
let gbk = encoding_rs::GBK.encode(&chinese).0.into_owned();
let head = "plain ascii line\n".repeat(1500);
inputs.push(("gbk after a long ascii head".to_string(), [head.as_bytes(), &gbk].concat()));
// Characters at every alignment against the sniffing head and the chunks.
for pad in 0..5 {
let mut bytes = "x".repeat(SNIFF_LEN - 3 + pad).into_bytes();
bytes.extend("\u{4e2d}\u{1f600}\u{e9}".as_bytes());
inputs.push((format!("utf8 at the head edge {pad}"), bytes));
let mut bytes = "y".repeat(SNIFF_LEN - 2 + pad).into_bytes();
bytes.extend([0xE9, b'z', 0xFF, b'e']);
inputs.push((format!("latin1 at the head edge {pad}"), bytes));
}
inputs
}
#[test]
fn streamed_text_equals_the_whole_file_decode() {
for (name, bytes) in inputs() {
for fallback in [None, Some("gbk"), Some("windows-1252"), Some("utf-16le"), Some("nonsense")] {
let expected = decode_text(&bytes, fallback).map(String::into_bytes);
for chunk in [1, 2, 3, 4, 5, 16, 255, 4096, CHUNK] {
for step in [1, 3, 8192, usize::MAX] {
assert_eq!(
streamed(&bytes, fallback, chunk, step),
expected,
"{name}, fallback {fallback:?}, chunk {chunk}, step {step}"
);
}
}
}
}
}
#[test]
fn utf8_check_matches_from_utf8_for_any_split() {
let samples: [&[u8]; 6] = [
"a\u{e9}\u{4e2d}\u{1f600}z".as_bytes(),
b"ab\xe4\xb8",
b"\xe4\xb8a",
b"\xf0\x9f\x98",
b"ok\xc3(",
b"\xed\xa0\x80",
];
for bytes in samples {
for first in 0..=bytes.len() {
for second in first..=bytes.len() {
let mut check = Utf8Check::default();
check.feed(&bytes[..first]);
check.feed(&bytes[first..second]);
check.feed(&bytes[second..]);
assert_eq!(check.is_valid(), std::str::from_utf8(bytes).is_ok(), "{bytes:?} {first} {second}");
}
}
}
}
#[test]
fn reads_at_most_a_bounded_number_of_bytes_per_step() {
// A reader that fails if asked for more than one chunk shows nothing is read whole.
struct Capped<'a>(&'a [u8]);
impl Read for Capped<'_> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
assert!(buf.len() <= SNIFF_LEN.max(1024), "asked for {} bytes", buf.len());
let n = buf.len().min(self.0.len());
buf[..n].copy_from_slice(&self.0[..n]);
self.0 = &self.0[n..];
Ok(n)
}
}
let bytes = encoding_rs::WINDOWS_1252.encode(&"caf\u{e9}\n".repeat(50_000)).0.into_owned();
let mut reader = decode_stream_in(|| Ok(Capped(&bytes)), None, 1024).unwrap().unwrap();
let mut text = String::new();
reader.read_to_string(&mut text).unwrap();
assert_eq!(text, "caf\u{e9}\n".repeat(50_000));
assert!(reader.out.len() <= 4 * 1024 + 16 && reader.raw.len() == 1024);
}
}
+1 -1
View File
@@ -103,7 +103,7 @@ pub fn save_properties_text(path: &Path, text: &str) -> IdeResult<f64> {
}
/// Detects BOM-less UTF-16 from the distribution of NUL bytes in mostly-ASCII text.
pub(crate) fn sniff_utf16(sample: &[u8]) -> Option<&'static Encoding> {
fn sniff_utf16(sample: &[u8]) -> Option<&'static Encoding> {
if sample.len() < 4 {
return None;
}
-2
View File
@@ -3,7 +3,6 @@
mod archive;
mod bytes;
mod compare;
mod decode_stream;
mod encoding;
mod ops;
mod private;
@@ -31,7 +30,6 @@ pub use compare::{
DirectoryCompareEntry, DirectoryCompareMode, DirectoryCompareProgress, DirectoryCompareStatus, DirectorySyncAction,
DirectorySyncFailure, DirectorySyncOperation, DirectorySyncProgress, compare_directories, copy_merge,
};
pub use decode_stream::{DecodedReader, decode_stream};
use encoding::SNIFF_LEN;
pub use encoding::{
LARGE_FILE_THRESHOLD, MAX_OPEN_SIZE, READ_ONLY_THRESHOLD, decode_properties_escapes, encode,
+1 -2
View File
@@ -1753,8 +1753,7 @@ 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());
let excluded = root.join("node_modules");
assert!(!paths.iter().any(|p| p != &excluded && p.starts_with(&excluded)), "{paths:?}");
assert!(!paths.iter().any(|p| p.starts_with(root.join("node_modules"))), "{paths:?}");
assert!(!paths.contains(&root.join("lib/out/o.txt")));
// Un-ignoring lib/out keeps its existing filename watch.
+3 -3
View File
@@ -125,16 +125,16 @@ Tasks are saved per project and survive restarts. When the agent supports resumi
## Manage agents
**Settings › Agents › Agent Setup** (also **More Agents…** in the agent picker) lists built-in agents and agents from the ACP Registry.
**Settings › Tools › Agents** (also **More Agents…** in the agent picker) has two tabs:
- **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 › 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 › 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**.
### External MCP servers
**Settings › Agents › MCP Connections** configures MCP servers across three persistent levels, while the composer's **MCP** picker (or `/mcp`) controls them per session:
**Settings › Agents › External MCP Servers** 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.
-1
View File
@@ -69,7 +69,6 @@ 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**.
+1 -1
View File
@@ -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 › MCP Connections**, 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 › External MCP Servers**, and again after its definition changes.
## File format
+3 -3
View File
@@ -125,16 +125,16 @@ agent 运行过一个任务后,新任务会以它自动批准所有操作的
## 管理 agent
**设置 › 智能体 › 智能体配置**(也可以在 agent 选择器中点 **更多 Agent…**)列出了内置智能体和 ACP Registry 提供的智能体。
**设置 › 工具 › 智能体**(也可以在 agent 选择器中点 **更多 Agent…**)有两个标签页:
- **内置**:每个内置 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 外部写入的项目服务器在批准启用前保持关闭。
-1
View File
@@ -69,7 +69,6 @@ OpenIDEA 通过 `docker` 命令行操作 Docker,所以只要能提供可用的
选中某项后,详情区会显示以下标签页:
- **Compose 项目**:**仪表盘**(项目概览、各服务的实时资源使用情况、该项目创建的命名卷)。
- **容器**:**仪表盘**(概览、实时资源使用情况、可在浏览器中打开的端口绑定、挂载、网络、环境变量、标签)、**日志**(最近 1,000 行,容器运行时持续跟随,可切换 **时间戳**)、**进程**(`docker top`)和 **检查**(原始 JSON)。
- **镜像**:**仪表盘**(标签、使用它的容器、环境变量、标签)、**镜像层** 和 **检查**。
- **卷** 和 **网络**:**仪表盘** 和 **检查**。
+1 -1
View File
@@ -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 服务器** 中将其开启;服务器定义改变后也需要重新开启。
## 文件格式
-57
View File
@@ -131,60 +131,3 @@ 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 });
});
+4 -8
View File
@@ -308,15 +308,11 @@ 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 › Agents › MCP Connections.
await sessionPopup.getByRole("button", { name: "MCP Connections…", exact: true }).click();
// 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();
const settingsDialog = page.getByRole("dialog", { name: "Settings", exact: true });
await expect(settingsDialog).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",
);
await expect(settingsDialog.getByRole("heading", { name: "External MCP Servers" })).toBeVisible();
// Probe `github-mcp-server` and inspect discovered tools inside the expandable card.
await settingsDialog.getByRole("button", { name: "Test github-mcp-server" }).click();
@@ -325,7 +321,7 @@ test("manages multi-level MCP servers in Settings and per-session overrides via
if (screenshotDir) {
await settingsDialog
.getByRole("heading", { name: "MCP Connections", exact: true })
.getByRole("heading", { name: "External MCP Servers" })
.evaluate((el) => el.scrollIntoView({ block: "start" }));
await settingsDialog.screenshot({ path: `${screenshotDir}/mcp-hub-levels.png` });
await settingsDialog.getByRole("button", { name: "Add from JSON" }).click();
-111
View File
@@ -1,111 +0,0 @@
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();
});
}
-1
View File
@@ -274,7 +274,6 @@ 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) => {
-52
View File
@@ -1,52 +0,0 @@
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);
});
+7 -68
View File
@@ -1,12 +1,11 @@
import type { Page } from "@playwright/test";
import { expect, PROJECT, stubDesktop, test } from "./fixtures";
import { expect, stubDesktop, test } from "./fixtures";
async function importCoverage(page: Page, width: number) {
test("Coverage keeps sortable statistics aligned next to the file tree at sidebar widths", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 1050, height: 550 });
await expect(page.getByRole("tree", { name: "Project" }).getByRole("treeitem", { name: PROJECT })).toBeVisible();
await expect(page.locator("#splash")).toHaveCount(0);
await stubDesktop(page);
await page.evaluate(async (width) => {
await page.evaluate(async () => {
const projectModule = "/src/platform/project.ts";
const actionsModule = "/src/platform/actions.ts";
const layoutModule = "/src/workbench/toolwindows/store.ts";
@@ -27,15 +26,10 @@ async function importCoverage(page: Page, width: number) {
hasBranches: path === "/tmp/coverage.lcov",
files,
});
setToolWindowSize("right", width);
setToolWindowSize("right", 280);
await executeAction("coverage.importReport", "/tmp/coverage.lcov");
}, width);
}
});
test("Coverage keeps sortable statistics aligned next to the file tree at sidebar widths", async ({
workbench: page,
}) => {
await importCoverage(page, 280);
const coverage = page.getByRole("region", { name: "Coverage", exact: true });
const tree = coverage.getByRole("tree", { name: "Coverage" });
const line = coverage.getByRole("columnheader", { name: "Line, %" });
@@ -76,58 +70,3 @@ test("Coverage keeps sortable statistics aligned next to the file tree at sideba
await expect(line).toBeVisible();
expect((await ready.getByTitle("100% (20/20)").boundingBox())!.x).toBeCloseTo((await line.boundingBox())!.x, 0);
});
test("Coverage column widths follow the dividers and survive a narrower dock and reload", async ({
workbench: page,
}) => {
await importCoverage(page, 460);
const coverage = page.getByRole("region", { name: "Coverage", exact: true });
const line = coverage.getByRole("columnheader", { name: "Line, %" });
const branch = coverage.getByRole("columnheader", { name: "Branch, %" });
const lineDivider = coverage.getByRole("separator", { name: "Resize Line, % column" });
const branchDivider = coverage.getByRole("separator", { name: "Resize Branch, % column" });
const ready = coverage.getByRole("treeitem", { name: /^Ready\.ts/ });
const nameHeader = coverage.getByRole("columnheader", { name: "Element" });
await expect(lineDivider).toBeVisible();
const width = async (loc: typeof line) => (await loc.boundingBox())!.width;
const originalLine = await width(line);
const originalBranch = await width(branch);
const originalName = await width(nameHeader);
const drag = (await lineDivider.boundingBox())!;
await page.mouse.move(drag.x + drag.width / 2, drag.y + drag.height / 2);
await page.mouse.down();
await page.mouse.move(drag.x + drag.width / 2 + 32, drag.y + drag.height / 2, { steps: 4 });
await page.mouse.up();
await expect.poll(() => width(line)).toBeCloseTo(originalLine - 32, 0);
await expect.poll(() => width(nameHeader)).toBeCloseTo(originalName + 32, 0);
await expect.poll(() => width(branch)).toBeCloseTo(originalBranch, 0);
await expect(line).toHaveAttribute("aria-sort", "none");
await branchDivider.press("ArrowRight");
await expect.poll(() => width(branch)).toBeCloseTo(originalBranch - 10, 0);
await expect.poll(() => width(line)).toBeCloseTo(originalLine - 22, 0);
expect((await ready.getByTitle("100% (20/20)").boundingBox())!.x).toBeCloseTo((await line.boundingBox())!.x, 0);
const resizeDock = (size: number) =>
page.evaluate(async (size) => {
const layoutModule = "/src/workbench/toolwindows/store.ts";
const { setToolWindowSize } = await import(/* @vite-ignore */ layoutModule);
setToolWindowSize("right", size);
}, size);
await resizeDock(240);
await expect.poll(() => width(line)).toBeLessThan(originalLine - 22);
const tree = coverage.getByRole("tree", { name: "Coverage" });
await expect.poll(() => tree.evaluate((el) => el.scrollWidth - el.clientWidth)).toBe(0);
await expect(branchDivider).toBeInViewport({ ratio: 1 });
await resizeDock(460);
await expect.poll(() => width(line)).toBeCloseTo(originalLine - 22, 0);
await expect.poll(() => width(branch)).toBeCloseTo(originalBranch - 10, 0);
await page.reload();
await importCoverage(page, 460);
await expect.poll(() => width(line)).toBeCloseTo(originalLine - 22, 0);
await expect.poll(() => width(branch)).toBeCloseTo(originalBranch - 10, 0);
await branchDivider.dblclick();
await expect.poll(() => width(line)).toBeCloseTo(originalLine, 0);
await expect.poll(() => width(branch)).toBeCloseTo(originalBranch, 0);
});
-106
View File
@@ -1,106 +0,0 @@
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);
});
-124
View File
@@ -487,45 +487,6 @@ 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");
@@ -668,91 +629,6 @@ 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");
-52
View File
@@ -1,52 +0,0 @@
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"],
]);
});
-51
View File
@@ -1,51 +0,0 @@
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);
});
-44
View File
@@ -1,44 +0,0 @@
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);
});
-83
View File
@@ -1,83 +0,0 @@
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,
},
]);
});
+6 -39
View File
@@ -5,29 +5,14 @@ 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"],
"/work/tutor": ["package.json", "vite.config.ts"],
const markers: Record<string, string> = {
"/work/api": "go.mod",
"/work/web": "pom.xml",
"/work/library": "pom.xml",
};
window.__ipc.handlers.fs_read_dir = ({ path }) => {
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;
const name = markers[String(path)];
return name ? [{ name, path: `${path}/${name}`, kind: "file", size: 0, mtimeMs: 0 }] : [];
};
window.__ipc.handlers.run_configs = () => [
{
@@ -69,7 +54,6 @@ 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");
@@ -89,23 +73,6 @@ 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 }) => {
+2 -15
View File
@@ -37,15 +37,6 @@ 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" });
@@ -99,7 +90,6 @@ 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())!;
@@ -111,16 +101,13 @@ 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.clock.runFor(75);
await page.waitForTimeout(75);
await expect(parent).toHaveAttribute("aria-expanded", "true");
}
await page.clock.runFor(350);
await page.waitForTimeout(350);
await expect(parent).toHaveAttribute("aria-expanded", "true");
await page.clock.resume();
await page.keyboard.press("Escape");
await page.keyboard.press("Escape");
});
+2 -1
View File
@@ -12,8 +12,9 @@ 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({
scratchesDir: async () => "/test-app-data/scratches",
dataDir: async () => "/test-app-data",
listNames: async () => [],
createDir: async () => {},
createFile: async () => {},
languages: async () => [
...Array.from({ length: 24 }, (_, i) => {
+2 -5
View File
@@ -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 page.locator("header").getByRole("button", { name: "Search Everywhere", exact: true }).click();
await doubleShift(page);
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,10 +122,7 @@ 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.backgroundImage.includes(expected)) &&
own.color === getComputedStyle(el.parentElement!).color
);
return own.backgroundColor === expected && own.color === getComputedStyle(el.parentElement!).color;
}),
).toBe(true);
const originalPreview = await preview.textContent();
+1 -30
View File
@@ -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, ipcCalls, openFromTree, stubDesktop, test } from "./fixtures";
import { expect, openFromTree, stubDesktop, test } from "./fixtures";
const LONG_RESULT_PATH = "config/RegionalOrderReconciliationEndpointsForSandboxEnvironments.txt";
@@ -118,35 +118,6 @@ 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");
+1 -439
View File
@@ -1,5 +1,5 @@
import type { Page } from "@playwright/test";
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
import { expect, test } from "./fixtures";
/** Supply detected configurations without launching desktop processes. */
async function configure(page: Page, extra = 0) {
@@ -241,441 +241,3 @@ 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 });
});
-2
View File
@@ -385,8 +385,6 @@ 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);
-79
View File
@@ -1,79 +0,0 @@
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",
});
});
-88
View File
@@ -1,88 +0,0 @@
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
View File
@@ -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.6",
"@lezer/common": "^1.5.3",
"@lezer/highlight": "^1.2.5",
"@lezer/lr": "^1.4.11",
"@mathjax/mathjax-tex-font": "4.1.3",
+44 -44
View File
@@ -76,8 +76,8 @@ importers:
specifier: ^5.3.0
version: 5.3.0
'@lezer/common':
specifier: ^1.5.6
version: 1.5.6
specifier: ^1.5.3
version: 1.5.3
'@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].6':
resolution: {integrity: sha512-NZxu3q49ck+YYbEJPuIPIyFP37XneBvzPIarBHEXBLBVfkZqQieZ/Y2boYnGNYtmjpOZLnAKs/lwqtmDpi365w==}
'@lezer/[email protected].3':
resolution: {integrity: sha512-H0iErY4e43LpXbYDyBci5W4v/RwTgGV3YzYOlJPiGZ8RY8w51kVE+xLn1tg3Z6UmSfyETvtsUK3r7YsgDQEI7Q==}
'@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.6
'@lezer/common': 1.5.3
'@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.6
'@lezer/common': 1.5.3
'@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.6
'@lezer/common': 1.5.3
'@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.6
'@lezer/common': 1.5.3
'@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.6
'@lezer/common': 1.5.3
'@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.6
'@lezer/common': 1.5.3
'@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.6
'@lezer/common': 1.5.3
'@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.6
'@lezer/common': 1.5.3
'@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.6
'@lezer/common': 1.5.3
'@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.6
'@lezer/common': 1.5.3
'@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.6
'@lezer/common': 1.5.3
'@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.6
'@lezer/common': 1.5.3
'@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.6
'@lezer/common': 1.5.3
'@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.6
'@lezer/common': 1.5.3
'@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.6
'@lezer/common': 1.5.3
'@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.6
'@lezer/common': 1.5.3
'@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.6
'@lezer/common': 1.5.3
'@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.6
'@lezer/common': 1.5.3
'@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.6
'@lezer/common': 1.5.3
'@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.6
'@lezer/common': 1.5.3
'@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].6': {}
'@lezer/[email protected].3': {}
'@lezer/[email protected]':
dependencies:
'@lezer/common': 1.5.6
'@lezer/common': 1.5.3
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
'@lezer/[email protected]':
dependencies:
'@lezer/common': 1.5.6
'@lezer/common': 1.5.3
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
'@lezer/[email protected]':
dependencies:
'@lezer/common': 1.5.6
'@lezer/common': 1.5.3
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
'@lezer/[email protected]':
dependencies:
'@lezer/common': 1.5.6
'@lezer/common': 1.5.3
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
'@lezer/[email protected]':
dependencies:
'@lezer/common': 1.5.6
'@lezer/common': 1.5.3
'@lezer/[email protected]':
dependencies:
'@lezer/common': 1.5.6
'@lezer/common': 1.5.3
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
'@lezer/[email protected]':
dependencies:
'@lezer/common': 1.5.6
'@lezer/common': 1.5.3
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
'@lezer/[email protected]':
dependencies:
'@lezer/common': 1.5.6
'@lezer/common': 1.5.3
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
'@lezer/[email protected]':
dependencies:
'@lezer/common': 1.5.6
'@lezer/common': 1.5.3
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
'@lezer/[email protected](patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)':
dependencies:
'@lezer/common': 1.5.6
'@lezer/common': 1.5.3
'@lezer/[email protected]':
dependencies:
'@lezer/common': 1.5.6
'@lezer/common': 1.5.3
'@lezer/highlight': 1.2.5
'@lezer/[email protected]':
dependencies:
'@lezer/common': 1.5.6
'@lezer/common': 1.5.3
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
'@lezer/[email protected]':
dependencies:
'@lezer/common': 1.5.6
'@lezer/common': 1.5.3
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
'@lezer/[email protected]':
dependencies:
'@lezer/common': 1.5.6
'@lezer/common': 1.5.3
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
'@lezer/[email protected]':
dependencies:
'@lezer/common': 1.5.6
'@lezer/common': 1.5.3
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
'@lezer/[email protected]':
dependencies:
'@lezer/common': 1.5.6
'@lezer/common': 1.5.3
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
'@lezer/[email protected]':
dependencies:
'@lezer/common': 1.5.6
'@lezer/common': 1.5.3
'@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.6
'@lezer/common': 1.5.3
'@plutojl/lezer-julia': 1.2.0
'@plutojl/[email protected]':
dependencies:
'@lezer/common': 1.5.6
'@lezer/common': 1.5.3
'@lezer/highlight': 1.2.5
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
+7 -73
View File
@@ -155,23 +155,6 @@ 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!(
@@ -197,12 +180,13 @@ impl EventSink for TauriSink {
}
let result = match &self.window {
Some(label) => {
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))
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)
}
None => self.app.emit(IDE_EVENT, &event),
};
@@ -256,56 +240,6 @@ 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();
-1
View File
@@ -286,7 +286,6 @@ 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
-7
View File
@@ -707,11 +707,6 @@ 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.
@@ -2534,8 +2529,6 @@ 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. */
+2 -10
View File
@@ -238,13 +238,11 @@ 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",
minHeight: "16px",
height: "16px",
color: "var(--fg-inlay, var(--fg-muted))",
WebkitUserSelect: "none",
userSelect: "none",
@@ -278,10 +276,7 @@ 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)",
// 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",
overflow: "hidden",
pointerEvents: "auto",
},
".cm-openidea-lensItem": {
@@ -298,9 +293,6 @@ 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)" },
-74
View File
@@ -417,79 +417,6 @@ 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
@@ -502,7 +429,6 @@ 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)
-29
View File
@@ -67,7 +67,6 @@ 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", () => {
@@ -95,34 +94,6 @@ 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,7 +2,6 @@ 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(
@@ -26,63 +25,3 @@ 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(),
);
}
});
});
-37
View File
@@ -1,37 +0,0 @@
/**
* 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(", "),
};
}
-82
View File
@@ -1,82 +0,0 @@
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);
});
});
-346
View File
@@ -1,346 +0,0 @@
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,
});
}
+4 -112
View File
@@ -68,27 +68,15 @@ function type(view: EditorView, text: string) {
);
}
/** One Backspace at every caret, or over every selection. */
/** One Backspace before every caret. */
function backspace(view: EditorView) {
const { state } = view;
view.dispatch(
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),
changes: { from: Math.max(0, r.head - 1), to: r.head },
range: EditorSelection.cursor(Math.max(0, r.head - 1)),
})),
{ userEvent: "delete.forward" },
{ userEvent: "delete.backward" },
);
}
@@ -204,84 +192,6 @@ 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");
@@ -309,12 +219,6 @@ 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');
});
}
});
@@ -357,18 +261,6 @@ 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");
+7 -17
View File
@@ -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), 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.
* 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.
*/
import { EditorState, type Extension, type Transaction } from "@codemirror/state";
import { syntaxTree } from "@codemirror/language";
@@ -39,31 +39,21 @@ function tagNameAround(tree: Tree, from: number, to: number): SyntaxNode | null
return null;
}
/**
* 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. */
/** The matching tag's name of the same element, or null without one. */
function counterpartName(name: SyntaxNode): SyntaxNode | null {
const tag = name.parent;
const element = tag?.parent;
if (!isComplete(tag) || !element) return null;
if (!tag || !element) return null;
if (element.name === "JSXElement") {
const other = element.getChild(tag.name === "JSXOpenTag" ? "JSXCloseTag" : "JSXOpenTag");
if (!isComplete(other)) return null;
for (let c = other.firstChild; c; c = c.nextSibling) if (JSX_NAMES.has(c.name)) return c;
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 isComplete(other) ? other.getChild("TagName") : null;
return other?.getChild("TagName") ?? null;
}
/** Insertions at a name's edge must extend the name; structural characters end it. */
-96
View File
@@ -1,96 +0,0 @@
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 -34
View File
@@ -6,7 +6,6 @@
*/
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";
@@ -65,29 +64,17 @@ 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 = highlightedLiterals(tree, 0, tree.length);
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);
});
cache.set(tree, out);
return out;
}
@@ -99,22 +86,7 @@ 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 {
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 {
const ranges = literalRanges(state);
let lo = 0;
let hi = ranges.length - 1;
while (lo <= hi) {
-19
View File
@@ -1,7 +1,6 @@
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[] = [];
@@ -55,22 +54,4 @@ 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)");
});
});
+6 -8
View File
@@ -1,6 +1,5 @@
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
@@ -39,7 +38,12 @@ const plugin = ViewPlugin.fromClass(
const theme = EditorView.baseTheme({
".cm-openidea-selected": {
"--openidea-selected-bg": "var(--editor-selection-inactive, var(--bg-editor-selection-inactive))",
...inlineBackground("var(--openidea-selected-bg)"),
// 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",
// Unset (the default `inherit`): the declaration drops and the syntax colours show through.
color: "var(--fg-editor-selection)",
WebkitTextFillColor: "var(--fg-editor-selection)",
@@ -47,12 +51,6 @@ 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];
-8
View File
@@ -101,14 +101,6 @@ 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";');
});
+2 -2
View File
@@ -23,7 +23,7 @@ import {
import type { SyntaxNode } from "@lezer/common";
import { indentMore } from "@codemirror/commands";
import { visibleColumn } from "./visibleColumn";
import { lineLiteralAt, literalAt } from "./literals";
import { 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 = lineLiteralAt(state, pos);
const lit = literalAt(state, pos);
return lit?.kind === "string" ? lit : null;
}
+14 -17
View File
@@ -9,7 +9,6 @@ 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%";
@@ -20,12 +19,10 @@ 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": {
...inlineBackground("var(--editor-search)"),
backgroundColor: "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",
@@ -35,13 +32,13 @@ export const findStyles = {
textDecoration: "line-through",
textDecorationColor: "var(--fg-muted)",
},
".cm-openidea-findScope": inlineBackground("var(--editor-selection-inactive, var(--bg-editor-selection-inactive))"),
".cm-openidea-findMatch-current": {
...inlineFramedFallback("var(--editor-search-current)", FIND_CURRENT_FRAME),
color: "var(--fg-search-match, inherit)",
".cm-openidea-findScope": {
backgroundColor: "var(--editor-selection-inactive, var(--bg-editor-selection-inactive))",
},
"@supports (height: 1lh)": {
".cm-openidea-findMatch-current": inlineFramedModern("var(--editor-search-current)", FIND_CURRENT_FRAME),
".cm-openidea-findMatch-current": {
backgroundColor: "var(--editor-search-current)",
color: "var(--fg-search-match, inherit)",
outline: "1px solid color-mix(in srgb, var(--editor-search-current) 60%, var(--fg-strong))",
},
};
@@ -225,25 +222,25 @@ export const openideaTheme = EditorView.theme({
background: "var(--openidea-line-bg)",
pointerEvents: "none",
},
".cm-selectionMatch": inlineBackground(
"var(--bg-identifier-under-caret, color-mix(in srgb, var(--fg) 9%, transparent))",
),
".cm-selectionMatch": {
backgroundColor: "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": {
...inlineBackground("var(--editor-brace)"),
backgroundColor: "var(--editor-brace)",
color: "inherit",
fontWeight: "var(--matched-brace-weight, var(--fw-code-bold, 700))",
borderRadius: "1px",
},
".cm-matchingTag, &.cm-focused .cm-matchingTag": {
...inlineBackground("var(--bg-matched-tag, var(--editor-brace))"),
backgroundColor: "var(--bg-matched-tag, var(--editor-brace))",
fontWeight: "inherit",
},
".cm-nonmatchingBracket, &.cm-focused .cm-nonmatchingBracket": {
color: "var(--danger)",
...inlineBackground("color-mix(in srgb, var(--danger) 14%, transparent)"),
backgroundColor: "color-mix(in srgb, var(--danger) 14%, transparent)",
},
".cm-specialChar": { color: "var(--danger)" },
@@ -366,7 +363,7 @@ export const openideaTheme = EditorView.theme({
...findStyles,
...markWidgetStyles,
// Find in Files preview matches (search/find/parts.tsx)
".cm-openidea-searchResult": inlineBackground("var(--bg-search-result)"),
".cm-openidea-searchResult": { backgroundColor: "var(--bg-search-result)" },
// Overlays
".cm-tooltip": {
-41
View File
@@ -8,7 +8,6 @@ import { resetDistractionFree, setDistractionFree } from "@/workbench/distractio
import * as contributions from "@/workbench/contributions";
import {
registerEditorKind,
registerMenuGroup,
registerTextEditorWrapper,
setProjectViewLead,
useProjectViewLead,
@@ -580,46 +579,6 @@ 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) => {
-3
View File
@@ -2324,9 +2324,6 @@ 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,11 +64,6 @@
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;
+3 -31
View File
@@ -6,16 +6,7 @@ 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,
useLayoutEffect,
useMemo,
useRef,
useState,
type FocusEvent,
type ReactNode,
} from "react";
import { Fragment, useEffect, useMemo, useRef, useState, type FocusEvent, type ReactNode } from "react";
import clsx from "clsx";
import { useShallow } from "zustand/react/shallow";
import { executeAction } from "@/platform/actions";
@@ -55,7 +46,6 @@ import {
Tabs,
showContextMenu,
registerDropTarget,
useSelectionVisibility,
FILES_DRAG,
type TabItem,
type TabsDnd,
@@ -507,13 +497,7 @@ function PaneContent({ paneId, tab, tabsVisible }: { paneId: string; tab: Tab; t
)}
<FindBar paneId={paneId} />
{crumbs && (
<PaneBreadcrumbs
key={`top:${wrapper?.id}`}
wrapper={wrapper}
path={tab.input.path!}
tabId={tab.id}
position="top"
/>
<PaneBreadcrumbs key={wrapper?.id} wrapper={wrapper} path={tab.input.path!} tabId={tab.id} position="top" />
)}
{wrapper ? (
<wrapper.component
@@ -529,7 +513,7 @@ function PaneContent({ paneId, tab, tabsVisible }: { paneId: string; tab: Tab; t
)}
{crumbs && (
<PaneBreadcrumbs
key={`bottom:${wrapper?.id}`}
key={wrapper?.id}
wrapper={wrapper}
path={tab.input.path!}
tabId={tab.id}
@@ -560,24 +544,12 @@ 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}
-2
View File
@@ -640,7 +640,6 @@ 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}
@@ -711,7 +710,6 @@ 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={[
-39
View File
@@ -95,43 +95,4 @@ 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();
}
});
});
-17
View File
@@ -297,23 +297,6 @@ 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) => {
+2 -3
View File
@@ -16,6 +16,7 @@ import {
moveCompletionSelection,
pickedCompletion,
selectedCompletion,
snippet,
startCompletion,
type Completion,
type CompletionContext,
@@ -52,7 +53,6 @@ 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,8 +296,7 @@ export function applyLspCompletion(
start = tr.changes.mapPos(start, 1);
end = tr.changes.mapPos(end, 1);
}
const source = lspSnippetToCm(item.insertText, snippetVariables(req.path));
applySnippet(view, [{ from: start, to: end, snippet: source }], completion);
snippet(lspSnippetToCm(item.insertText, snippetVariables(req.path)))(view, completion, start, end);
// 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,9 +1,7 @@
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"];
@@ -87,64 +85,3 @@ 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);
});
});
+22 -61
View File
@@ -4,71 +4,32 @@
* function the server reports; a variable or function without tsserver's `local`
* modifier is a module-level global.
*/
import { Tree, TreeBuffer, type NodeSet, type SyntaxNode } from "@lezer/common";
import type { Tree } from "@lezer/common";
import { registerLanguageSemantics, type LanguageSemantics, type SemanticRange } from "../languages";
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);
/** The names of decorators, left of their arguments: `@A`, `@a.B`, `@A()`, `@a.B<T>()`. */
export function decoratorRanges(tree: Tree): SemanticRange[] {
const out: SemanticRange[] = [];
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;
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;
}
}
}
}
},
});
return out;
}
+1 -3
View File
@@ -4,7 +4,6 @@
* 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 {
@@ -290,8 +289,7 @@ 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 (hasLinkedSnippetField(state, dir) || (dir > 0 ? hasNextSnippetField(state) : hasPrevSnippetField(state)))
return false;
if (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);
Loaded 100 of 258 files, more files were not shown because too many files have changed in this diff. Show more