Compare commits

..
Author SHA1 Message Date
l0ng-ai 011289b280 ci(smoke): build the smoke binaries once for every language
Each language job compiled the language_smoke / project_smoke tests and
openidea-server itself, about 4-5 minutes of the same work nine times. A
build job now compiles them once and hands them on as an artifact; the
language jobs only install their tools and run the binaries.
2026-11-23 15:29:18 +08:00
192 changed files with 1159 additions and 5842 deletions

No files matched your search

Binary file not shown.

Before

Width:  |  Height:  |  Size: 138 KiB

After

Width:  |  Height:  |  Size: 160 KiB

+48 -13
View File
@@ -65,6 +65,8 @@ concurrency:
env:
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: 0
# Line tables keep test backtraces readable and the binaries the build job hands on small.
CARGO_PROFILE_DEV_DEBUG: line-tables-only
jobs:
# The languages a pull request can affect: a change to one language's fixture, definition or
@@ -132,10 +134,40 @@ jobs:
done < files.txt
echo "languages=$(emit "$langs")" | tee -a "$GITHUB_OUTPUT"
smoke:
name: Language smoke (${{ matrix.language }})
# Builds the smoke test binaries and openidea-server once for every language below.
build:
name: Build
needs: changes
if: needs.changes.outputs.languages != '[]'
# The tests find the fixtures through the checkout path compiled into them (CARGO_MANIFEST_DIR),
# which is the same on every GitHub-hosted runner.
runs-on: ubuntu-22.04
timeout-minutes: 30
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
with:
shared-key: language-smoke
save-if: ${{ github.ref == 'refs/heads/main' }}
- run: |
set -euo pipefail
mkdir -p smoke-bin
cargo test --locked -p ide-host --test language_smoke --test project_smoke --no-run --message-format=json \
| jq -r 'select(.reason == "compiler-artifact" and .executable != null and .target.kind == ["test"]) | "\(.target.name) \(.executable)"' \
| while read -r name exe; do cp "$exe" "smoke-bin/$name"; done
cargo build --locked -p ide-host --bin openidea-server
cp target/debug/openidea-server smoke-bin/
ls -l smoke-bin
test -x smoke-bin/language_smoke && test -x smoke-bin/project_smoke
# A tar keeps the executable bits, which artifacts drop.
tar -cf smoke-bin.tar smoke-bin
- uses: actions/upload-artifact@v6
with: { name: smoke-bin, path: smoke-bin.tar, retention-days: 1 }
smoke:
name: Language smoke (${{ matrix.language }})
needs: [changes, build]
strategy:
fail-fast: false
matrix:
@@ -149,11 +181,11 @@ jobs:
- run: grep -E '^[A-Z0-9_]+=' .github/tool-versions.env >> "$GITHUB_ENV"
- uses: dtolnay/rust-toolchain@stable
with: { components: "rust-analyzer, rustfmt" }
# One build cache for every language; main saves it.
- uses: Swatinem/rust-cache@v2
with:
shared-key: language-smoke
save-if: ${{ github.ref == 'refs/heads/main' && matrix.language == 'rust' }}
- uses: actions/download-artifact@v6
with: { name: smoke-bin }
- run: |
tar -xf smoke-bin.tar && rm smoke-bin.tar
mkdir -p target/debug && mv smoke-bin/openidea-server target/debug/
- uses: pnpm/action-setup@v4
with: { version: 11 }
@@ -209,17 +241,20 @@ jobs:
- if: matrix.language == 'php'
run: npm install --global "intelephense@$INTELEPHENSE"
- run: cargo test --locked -p ide-host --test language_smoke --no-run
- run: cargo test --locked -p ide-host --test language_smoke -- --ignored --exact ${{ matrix.language }}
# The binaries from the build job, run from the crate directory as `cargo test` does.
- working-directory: crates/ide-host
run: ../../smoke-bin/language_smoke --ignored --exact ${{ matrix.language }}
- if: matrix.language == 'java'
run: cargo test --locked -p ide-host --test project_smoke -- --ignored --exact maven_sync jdk maven_launch_classpath_uses_the_runner_jdk_classifier
working-directory: crates/ide-host
run: ../../smoke-bin/project_smoke --ignored --exact maven_sync jdk maven_launch_classpath_uses_the_runner_jdk_classifier
- if: matrix.language == 'kotlin'
run: cargo test --locked -p ide-host --test project_smoke -- --ignored --exact gradle_sync
working-directory: crates/ide-host
run: ../../smoke-bin/project_smoke --ignored --exact gradle_sync
- if: matrix.language == 'python'
run: cargo test --locked -p ide-host --test project_smoke -- --ignored --exact python_venv
working-directory: crates/ide-host
run: ../../smoke-bin/project_smoke --ignored --exact python_venv
- run: pnpm install --frozen-lockfile
- run: cargo build --locked -p ide-host --bin openidea-server
- run: pnpm smoke smoke/run.test.ts -t "^${{ matrix.language }}$"
- run: pnpm smoke smoke/debug.test.ts -t "^${{ matrix.language }}$"
# The IDE installs the debugger from GitHub releases: authenticated, against rate limits.
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);
+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();
-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)?;
+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();
+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 -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 -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);
});
-39
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");
-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);
});
+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) => {
+1 -1
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();
-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",
});
});
-123
View File
@@ -1,123 +0,0 @@
import type { Page } from "@playwright/test";
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
async function seedReview(page: Page) {
await stubDesktop(page);
await page.evaluate(async () => {
const project = "/src/platform/project.ts";
const context = "/src/platform/context.ts";
const repositoryStore = "/src/features/github/data/repository.ts";
const pullRequests = "/src/features/github/data/pullRequest.ts";
const { useProject } = await import(/* @vite-ignore */ project);
const { setContext } = await import(/* @vite-ignore */ context);
const { useGhRepository } = await import(/* @vite-ignore */ repositoryStore);
const { setPullRequestData } = await import(/* @vite-ignore */ pullRequests);
useProject.setState((s: { settings: { editor: unknown } }) => ({
settings: {
...s.settings,
editor: { ...(s.settings?.editor as object), fontFamily: "Courier New", fontSize: 17, lineHeight: 25 },
},
}));
const coordinates = { owner: "sample", name: "settlement" };
useGhRepository.setState({
connection: {
coordinates,
repository: { id: "repository", nameWithOwner: "sample/settlement" },
currentUser: { id: "reviewer", login: "reviewer" },
root: null,
remotes: [],
},
});
setContext("githubConnected", true);
setContext("githubCurrentBranchPullRequest", true);
setPullRequestData(7, "details", () => ({ number: 7, viewerDidAuthor: false }));
setPullRequestData(7, "pendingReview", () => ({ id: "draft-seven", state: "PENDING", commentsCount: 12 }));
});
}
async function openReview(page: Page) {
await page.evaluate(async () => {
const actions = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actions);
await executeAction("github.pullRequest.submitReview", 7);
});
}
test("centers the unanchored composer, follows the editor font and reflows its review actions", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 1120, height: 840 });
await seedReview(page);
await openReview(page);
const popup = page.getByRole("dialog", { name: "Submit Review" });
const editor = popup.getByRole("textbox", { name: "Review comment" });
const verticalCenter = () =>
popup.evaluate((el) => {
const { top, height } = el.getBoundingClientRect();
return Math.abs(top + height / 2 - innerHeight / 2);
});
await expect.poll(verticalCenter, { message: "verticalCenter at standard size" }).toBeLessThan(1);
await expect(editor).toBeFocused();
await expect(editor).toHaveCSS("font-size", "17px");
await expect(editor).toHaveCSS("line-height", "25px");
await expect(editor).toHaveCSS("font-family", /Courier New/);
await editor.fill("Please double-check the rounding step.");
const grip = (await popup.getByRole("separator", { name: "Resize" }).boundingBox())!;
await page.mouse.move(grip.x + grip.width / 2, grip.y + grip.height / 2);
await page.mouse.down();
await page.mouse.move(grip.x + grip.width / 2 + 56, grip.y + grip.height / 2 + 32);
await page.mouse.up();
await expect.poll(async () => (await popup.boundingBox())!.width).toBeGreaterThan(540);
await page.setViewportSize({ width: 300, height: 400 });
await expect.poll(verticalCenter, { message: "verticalCenter after shrinking" }).toBeLessThan(1);
const approve = (await popup.getByRole("button", { name: "Approve", exact: true }).boundingBox())!;
const comment = (await popup.getByRole("button", { name: "Comment", exact: true }).boundingBox())!;
expect(comment.y).toBeGreaterThan(approve.y);
expect(comment.x + comment.width).toBeLessThan(300);
await expect(editor).toHaveValue("Please double-check the rounding step.");
await editor.press("Escape");
await expect(popup).toHaveCount(0);
await openReview(page);
await expect(editor).toHaveValue("Please double-check the rounding step.");
});
test("keeps anchored review controls and the comment visible after a long submission error", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 355, height: 390 });
await seedReview(page);
await page.evaluate(async () => {
const path = "/src/features/github/details/SubmitReviewPopup.tsx";
const { showSubmitReview } = await import(/* @vite-ignore */ path);
const anchor = document.createElement("button");
anchor.style.cssText = "position:fixed;top:350px;left:275px;";
anchor.textContent = "Review anchor";
document.body.append(anchor);
window.__ipc.handlers.gh_api = ({ request }) => {
const { query } = JSON.parse((request as { body: string }).body);
if (!query.includes("submitPullRequestReview")) throw Error("Unexpected GitHub request");
return JSON.stringify({ errors: [{ message: "Review request failed. " + "outdated-reference-".repeat(35) }] });
};
void showSubmitReview(7, anchor);
});
const popup = page.getByRole("dialog", { name: "Submit Review" });
const editor = popup.getByRole("textbox", { name: "Review comment" });
const button = popup.getByRole("button", { name: "Comment", exact: true });
await editor.fill("Check the batch limit.");
await button.click();
const error = popup.getByRole("alert");
await expect(error).toContainText("Review request failed.");
await expect(button).toBeEnabled();
await expect(editor).toHaveValue("Check the batch limit.");
const box = (await popup.boundingBox())!;
const buttonBox = (await button.boundingBox())!;
expect(box.y + box.height).toBeLessThan(350);
expect(buttonBox.y + buttonBox.height).toBeLessThanOrEqual(box.y + box.height);
expect(box.x + box.width).toBeLessThanOrEqual(355);
await expect.poll(() => error.evaluate((el) => el.scrollHeight > el.clientHeight)).toBe(true);
const calls = await ipcCalls(page, "gh_api");
expect(calls).toHaveLength(1);
const { variables } = JSON.parse((calls[0]!.request as { body: string }).body);
expect(variables).toEqual({ reviewId: "draft-seven", event: "COMMENT", body: "Check the batch limit." });
});
-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]);
});
+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);
-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. */
-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" },
+2 -8
View File
@@ -507,13 +507,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 +523,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}
-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 -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);
+2 -8
View File
@@ -193,17 +193,11 @@ export function lspSnippetToCm(snippet: string, vars: SnippetVariables = {}): st
const hasField = nodes.some(
(n) => n.t === "tab" || n.t === "choice" || (n.t === "var" && vars[n.name] === undefined && !n.children),
);
const defaults = new Map<number, string>();
for (const node of nodes) {
if (node.t === "text" || node.t === "var" || node.n === 0 || defaults.has(node.n)) continue;
if (node.t === "choice") defaults.set(node.n, node.options[0] ?? "");
else if (node.children) defaults.set(node.n, flatten(node.children, vars));
}
let out = "";
for (const n of nodes) {
if (n.t === "text") out += escapeText(n.v);
else if (n.t === "tab") out += field(n.n, defaults.get(n.n) ?? (n.children ? flatten(n.children, vars) : ""));
else if (n.t === "choice") out += field(n.n, defaults.get(n.n) ?? n.options[0] ?? "");
else if (n.t === "tab") out += field(n.n, n.children ? flatten(n.children, vars) : "");
else if (n.t === "choice") out += field(n.n, n.options[0] ?? "");
else {
const v = vars[n.name];
if (v !== undefined) out += escapeText(v);
+1
View File
@@ -201,6 +201,7 @@ export const lspTheme = EditorView.theme({
flex: "0 1 auto",
minWidth: "0",
marginLeft: "auto",
paddingLeft: "16px",
textAlign: "right",
color: "var(--fg-subtle)",
overflow: "hidden",
+32 -65
View File
@@ -25,7 +25,6 @@ import { isNavigating, onNavigation } from "@/editor/lsp/foreground";
import { readManyFileLines, withDocument } from "@/editor/lsp/files";
import { locationItems, navigateTo, pinToFind } from "@/editor/lsp/navigation";
import { openPopup } from "@/editor/lsp/popupStore";
import type { DeclarationTarget } from "@/editor/lsp/syntaxFallback";
import {
commands,
isCancelled,
@@ -543,32 +542,13 @@ async function markerTargets(marker: LineMarker, doc: DocId | null): Promise<Loc
}
}
/** Resolves each declaration's targets before opening the shared chooser. */
/** Opens the single target, or the chooser over several. */
export async function openMarkerTargets(
markers: readonly [LineMarker, ...LineMarker[]],
marker: LineMarker,
anchor: { x: number; y: number },
doc: DocId | null = null,
) {
const [first] = markers;
const merged = markers.length > 1;
let targets: DeclarationTarget[] = (
await Promise.all(
markers.map(async (marker) => {
const locations = await markerTargets(marker, doc);
// Generated methods can share a source location. Keep their names visible in the chooser.
return merged && marker.method ? locations.map((target) => ({ ...target, name: marker.name })) : locations;
}),
)
).flat();
if (merged) {
const seen = new Set<string>();
targets = targets.filter(({ path, range, name }) => {
const key = JSON.stringify([path, range.start.line, range.start.col, name]);
if (seen.has(key)) return false;
seen.add(key);
return true;
});
}
const targets = await markerTargets(marker, doc);
if (targets.length === 1) {
await navigateTo(targets[0]!);
return;
@@ -576,9 +556,9 @@ export async function openMarkerTargets(
openPopup({
kind: "list",
anchor,
title: merged ? tx`Choose Inheritance Target (${targets.length} found)` : first.chooserTitle,
title: marker.chooserTitle,
items: await locationItems(targets),
pin: pinToFind([...new Set(markers.map((m) => m.name))].join(", "), targets),
pin: pinToFind(marker.name, targets),
});
}
@@ -607,50 +587,41 @@ function place(doc: Text, markers: readonly LineMarker[]): PlacedMarker[] {
}
const sameMarkers = (a: readonly PlacedMarker[], b: readonly PlacedMarker[]) =>
a.length === b.length && a.every((m, i) => m.pos === b[i]!.pos && m.marker === b[i]!.marker);
a.length === b.length &&
a.every(
(m, i) => m.pos === b[i]!.pos && m.marker.kind === b[i]!.marker.kind && m.marker.tooltip === b[i]!.marker.tooltip,
);
class InheritanceMarker extends GutterMarker {
readonly kind: LineMarker["kind"];
readonly tooltip: string;
constructor(readonly markers: readonly [LineMarker, ...LineMarker[]]) {
constructor(readonly marker: LineMarker) {
super();
const [first] = markers;
this.kind = first.kind;
this.tooltip =
markers.length === 1 ? first.tooltip : [...new Set(markers.map((m) => `${m.name} — ${m.tooltip}`))].join("\n");
}
override eq(other: GutterMarker): boolean {
return other instanceof InheritanceMarker && other.kind === this.kind && other.tooltip === this.tooltip;
return (
other instanceof InheritanceMarker &&
other.marker.kind === this.marker.kind &&
other.marker.tooltip === this.marker.tooltip
);
}
override toDOM(): Node {
const el = document.createElement("div");
el.className = `${styles.marker} cm-openidea-lineMarker-${this.kind}`;
el.dataset.kind = this.kind;
el.title = this.tooltip;
el.className = `${styles.marker} cm-openidea-lineMarker-${this.marker.kind}`;
el.dataset.kind = this.marker.kind;
el.title = this.marker.tooltip;
el.setAttribute("role", "button");
el.setAttribute("aria-label", this.tooltip);
el.innerHTML = gutterIconMarkup(MARKER_ICONS[this.kind]) ?? "";
el.setAttribute("aria-label", this.marker.tooltip);
el.innerHTML = gutterIconMarkup(MARKER_ICONS[this.marker.kind]) ?? "";
return el;
}
}
const gutterMarkers = new WeakMap<readonly PlacedMarker[], RangeSet<InheritanceMarker>>();
const gutterMarkers = new WeakMap<readonly PlacedMarker[], RangeSet<GutterMarker>>();
function markerSet(placed: readonly PlacedMarker[]): RangeSet<InheritanceMarker> {
function markerSet(placed: readonly PlacedMarker[]): RangeSet<GutterMarker> {
let set = gutterMarkers.get(placed);
if (!set) {
const groups = new Map<string, { pos: number; markers: [LineMarker, ...LineMarker[]] }>();
for (const { pos, marker } of placed) {
const key = `${pos}:${marker.kind}`;
const group = groups.get(key);
if (group) group.markers.push(marker);
else groups.set(key, { pos, markers: [marker] });
}
set = RangeSet.of(
[...groups.values()].map(({ pos, markers }) => new InheritanceMarker(markers).range(pos)),
placed.map((m) => new InheritanceMarker(m.marker).range(m.pos)),
true,
);
gutterMarkers.set(placed, set);
@@ -858,14 +829,10 @@ export function markerDeps(
};
}
function markerAt(view: EditorView, lineFrom: number, kind: string | undefined): InheritanceMarker | undefined {
let match: InheritanceMarker | undefined;
markerSet(view.state.field(markersField)).between(lineFrom, lineFrom, (pos, _to, marker) => {
if (pos !== lineFrom || marker.kind !== kind) return;
match = marker;
return false;
});
return match;
function markerAt(view: EditorView, lineFrom: number, el: Element | null): LineMarker | null {
const onLine = view.state.field(markersField).filter((m) => m.pos === lineFrom);
const kind = (el?.closest(`.${styles.marker}`) as HTMLElement | null)?.dataset.kind;
return (onLine.find((m) => m.marker.kind === kind) ?? (onLine.length === 1 ? onLine[0] : null))?.marker ?? null;
}
export function implementationGutter(ctx: EditorDocContext): Extension {
@@ -879,13 +846,13 @@ export function implementationGutter(ctx: EditorDocContext): Extension {
markers: (view) => markerSet(view.state.field(markersField)),
mousedown: (view, block, e) => {
if (e.button !== 0) return false;
const target = e.target instanceof Element ? e.target.closest<HTMLElement>(`.${styles.marker}`) : null;
if (!target) return false;
const marker = markerAt(view, block.from, target.dataset.kind);
const target = e.target instanceof Element ? e.target : null;
if (!target?.closest(`.${styles.marker}`)) return false;
const marker = markerAt(view, block.from, target);
if (!marker) return false;
e.preventDefault();
const rect = target.getBoundingClientRect();
void openMarkerTargets(marker.markers, { x: rect.left, y: rect.bottom + 2 }, ctx.doc);
const rect = (target.closest(`.${styles.marker}`) ?? target).getBoundingClientRect();
void openMarkerTargets(marker, { x: rect.left, y: rect.bottom + 2 }, ctx.doc);
return true;
},
}),
+32 -137
View File
@@ -1,9 +1,4 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { fireEvent } from "@testing-library/react";
import { EditorView } from "@codemirror/view";
import { iconAreaExtension } from "@/editor/core/cm/iconArea";
import { lspDoc } from "@/editor/lsp/lsp";
import type { DeclarationTarget } from "@/editor/lsp/syntaxFallback";
import {
IpcError,
commands,
@@ -19,15 +14,14 @@ const nav = vi.hoisted(() => ({ navigateTo: vi.fn(async () => {}), openPopup: vi
vi.mock("@/editor/lsp/navigation", async (orig) => ({
...(await orig<typeof import("@/editor/lsp/navigation")>()),
navigateTo: nav.navigateTo,
locationItems: async (locs: DeclarationTarget[]) =>
locs.map((l, i) => ({ id: `${i}`, label: l.name ?? l.path, run: () => {} })),
locationItems: async (locs: Location[]) => locs.map((l, i) => ({ id: `${i}`, label: l.path, run: () => {} })),
}));
vi.mock("@/editor/lsp/popupStore", async (orig) => ({
...(await orig<typeof import("@/editor/lsp/popupStore")>()),
openPopup: nav.openPopup,
}));
import { candidateKey, markerCandidates, type LineMarker, type MarkerCandidate } from "./lineMarkers";
import { candidateKey, markerCandidates, type MarkerCandidate } from "./lineMarkers";
import { Text } from "@codemirror/state";
import {
affectsMarkers,
@@ -35,7 +29,6 @@ import {
emptyCache,
enabledGroups,
fillMarkers,
implementationGutter,
libraryCandidates,
markerBatches,
markerDeps,
@@ -546,18 +539,16 @@ describe("clicking a marker", () => {
it("navigates to a single target", async () => {
const target = loc("/p/Circle.java", 0, 13);
await openMarkerTargets(
[
{
kind: "implemented",
line: 0,
col: 17,
method: false,
name: "Shape",
targets: [target],
tooltip: "",
chooserTitle: "",
},
],
{
kind: "implemented",
line: 0,
col: 17,
method: false,
name: "Shape",
targets: [target],
tooltip: "",
chooserTitle: "",
},
{ x: 1, y: 2 },
);
expect(nav.navigateTo).toHaveBeenCalledWith(target);
@@ -571,18 +562,16 @@ describe("clicking a marker", () => {
const method = { ...zero, range: { start: { line: 5, col: 4 }, end: { line: 7, col: 5 } } };
const spy = vi.spyOn(commands, "lspImplementationLocations").mockResolvedValue({ status: "ok", data: [method] });
await openMarkerTargets(
[
{
kind: "implemented",
line: 1,
col: 9,
method: true,
name: "save",
targets: [zero],
tooltip: "",
chooserTitle: "",
},
],
{
kind: "implemented",
line: 1,
col: 9,
method: true,
name: "save",
targets: [zero],
tooltip: "",
chooserTitle: "",
},
{ x: 1, y: 2 },
7,
);
@@ -596,18 +585,16 @@ describe("clicking a marker", () => {
const targets = [loc("/p/Circle.java", 0, 13), loc("/p/Square.java", 0, 13)];
expect(candidateKey(candidate())).toBe("0:17:Shape");
await openMarkerTargets(
[
{
kind: "implemented",
line: 0,
col: 17,
method: false,
name: "Shape",
targets,
tooltip: "",
chooserTitle: "Choose Implementation of Shape (2 found)",
},
],
{
kind: "implemented",
line: 0,
col: 17,
method: false,
name: "Shape",
targets,
tooltip: "",
chooserTitle: "Choose Implementation of Shape (2 found)",
},
{ x: 1, y: 2 },
);
expect(nav.navigateTo).not.toHaveBeenCalled();
@@ -622,98 +609,6 @@ describe("clicking a marker", () => {
});
});
describe("inheritance gutter", () => {
it.each([
{ kind: "overriding", language: "java", declaration: "@SuperBuilder" },
{ kind: "overridden", language: "java", declaration: "@Data" },
{ kind: "implementing", language: "go", declaration: "type Square struct{}" },
{ kind: "implemented", language: "rust", declaration: "trait Shape { fn area(); fn label(); }" },
] as const)("merges $language $kind markers by line and kind", async ({ kind, language, declaration }) => {
vi.useFakeTimers();
nav.navigateTo.mockClear();
nav.openPopup.mockClear();
const ctx = { doc: 1, path: `/p/gutter-${kind}`, language, uiMode: null, readOnly: false };
const doc = Text.of([declaration, "another declaration"]);
const markers = markersOf(ctx.path, doc);
const otherKind = kind === "overridden" ? "overriding" : "overridden";
const inputs = [
{ kind, name: "build", line: 0 },
{ kind: otherKind, name: "other", line: 0 },
{ kind, name: "self", line: 0 },
{ kind, name: "build", line: 0 },
{ kind, name: "later", line: 1 },
] as const;
const candidates = inputs.map(({ name, line }, i): MarkerCandidate => ({
name,
line,
symbol: `${name}(${i})`,
col: 0,
method: true,
abstract: false,
inheritable: false,
overriding: false,
owner: null,
}));
markers.outline = { items: [], candidates };
inputs.forEach((input, i) => {
const marker: LineMarker = {
...input,
col: 0,
method: true,
targets: [
loc(
language === "java" && input.kind === kind && input.line === 0 ? "/p/BaseOrder.java" : `/p/${input.name}`,
2,
),
],
tooltip: `Target for ${input.name}`,
chooserTitle: input.name,
};
const group = marker.kind === "implemented" || marker.kind === "overridden" ? "inheritors" : "supers";
markers.cache.entries.set(candidateKey(candidates[i]!), { [group]: marker });
});
const view = new EditorView({
doc,
extensions: [lspDoc.of(ctx), iconAreaExtension, implementationGutter(ctx)],
parent: document.body,
});
try {
await vi.advanceTimersByTimeAsync(500);
const icons = [...view.dom.querySelectorAll<HTMLElement>(`.cm-openidea-lineMarker-${kind}`)];
expect(icons).toHaveLength(2);
expect(icons[0]!.title).toContain("Target for build");
expect(icons[0]!.title).toContain("Target for self");
expect(icons[0]!.title).not.toContain("Target for later");
expect(icons[0]!.parentElement!.querySelector(`.cm-openidea-lineMarker-${otherKind}`)).not.toBeNull();
fireEvent.mouseDown(icons[0]!, { button: 0 });
await vi.advanceTimersByTimeAsync(0);
expect(nav.navigateTo).not.toHaveBeenCalled();
expect(nav.openPopup.mock.calls[0]![0].items.map((item: { label: string }) => item.label)).toEqual([
"build",
"self",
]);
// CodeMirror finds the clicked line by the gutter row's screen position.
const block = view.lineBlockAt(doc.line(2).from);
vi.spyOn(icons[1]!.parentElement!, "getBoundingClientRect").mockReturnValue(
new DOMRect(0, view.documentTop + block.top, 10, block.height),
);
fireEvent.mouseDown(icons[1]!, { button: 0 });
await vi.advanceTimersByTimeAsync(0);
expect(nav.navigateTo).toHaveBeenCalledWith(loc("/p/later", 2));
view.dispatch({ changes: { from: doc.line(1).to, to: doc.line(2).from, insert: " " } });
const joined = view.dom.querySelectorAll<HTMLElement>(`.cm-openidea-lineMarker-${kind}`);
expect(joined).toHaveLength(1);
expect(joined[0]!.title).toContain("Target for later");
} finally {
view.destroy();
vi.useRealTimers();
}
});
});
describe("overriders of a type's methods from its subtypes", () => {
// Shapes and names as jdtls answers them (outline names carry the signature).
const REPO = [
+1 -1
View File
@@ -1,5 +1,5 @@
/**
* Agent Setup lists every agent, with those this machine can run first
* Settings › Agents › Coding Agents: one searchable list of every agent, those this machine can run first
* (built in, installed from the ACP Registry, or defined in an agent file), then those it
* can install. The selected agent's page holds its actions, the settings its new tasks
* start with, and how it is launched. Launch edits are staged until Apply; installs run in
+3 -2
View File
@@ -1,5 +1,6 @@
/**
* Command Rules defines the allow and block patterns for agent permission requests.
* Settings › Tools › Agents › Command Permissions: whitelist (auto-approve)
* and blacklist (auto-reject) command patterns evaluated on agent permission requests.
*/
import { useMemo, useState } from "react";
import { tx } from "@/platform/i18n";
@@ -46,7 +47,7 @@ export function AgentPolicyPage() {
};
return (
<section className={styles.body} aria-label={tx("Command Rules")}>
<section className={styles.body} aria-label="Command Permissions">
<p className={styles.notice}>
<T>
Allowed commands run without asking, with or without extra arguments. Blocked commands are always rejected,
+1 -1
View File
@@ -1,4 +1,4 @@
/** Settings › Agents › Agent Setup. */
/** Settings › Agents › Coding Agents. */
import { AgentList } from "./AgentList";
import { tauriCommands, tauriRegistry, type CommandsBackend, type RegistryBackend } from "./registry";
import styles from "./AgentRegistry.module.css";
+1 -2
View File
@@ -224,12 +224,11 @@
flex: none;
}
/* Keep the import list height stable while filtering. */
/* Import Sessions from Other Apps: filter above a fixed-height list, so the dialog doesn't grow. */
.chooser {
display: flex;
flex-direction: column;
gap: var(--space-2);
padding: var(--space-3) var(--space-4) 0;
}
.chooserList {
height: 312px;
+5 -6
View File
@@ -281,9 +281,8 @@ describe("Agents docked view", () => {
]);
});
it("lists Import Sessions in Find Action", () => {
it("lists Import Sessions from Other Apps in Find Action", () => {
const action = taskActions.find((a) => a.id === "agents.importSessions");
expect(action?.title).toBe("Import Sessions…");
expect(action?.hidden).toBeFalsy();
expect(action?.when).toBe("projectOpen");
act(() => void action?.run({} as never));
@@ -503,17 +502,17 @@ describe("Agents pinned and grouped tasks", () => {
expect(rows.some((text) => text.includes("one"))).toBe(true);
});
it("offers the groups, a new one and a way out in the Group submenu", () => {
it("offers the groups, a new one and a way out in Move to Group", () => {
useAgents.setState({ organize: { groups: [frontend], groupOf: { two: "g1" }, pinned: [] } });
const menu = taskMenu([useAgents.getState().tasks.get("two")!]);
const move = menu.find((item) => "label" in item && item.label === "Group");
const move = menu.find((item) => "label" in item && item.label === "Move to Group");
expect(move).toBeDefined();
const submenu = (move as { submenu: { label?: string; checked?: boolean }[] }).submenu;
expect(submenu.map((item) => item.label ?? "separator")).toEqual([
"Frontend",
"separator",
"New Group…",
"No Group",
"Remove from Group",
]);
expect(submenu[0]).toMatchObject({ checked: true });
});
@@ -521,7 +520,7 @@ describe("Agents pinned and grouped tasks", () => {
it("moves a pinned task into a group, out of the pinned section", () => {
useAgents.setState({ organize: { groups: [frontend], groupOf: {}, pinned: ["two"] } });
const menu = taskMenu([useAgents.getState().tasks.get("two")!]);
const move = menu.find((item) => "label" in item && item.label === "Group") as {
const move = menu.find((item) => "label" in item && item.label === "Move to Group") as {
submenu: { label?: string; run?: () => void }[];
};
act(() => move.submenu.find((item) => item.label === "Frontend")!.run!());
-2
View File
@@ -36,9 +36,7 @@
outline: none;
}
.field :global(.cm-scroller) {
height: auto;
max-height: 280px;
overflow-x: hidden;
overflow-y: auto;
font-family: inherit;
line-height: 1.5;
-40
View File
@@ -1,40 +0,0 @@
import { useState } from "react";
import type { AgentImage } from "@/bindings";
import { useTx } from "@/platform/i18n";
import { IconButton } from "@/ui";
import { ImagePreview, imageSrc } from "./ImagePreview";
import styles from "./Session.module.css";
/** Image thumbnails; a click opens the full image, `onRemove` adds a remove button to each. */
export function ImageStrip({ images, onRemove }: { images: AgentImage[]; onRemove?: (index: number) => void }) {
const tx = useTx();
const [open, setOpen] = useState<AgentImage | null>(null);
if (images.length === 0) return null;
return (
<div className={styles.images}>
{images.map((img, i) => (
<span key={i} className={styles.imageItem}>
<button
type="button"
className={styles.imageButton}
title={img.name ?? undefined}
onClick={() => setOpen(img)}
>
<img className={styles.image} src={imageSrc(img)} alt={img.name ?? tx("Image")} />
</button>
{onRemove && (
<IconButton
type="button"
className={styles.removeImage}
aria-label={tx("Remove Image")}
onClick={() => onRemove(i)}
icon="close"
size="small"
/>
)}
</span>
))}
<ImagePreview image={open} onClose={() => setOpen(null)} />
</div>
);
}
+2 -2
View File
@@ -1,4 +1,4 @@
/** Pick external sessions and import them as agent tasks. */
/** Import Sessions from Other Apps: pick sessions a scan found now, and import them as tasks. */
import { useEffect, useId, useMemo, useRef, useState, type KeyboardEvent, type MouseEvent } from "react";
import { Button, Dialog, Icon, List, SearchField, Spinner, T, listNavigate, rowSelectionMode, selectRow } from "@/ui";
import { useRowHeight } from "@/ui/density";
@@ -160,7 +160,7 @@ function ImportSessionsDialog() {
<Dialog
open
onClose={close}
title="Import Sessions"
title="Import Sessions from Other Apps"
width={560}
footerStart={
<span className={styles.chooserFooter}>
+2 -2
View File
@@ -1,7 +1,7 @@
/**
* Per-session MCP picker for the New Task and Session composers: shows inherited IDE, Project,
* Global, and Agent-Native CLI MCP servers, lets the user toggle servers for this session only,
* reset session overrides, or jump to Settings › Agents › MCP Connections.
* reset session overrides, or jump to Settings › Agents › External MCP Servers.
*/
import { useMemo, useState } from "react";
import type { McpExternalSource, McpServer } from "@/bindings";
@@ -110,7 +110,7 @@ export function McpPicker({
}}
triggerAriaLabel={tx("MCP servers")}
popupTitle={tx("Session MCP Servers")}
settingsTitle={tx("MCP Connections…")}
settingsTitle={tx("External MCP Servers…")}
settingsPage={MCP_PAGE}
counts={{ active: resolved.activeCount, total: resolved.totalCount, overrides: resolved.overrideCount }}
search={{ placeholder: tx("Filter MCP servers…"), ariaLabel: tx("Filter MCP servers"), shown: totalRows > 5 }}
+2 -2
View File
@@ -1,5 +1,5 @@
/**
* Settings › Agents › MCP Connections: multi-level MCP management across Global (`settings.toml`
* Settings › Agents › External MCP Servers: multi-level MCP management across Global (`settings.toml`
* + Keychain), Project (`.openidea/settings.toml`), and Agent CLI config directories
* (`~/.copilot/mcp-config.json`, `~/.claude.json`, `~/.codex/config.toml`, `~/.cursor/mcp.json`,
* `~/.gemini/settings.json`, `~/.jetbrains/mcp/mcp.json`, `.mcp.json`, `.vscode/mcp.json`), with
@@ -535,7 +535,7 @@ export function McpServersPage({ backend = defaultMcpBackend }: { backend?: McpB
<div className={page.page}>
<div className={page.header}>
<h2 className={page.title}>
<T>MCP Connections</T>
<T>External MCP Servers</T>
</h2>
<div className={page.headerActions}>
<Button
+2 -13
View File
@@ -202,8 +202,6 @@
overflow-x: hidden;
overflow-anchor: none;
padding: var(--space-3);
/* Room below the end that keeps the header of a section folded there in place (`Stream`). */
padding-bottom: calc(var(--space-3) + var(--stream-slack, 0px));
display: flex;
flex-direction: column;
font-size: var(--agent-fs-ui, var(--fs-ui));
@@ -231,7 +229,7 @@
content-visibility: auto;
}
/* WebKit leaves a stale selection highlight on rows that skipped rendering (`useOffscreenRows`). */
.conversationRow[data-measured][data-selection] {
.stream[data-selection] > .conversationRow[data-measured] {
content-visibility: visible;
}
/* Keep turns distinct and the work within a turn close to its author. Not `* + *`: a
@@ -1197,15 +1195,6 @@
border: 1px solid var(--border);
border-radius: var(--radius-small);
}
.toolImages,
.toolImages .imageItem,
.toolImages .imageButton {
max-width: 100%;
}
.toolImages .image {
max-width: min(100%, 640px);
max-height: 320px;
}
.removeImage {
position: absolute;
top: 4px;
@@ -1285,7 +1274,7 @@
}
.changesScope {
flex: none;
padding: 0 4px;
padding: 6px 10px 2px;
}
.changesSummary {
flex: none;
+3 -3
View File
@@ -32,7 +32,7 @@ function FormWrapper({ children }: { children: ReactNode }) {
return <SettingsFormContext.Provider value={form}>{children}</SettingsFormContext.Provider>;
}
describe("Command Rules sub-page", () => {
describe("Command Permissions sub-page", () => {
it("registers under Agents group in settings", () => {
const dispose = activateSettingsPages();
try {
@@ -40,7 +40,7 @@ describe("Command Rules sub-page", () => {
const agentsGroup = tree.find((n) => n.title === AGENTS_GROUP);
expect(agentsGroup).toBeDefined();
const policyNode = agentsGroup?.children.find((n) => n.key === POLICY_PAGE);
expect(policyNode?.title).toBe("Command Rules");
expect(policyNode?.title).toBe("Command Permissions");
// A project's settings file can't decide what agents run without asking.
expect(policyNode?.page?.projectScope).not.toBe(true);
} finally {
@@ -56,7 +56,7 @@ describe("Command Rules sub-page", () => {
</FormWrapper>,
);
const policy = screen.getByRole("region", { name: "Command Rules" });
const policy = screen.getByRole("region", { name: "Command Permissions" });
expect(within(policy).getByText("rm -rf *")).toBeInTheDocument();
fireEvent.change(within(policy).getByRole("textbox", { name: "Allowed command pattern" }), {
+5 -4
View File
@@ -313,7 +313,7 @@ export function activate(): () => void {
{
id: "agents.addAgent",
title: "More Agents…",
description: "Install, update, or remove agents from the ACP Registry.",
description: "Opens Settings › Tools › Agents: installs, updates or removes agents from the ACP Registry.",
category: "Agents",
icon: "plugin",
keywords: ["agent", "acp", "registry", "install", "update"],
@@ -321,11 +321,12 @@ export function activate(): () => void {
},
{
id: "agents.mcpServers",
title: "MCP Connections…",
description: "Configure the MCP servers that agents can use.",
title: "External MCP Servers…",
description:
"Opens Settings › Agents › External MCP Servers: configures the User and Workspace MCP servers coding agents use.",
category: "Agents",
icon: "settings",
keywords: ["mcp", "model context protocol", "servers", "tools", "agent", "External MCP Servers"],
keywords: ["mcp", "model context protocol", "servers", "tools", "agent"],
run: () => void executeAction("file.settings", MCP_PAGE),
},
{
+1 -1
View File
@@ -1,6 +1,6 @@
/**
* Shared MCP server model, multi-level inheritance resolution (IDE -> Project -> Global -> Agent CLI),
* and reactive cache for Settings › Agents › MCP Connections and the Composer MCP picker.
* and reactive cache for Settings › Agents › External MCP Servers and the Composer MCP picker.
*/
import { useEffect } from "react";
import { create } from "zustand";
+3 -3
View File
@@ -7,15 +7,15 @@ export const HOME_KEY = "agent:new";
export const TOOL_WINDOW = "agents";
/** MIME of a dragged agent task (a tree row or the docked conversation bar): the payload is the task id. */
export const TASK_DRAG = "application/x-openidea-agent-task";
/** Settings › Agents › Agent Setup. */
/** Settings › Agents › Coding Agents: the agents this machine runs. */
export const REGISTRY_PAGE = "agents.list";
/** The Settings folder holding the agent pages. */
export const AGENTS_GROUP = "Agents";
/** Settings › Agents › MCP Connections. */
/** Settings › Agents › External MCP Servers: User and Workspace MCP configurations. */
export const MCP_PAGE = "agents.mcpServers";
/** Settings › Agents › Skills: every CLI's SKILL.md folders and their modes. */
export const SKILLS_PAGE = "agents.skills";
/** Settings › Agents › Command Rules. */
/** Settings › Agents › Command Permissions. */
export const POLICY_PAGE = "agents.policy";
export const sessionKey = (task: string) => `agent:${task}`;
+1 -1
View File
@@ -3,7 +3,7 @@ import type { AgentProvider } from "@/bindings";
import type { tx as Tx } from "@/platform/i18n";
import type { SelectOption } from "@/ui";
/** Picker entry that opens Settings › Agents › Agent Setup. */
/** Picker entry that opens Settings › Tools › Agents instead of choosing an agent. */
export const ADD_AGENT = "__addAgent__";
/**
+16 -16
View File
@@ -4,13 +4,14 @@ import { repositoryPath } from "@/features/vcs/repositoryPaths";
import { tx } from "@/platform/i18n";
import { call, commands, onIdeEvent } from "@/platform/ipc";
import { basename, dirname, relativeDir } from "@/platform/project";
import { fileIconName, Icon, IconButton, showContextMenu, Spinner, T, Tabs, Tree } from "@/ui";
import { fileIconName, Icon, IconButton, showContextMenu, Spinner, T, Tree } from "@/ui";
import { notifications } from "@/workbench/contributions";
import { confirm } from "@/workbench/messages";
import { useCallback, useEffect, useMemo, useState } from "react";
import { ChangesResizer } from "../ChangesResizer";
import styles from "../Session.module.css";
import { setChangesOptions, type ChangesScope } from "../changesOptions";
import { SegmentedControl } from "../ConfigPickers";
import { formatSentAt } from "../conversation";
import { branchLabel } from "../model";
import { acceptChanges, refreshChanges, rollbackChanges, useAgents } from "../store";
@@ -385,21 +386,20 @@ export function ChangesPane({
)}
{!docked && <IconButton icon="chevron-right" title={tx("Hide changes")} size="small" onClick={onHide} />}
</div>
<Tabs
variant="compact"
className={styles.changesScope}
aria-label="Changes to show"
activeId={scope}
onSelect={(id) => {
if (id === scope) return;
setChangesOptions({ scope: id === "turn" ? "turn" : "task" });
void refreshChanges(task.id);
}}
items={[
{ id: "task", label: "Whole Task" },
{ id: "turn", label: "Last Turn" },
]}
/>
<div className={styles.changesScope}>
<SegmentedControl
ariaLabel={tx("Changes to show")}
options={[
{ value: "task", label: tx("Whole Task") },
{ value: "turn", label: tx("Last Turn") },
]}
value={scope}
onChange={(value) => {
setChangesOptions({ scope: value === "turn" ? "turn" : "task" });
void refreshChanges(task.id);
}}
/>
</div>
{(scope === "turn" || grouped || head || task.base) && (
<div className={styles.changesSummary}>
{scope === "turn" ? (
+16 -26
View File
@@ -1,5 +1,4 @@
import { createContext, useContext, useRef, useState, type ReactElement, type ReactNode } from "react";
import { flushSync } from "react-dom";
import { createContext, useContext, useLayoutEffect, useRef, useState, type ReactElement, type ReactNode } from "react";
/** Set while Find in Conversation is open: folded sections render their content, so it is found. */
export const FoldedContent = createContext(false);
@@ -10,8 +9,8 @@ export const FoldedContent = createContext(false);
*/
export const OpenFolds = createContext<Map<string, boolean> | null>(null);
/** Puts a section's header back at `top` (viewport px) after the reader opened or closed it (`Stream`). */
export const KeepFoldHeader = createContext<((header: HTMLElement, top: number) => void) | null>(null);
/** Scrolls a section the reader just opened into view (`Stream`). */
export const RevealFold = createContext<((el: HTMLElement) => void) | null>(null);
/**
* A collapsed section that renders its content only once opened: most of a long conversation
@@ -36,38 +35,29 @@ export function Fold({
}) {
const always = useContext(FoldedContent);
const remembered = useContext(OpenFolds);
const keepHeader = useContext(KeepFoldHeader);
const reveal = useContext(RevealFold);
const [expanded, setExpanded] = useState(() => !!open || !!defaultOpen || (!!id && !!remembered?.get(id)));
const ref = useRef<HTMLDetailsElement>(null);
const remember = (now: boolean) => {
if (!id || !remembered) return;
if (now) remembered.set(id, true);
else remembered.delete(id);
};
const opened = useRef(false);
// Once its content is laid out, so its height is known.
useLayoutEffect(() => {
if (!expanded || !opened.current) return;
opened.current = false;
if (ref.current) reveal?.(ref.current);
}, [expanded, reveal]);
return (
<details
ref={ref}
className={className}
open={open || ((!!id || defaultOpen) && expanded) || undefined}
// Toggle here rather than natively: the content renders in the same frame, and the header
// is put back where it was before anything paints.
onClick={(e) => {
const details = ref.current;
const header = e.target instanceof Element ? e.target.closest("summary") : null;
if (e.defaultPrevented || !details || !header || header.parentElement !== details) return;
if ((e.target as Element).closest("a, button, input, select, textarea, label") !== null) return;
e.preventDefault();
const top = header.getBoundingClientRect().top;
const now = !details.open;
details.open = now;
remember(now);
flushSync(() => setExpanded(now));
keepHeader?.(header, top);
}}
onToggle={(e) => {
const now = e.currentTarget.open;
opened.current = now;
setExpanded(now);
remember(now);
if (id && remembered) {
if (now) remembered.set(id, true);
else remembered.delete(id);
}
}}
>
{summary}
+64 -148
View File
@@ -1,4 +1,4 @@
import type { AgentEntry, AgentImage, AgentTask } from "@/bindings";
import type { AgentEntry, AgentTask } from "@/bindings";
import { executeAction } from "@/platform/actions";
import { tx } from "@/platform/i18n";
import {
@@ -27,7 +27,6 @@ import {
type RefObject,
} from "react";
import { useAgentSettings } from "../agentSettings";
import { ImageStrip } from "../ImageStrip";
import {
entriesKey,
isBusy,
@@ -50,7 +49,7 @@ import {
type EntryRow,
} from "./conversationRows";
import { FindBar } from "./FindBar";
import { KeepFoldHeader, OpenFolds } from "./Folds";
import { OpenFolds, RevealFold } from "./Folds";
import { Entry } from "./messages";
import { ProcessRun, TurnFold } from "./ProcessRows";
import { type QuestionAnswer } from "./QuestionForm";
@@ -148,14 +147,7 @@ function useOffscreenRows(
}, [ref, visible, enabled, fitWindowWidth, fontZoom]);
// Keep independent of `visible`: when a kept-alive tab hides, `data-selection` must stay until
// the selection leaves and WebKit clears off-screen rows' highlights before skipping again.
useSelectionVisibility(ref, enabled, `.${styles.conversationRow}`);
}
/** Images remain visible beside the work's folded summary, without duplicating them when it opens. */
function toolImages(row: ConversationRow): AgentImage[] {
if (row.kind === "turn") return row.rows.flatMap(toolImages);
const entries = row.kind === "process" ? row.entries.map(({ entry }) => entry) : [row.entry];
return entries.flatMap((entry) => (entry.type === "tool" ? (entry.images ?? []) : []));
useSelectionVisibility(ref, enabled);
}
interface StreamProps {
@@ -177,31 +169,15 @@ interface StreamProps {
/** Entries rendered at a time when a conversation opens at its end. */
const ENTRY_BATCH = 40;
function scrollsY(el: Element): boolean {
if (el.scrollHeight - el.clientHeight <= 1) return false;
const overflow = getComputedStyle(el).overflowY;
return overflow === "auto" || overflow === "scroll";
}
/** The innermost container under `target` that scrolls vertically: a tool output, a run of calls, or `root`. */
function scrollOwner(target: EventTarget | null, root: HTMLElement): HTMLElement {
function scrollsInside(target: EventTarget | null, root: HTMLElement): boolean {
for (let el = target instanceof Element ? target : null; el && el !== root; el = el.parentElement) {
if (el instanceof HTMLElement && scrollsY(el)) return el;
}
return root;
}
/** Whether a container inside `root` under `target` can still scroll up. */
function scrollsUpInside(target: EventTarget | null, root: HTMLElement): boolean {
for (let el = target instanceof Element ? target : null; el && el !== root; el = el.parentElement) {
if (el.scrollTop > 0 && scrollsY(el)) return true;
if (el.scrollTop <= 0) continue;
const overflow = getComputedStyle(el).overflowY;
if (overflow === "auto" || overflow === "scroll") return true;
}
return false;
}
/** A wheel gesture's events arrive closer together than this; a pause starts a new one. */
const WHEEL_GESTURE_MS = 150;
export function Stream({
loadError,
task,
@@ -223,7 +199,7 @@ export function Stream({
const restored = useRef(false);
const previousLength = useRef(entries?.length ?? 0);
/** Scrolled away from the end: offer one click back to the latest message. */
const [away, setAway] = useState(false);
const [away, setAway] = useState(() => positions.get(key)?.stick === false);
// Opened at the end, the last entries come first and the earlier ones follow in batches:
// reopening a long conversation paints at once. A kept offset needs them all.
const [shown, setShown] = useState(() => (positions.get(key)?.stick === false ? Infinity : ENTRY_BATCH));
@@ -247,22 +223,15 @@ export function Stream({
const stopFollowing = useCallback(
(target: EventTarget | null) => {
const el = ref.current;
if (!el || el.scrollHeight <= el.clientHeight || scrollsUpInside(target, el)) return;
if (!el || el.scrollHeight <= el.clientHeight || scrollsInside(target, el)) return;
scrollingUp.current = true;
if (!position.current.stick) return;
position.current = { top: el.scrollTop, stick: false };
positions.set(key, position.current);
setAway(true);
},
[key, positions],
);
const updateJumpVisibility = useCallback((el: HTMLElement) => {
// An upward gesture releases following before anything moves. Only offer a jump
// when there is actual content below the viewport, excluding the fold spacer.
setAway(
!position.current.stick &&
el.scrollHeight - el.clientHeight - el.scrollTop > (parseFloat(getComputedStyle(el).paddingBottom) || 0) + 1,
);
}, []);
// Earlier entries are prepended above the view: remember where the first painted row is
// so the content stays put and the scrollbar doesn't jump under the pointer.
const anchor = useRef<{ el: Element; top: number } | null>(null);
@@ -316,31 +285,11 @@ export function Stream({
const visible = useEditorShown();
const { foldTurns, toolCalls, fitWindowWidth } = useAgentSettings();
useOffscreenRows(ref, visible, !finding, fitWindowWidth, fontZoom);
/**
* Blank space after the conversation that lets a section folded near the end keep its header
* in place. It is only ever what the view shows below the content: scrolling up or new rows
* take it back without moving anything.
*/
const slack = useRef(0);
const setSlack = useCallback((px: number) => {
slack.current = px;
if (px) ref.current?.style.setProperty("--stream-slack", `${px}px`);
else ref.current?.style.removeProperty("--stream-slack");
}, []);
const trimSlack = useCallback(() => {
const el = ref.current;
if (!el || slack.current === 0) return;
const content = el.scrollHeight - slack.current;
const next = Math.max(0, Math.min(slack.current, Math.ceil(el.scrollTop + el.clientHeight - content)));
if (next !== slack.current) setSlack(next);
}, [setSlack]);
/** A diagram that drew after the last streamed chunk grows the conversation: keep following. */
const onDiagramDrawn = useCallback(() => {
const el = ref.current;
if (!el) return;
if (position.current.stick && !dragging.current) el.scrollTop = el.scrollHeight;
updateJumpVisibility(el);
}, [updateJumpVisibility]);
if (el && position.current.stick && !dragging.current) el.scrollTop = el.scrollHeight;
}, []);
useLayoutEffect(() => {
const el = ref.current;
if (!el || entries === null || !visible) return;
@@ -365,12 +314,10 @@ export function Stream({
useLayoutEffect(() => {
const el = ref.current;
if (!el || entries === null || !visible) return;
trimSlack();
if (position.current.stick) {
if (!dragging.current) el.scrollTop = el.scrollHeight;
} else if (!restored.current) el.scrollTop = position.current.top;
restored.current = true;
updateJumpVisibility(el);
});
useLayoutEffect(() => {
// Prepending earlier entries moved the first painted row down: follow it, so the same
@@ -381,80 +328,52 @@ export function Stream({
anchor.current = null;
if (position.current.stick || !from.el.isConnected) return;
scroller.scrollTop += from.el.getBoundingClientRect().top - from.top;
updateJumpVisibility(scroller);
});
useLayoutEffect(() => {
const el = ref.current;
if (!el) return;
const observer = new ResizeObserver(() => {
trimSlack();
if (position.current.stick && !dragging.current) el.scrollTop = el.scrollHeight;
updateJumpVisibility(el);
});
observer.observe(el);
return () => {
observer.disconnect();
if (restored.current) positions.set(key, { ...position.current, top: el.scrollTop });
};
}, [key, positions, trimSlack, updateJumpVisibility]);
/**
* The wheel scrolls the innermost container under the pointer, and only that one: a run of
* calls from its headers, a tool output from its text, the conversation elsewhere. A container
* at its edge doesn't hand the rest to the conversation; a gesture stays with the container
* it started in.
*/
}, [key, positions]);
// How far the end was below the view when a section was toggled, before its content renders.
const gapAtToggle = useRef(Infinity);
useEffect(() => {
const el = ref.current;
if (!el) return;
let gesture: { owner: HTMLElement; at: number } | null = null;
const onWheel = (e: WheelEvent) => {
if (e.defaultPrevented || e.ctrlKey || e.metaKey) return;
if (e.shiftKey || Math.abs(e.deltaX) > Math.abs(e.deltaY)) return;
const now = performance.now();
const latched = gesture && now - gesture.at < WHEEL_GESTURE_MS && gesture.owner.isConnected;
const owner = latched ? gesture!.owner : scrollOwner(e.target, el);
gesture = { owner, at: now };
if (owner !== el) {
const room = e.deltaY < 0 ? owner.scrollTop : owner.scrollHeight - owner.clientHeight - owner.scrollTop;
if (room <= 1) e.preventDefault();
return;
}
markUserScroll();
if (e.deltaY < 0) stopFollowing(e.target);
else if (e.deltaY > 0) scrollingUp.current = false;
const toggled = () => {
gapAtToggle.current = el.scrollHeight - el.scrollTop - el.clientHeight;
};
el.addEventListener("wheel", onWheel, { passive: false });
return () => el.removeEventListener("wheel", onWheel);
}, [markUserScroll, stopFollowing]);
el.addEventListener("toggle", toggled, true);
return () => el.removeEventListener("toggle", toggled, true);
}, []);
/**
* The reader opened or closed a section: put its header back where it was, in the run or
* output that scrolls it and then in the conversation. Following stops when that leaves any
* of the end out of view, so the next chunk doesn't pull the header away.
* An opened section grew the conversation below its header: with the end in view, stay at
* it; otherwise bring what it shows into view. Either way its header stays on screen, and
* following stops when that leaves the end out of view.
*/
const keepFoldHeader = useCallback(
(header: HTMLElement, top: number) => {
const revealFold = useCallback(
(fold: HTMLElement) => {
const el = ref.current;
if (!el?.contains(header)) return;
// Opened, the section fills the room left by an earlier fold first.
trimSlack();
for (let s = header.parentElement; s; s = s.parentElement) {
const moved = header.getBoundingClientRect().top - top;
if (Math.abs(moved) < 1) break;
if (s === el) {
const short = Math.ceil(el.scrollTop + moved + el.clientHeight - el.scrollHeight);
if (short > 0) setSlack(slack.current + short);
el.scrollTop += moved;
break;
}
if (scrollsY(s)) s.scrollTop += moved;
}
if (position.current.stick && el.scrollHeight - el.scrollTop - el.clientHeight >= 1) {
if (!el || dragging.current) return;
const view = el.getBoundingClientRect();
const box = fold.getBoundingClientRect();
const atEnd = position.current.stick || gapAtToggle.current < 40;
gapAtToggle.current = Infinity;
const below = atEnd ? el.scrollHeight - el.scrollTop - el.clientHeight : box.bottom - view.bottom;
if (below > 0) el.scrollTop += Math.max(0, Math.min(below, box.top - view.top));
if (atEnd && el.scrollHeight - el.scrollTop - el.clientHeight >= 40) {
position.current = { top: el.scrollTop, stick: false };
positions.set(key, position.current);
setAway(true);
}
updateJumpVisibility(el);
},
[key, positions, setSlack, trimSlack, updateJumpVisibility],
[key, positions],
);
/** Back to the end of the stream; following resumes from there. */
const jumpToLatest = useCallback(() => {
@@ -535,7 +454,7 @@ export function Stream({
);
return (
<OpenFolds.Provider value={openFolds}>
<KeepFoldHeader.Provider value={keepFoldHeader}>
<RevealFold.Provider value={revealFold}>
<div className={styles.streamArea}>
{finding && <FindBar streamRef={ref} focus={findFocus} onClose={onCloseFind} />}
<div
@@ -543,6 +462,12 @@ export function Stream({
// The conversation is read and copied like a document; focusable so ⌘F reaches it.
className={clsx(styles.stream, selectableText)}
tabIndex={-1}
onWheel={(e) => {
if (e.defaultPrevented) return;
markUserScroll();
if (e.deltaY < 0 && !e.ctrlKey && !e.metaKey) stopFollowing(e.target);
else if (e.deltaY > 0 && !e.ctrlKey && !e.metaKey) scrollingUp.current = false;
}}
onTouchStart={(e) => {
touchY.current = e.touches.length === 1 ? e.touches[0]!.clientY : null;
}}
@@ -572,7 +497,6 @@ export function Stream({
}}
onScroll={(e) => {
const el = e.currentTarget;
trimSlack();
const atEnd = el.scrollHeight - el.scrollTop - el.clientHeight < 40;
const laidOut =
el.scrollHeight !== seenHeight.current.content || el.clientHeight !== seenHeight.current.view;
@@ -589,7 +513,7 @@ export function Stream({
if (stick && !atEnd && !dragging.current) el.scrollTop = el.scrollHeight;
position.current = { top: el.scrollTop, stick };
positions.set(key, position.current);
updateJumpVisibility(el);
setAway(!position.current.stick);
// Reached the top of what is painted: fetch the earlier entries, but only
// once the drag has settled.
if (loadTimer.current !== null) window.clearTimeout(loadTimer.current);
@@ -636,41 +560,33 @@ export function Stream({
) : entries.length === 0 && !busy && !loadError ? (
<EmptyState title="No conversation history" />
) : (
rows.map((row) => {
const images = toolImages(row);
return (
<div
key={row.index}
className={styles.conversationRow}
data-message={
(row.kind === "entry" && (row.entry.type === "user" || row.entry.type === "agent")) || undefined
}
data-process={row.kind !== "entry" || row.entry.type !== "user" || undefined}
data-author={authorHeaders.has(row.index) || undefined}
>
{authorHeaders.has(row.index) && (
<div className={styles.agentAuthor}>
<div className={styles.role}>
<Icon name={providerIcon(task.provider)} size={13} />
<span>{providerName(task.provider)}</span>
</div>
rows.map((row) => (
<div
key={row.index}
className={styles.conversationRow}
data-message={
(row.kind === "entry" && (row.entry.type === "user" || row.entry.type === "agent")) || undefined
}
data-process={row.kind !== "entry" || row.entry.type !== "user" || undefined}
data-author={authorHeaders.has(row.index) || undefined}
>
{authorHeaders.has(row.index) && (
<div className={styles.agentAuthor}>
<div className={styles.role}>
<Icon name={providerIcon(task.provider)} size={13} />
<span>{providerName(task.provider)}</span>
</div>
)}
{renderConversationRow(row)}
{images.length > 0 && (
<div className={styles.toolImages}>
<ImageStrip images={images} />
</div>
)}
</div>
);
})
</div>
)}
{renderConversationRow(row)}
</div>
))
)}
<WorkingRow task={task} entries={entries} subagent={subagent} />
</div>
{away && !!entries?.length && <JumpToLatest onJump={jumpToLatest} />}
</div>
</KeepFoldHeader.Provider>
</RevealFold.Provider>
</OpenFolds.Provider>
);
}
+35 -1
View File
@@ -7,7 +7,7 @@ import { notifications } from "@/workbench/contributions";
import clsx from "clsx";
import { memo, useLayoutEffect, useRef, useState, type RefObject } from "react";
import { AgentReply, MessageActions, ReplyActions } from "../AgentReply";
import { ImageStrip } from "../ImageStrip";
import { ImagePreview, imageSrc } from "../ImagePreview";
import { ReferencedText } from "../ReferenceChip";
import styles from "../Session.module.css";
import { SubmitButton } from "../SubmitButton";
@@ -425,3 +425,37 @@ function MessageEditor({
</div>
);
}
/** Image thumbnails; a click opens the full image, `onRemove` adds a remove button to each. */
function ImageStrip({ images, onRemove }: { images: AgentImage[]; onRemove?: (index: number) => void }) {
const tx = useTx();
const [open, setOpen] = useState<AgentImage | null>(null);
if (images.length === 0) return null;
return (
<div className={styles.images}>
{images.map((img, i) => (
<span key={i} className={styles.imageItem}>
<button
type="button"
className={styles.imageButton}
title={img.name ?? undefined}
onClick={() => setOpen(img)}
>
<img className={styles.image} src={imageSrc(img)} alt={img.name ?? tx("Image")} />
</button>
{onRemove && (
<IconButton
type="button"
className={styles.removeImage}
aria-label={tx("Remove Image")}
onClick={() => onRemove(i)}
icon="close"
size="small"
/>
)}
</span>
))}
<ImagePreview image={open} onClose={() => setOpen(null)} />
</div>
);
}
+65 -155
View File
@@ -459,37 +459,6 @@ describe("process folding", () => {
});
});
describe("tool result images", () => {
it.each([
["grouped", true],
["grouped", false],
["each", true],
["each", false],
] as const)("keeps tool images visible with %s tools and folded turns=%s", async (toolCalls, foldTurns) => {
useProject.setState({ settings: { agents: { toolCalls, foldTurns } } as never });
const image = { mimeType: "image/png", data: "aW1hZ2U=", name: null };
backend.entries.set("A", [
{ type: "user", text: "Render a preview", attachments: [], steered: false, sentMs: 1000, doneMs: 2000 },
{ type: "thought", text: "Rendering" },
tool("preview", { images: [image] }),
tool("inspect", { output: "Preview ready" }),
{ type: "agent", text: "Here is the result." },
]);
useAgents.setState({ entries: new Map(backend.entries) });
render(<SessionEditor input={input("A")} />);
await screen.findByText("Here is the result.");
const preview = screen.getByRole("img", { name: "Image" });
expect(preview).toHaveAttribute("src", "data:image/png;base64,aW1hZ2U=");
expect(preview.closest("details")).toBeNull();
fireEvent.click(preview.closest("button")!);
const dialog = await screen.findByRole("dialog", { name: "Image" });
expect(within(dialog).getByRole("img")).toHaveAttribute("src", "data:image/png;base64,aW1hZ2U=");
fireEvent.click(within(dialog).getByText("Close", { selector: "button" }));
expect(screen.queryByRole("dialog")).toBeNull();
expect(screen.getAllByRole("img", { name: "Image" })).toHaveLength(1);
});
});
describe("turn folding", () => {
it("folds a finished turn's work under its message and keeps the reply", async () => {
backend.entries.set("A", [
@@ -769,31 +738,6 @@ describe("the conversation selection", () => {
});
describe("scrolling", () => {
it("hides Jump to Latest while the end is visible even when following has stopped", async () => {
render(<SessionEditor input={input("A")} />);
await screen.findByText("Answer A");
const el = stream();
let height = 1000;
Object.defineProperty(el, "scrollHeight", { configurable: true, get: () => height });
Object.defineProperty(el, "clientHeight", { configurable: true, value: 400 });
el.style.paddingBottom = "12px";
el.scrollTop = 599.75;
fireEvent.scroll(el);
fireEvent.wheel(el, { deltaY: -2 });
const jump = () => screen.queryByRole("button", { name: "Jump to Latest" });
expect(jump()).toBeNull();
el.scrollTop = 594;
fireEvent.scroll(el);
expect(jump()).toBeNull();
el.scrollTop = 580;
fireEvent.scroll(el);
expect(jump()).toBeInTheDocument();
// The end moves into view when content shrinks, without a downward gesture.
height = 980;
fireEvent.scroll(el);
expect(jump()).toBeNull();
});
it("returns to the end when the user sends a message while scrolled up", async () => {
const reply = { type: "agent", text: "Initial reply" } as AgentEntry;
useAgents.setState({ entries: new Map([["A", [reply]]]) });
@@ -828,106 +772,74 @@ describe("scrolling", () => {
expect(screen.queryByRole("button", { name: "Jump to Latest" })).toBeNull();
});
/** A stream whose height follows its fold and whose offset is clamped like a browser's. */
const foldingStream = (openHeight: number) => {
it.each([
{
name: "stays at the end below it",
top: 300,
bottom: 360,
scrolled: 60,
away: false,
},
{
name: "keeps its header on screen",
top: 50,
bottom: 900,
scrolled: 50,
away: true,
},
{
name: "back at the end without following",
top: 300,
bottom: 360,
scrolled: 60,
away: false,
released: true,
},
])("scrolls a section opened at the end into view: $name", async ({ top, bottom, scrolled, away, released }) => {
backend.entries.set("A", [
{ type: "thought", text: "Weighing it" },
{ type: "agent", text: "Answer A" },
]);
useAgents.setState({ entries: new Map(backend.entries) });
render(<SessionEditor input={input("A")} />);
await screen.findByText("Answer A");
const el = stream();
const fold = el.querySelector("details")!;
const slack = () => parseFloat(el.style.getPropertyValue("--stream-slack")) || 0;
const height = () => (fold.children.length > 1 ? 1000 + openHeight : 1000) + slack();
let top = 0;
Object.defineProperty(el, "scrollHeight", { configurable: true, get: height });
Object.defineProperty(el, "clientHeight", { configurable: true, value: 400 });
Object.defineProperty(el, "scrollTop", {
Object.defineProperty(el, "scrollHeight", {
configurable: true,
get: () => Math.max(0, Math.min(top, height() - 400)),
set: (v: number) => {
top = Math.max(0, Math.min(v, height() - 400));
},
value: 1000,
});
return { el, fold, summary: fold.querySelector("summary")!, slack };
};
it("keeps the header of a section opened at the end in place and stops following", async () => {
backend.entries.set("A", [
{ type: "thought", text: "Weighing it" },
{ type: "agent", text: "Answer A" },
]);
useAgents.setState({ entries: new Map(backend.entries) });
render(<SessionEditor input={input("A")} />);
await screen.findByText("Answer A");
const { el, summary } = foldingStream(500);
summary.getBoundingClientRect = () => ({ top: 900 - el.scrollTop }) as DOMRect;
Object.defineProperty(el, "clientHeight", {
configurable: true,
value: 400,
});
el.getBoundingClientRect = () => ({ top: 0, bottom: 400 }) as DOMRect;
el.scrollTop = 600;
fireEvent.scroll(el);
fireEvent.click(summary);
expect(el.scrollTop).toBe(600);
expect(screen.getByRole("button", { name: "Jump to Latest" })).toBeInTheDocument();
act(() =>
useAgents.setState({
entries: new Map([["A", [...backend.entries.get("A")!, { type: "agent", text: "More" }]]]),
}),
);
expect(el.scrollTop).toBe(600);
});
it("keeps the header of a section closed at the end in place", async () => {
backend.entries.set("A", [
{ type: "thought", text: "Weighing it" },
{ type: "agent", text: "Answer A" },
]);
useAgents.setState({ entries: new Map(backend.entries) });
render(<SessionEditor input={input("A")} />);
await screen.findByText("Answer A");
const { el, fold, summary, slack } = foldingStream(500);
summary.getBoundingClientRect = () => ({ top: 1200 - el.scrollTop }) as DOMRect;
fireEvent.click(summary);
expect(fold.open).toBe(true);
el.scrollTop = 1100;
if (released) {
fireEvent.wheel(el, { deltaY: -50 });
el.scrollTop = 550;
fireEvent.scroll(el);
el.scrollTop = 600;
fireEvent.scroll(el);
expect(screen.getByRole("button", { name: "Jump to Latest" })).toBeInTheDocument();
}
const fold = stream().querySelector("details")!;
fold.getBoundingClientRect = () => ({ top, bottom }) as DOMRect;
// It grows once its content renders.
Object.defineProperty(el, "scrollHeight", {
configurable: true,
get: () => (fold.children.length > 1 ? 1000 + bottom - top : 1000),
});
fireEvent.pointerDown(fold);
fireEvent.pointerUp(fold);
fold.open = true;
act(() => {
fireEvent(fold, new Event("toggle"));
});
expect(el.scrollTop).toBe(600 + scrolled);
fireEvent.scroll(el);
// Closing it would pull the end up to 600: room below keeps the header at 100.
fireEvent.click(summary);
expect(fold.open).toBe(false);
expect(el.scrollTop).toBe(1100);
expect(slack()).toBe(500);
// Scrolling up takes the room back without moving the content.
el.scrollTop = 1000;
fireEvent.scroll(el);
expect(slack()).toBe(400);
expect(el.scrollTop).toBe(1000); // Opened again, the section fills that room first: nothing moves and no blank is left below.
fireEvent.click(summary);
expect(fold.open).toBe(true);
expect(slack()).toBe(0);
expect(el.scrollTop).toBe(1000);
});
it("scrolls the innermost container under the wheel and never hands it to the conversation", () => {
const transcript: AgentEntry[] = [tool("live", { status: "running", output: "Tool output" })];
useAgents.setState({ entries: new Map([["A", transcript]]) });
render(<SessionEditor input={input("A")} />);
const el = stream();
Object.defineProperty(el, "scrollHeight", { configurable: true, value: 1000 });
Object.defineProperty(el, "clientHeight", { configurable: true, value: 400 });
el.scrollTop = 600;
fireEvent.scroll(el);
const output = screen.getByText("Tool output");
output.style.overflowY = "auto";
Object.defineProperty(output, "scrollHeight", { configurable: true, value: 300 });
Object.defineProperty(output, "clientHeight", { configurable: true, value: 100 });
let now = 0;
vi.spyOn(performance, "now").mockImplementation(() => now);
// At its top, scrolling up over it stays with it.
output.scrollTop = 0;
expect(fireEvent.wheel(output, { deltaY: -4 })).toBe(false);
now = 1000;
output.scrollTop = 100;
expect(fireEvent.wheel(output, { deltaY: -4 })).toBe(true);
expect(screen.queryByRole("button", { name: "Jump to Latest" })).toBeNull();
// A gesture that started in the conversation stays there when the output slides under it.
now = 2000;
expect(fireEvent.wheel(el, { deltaY: -4 })).toBe(true);
now = 2050;
output.scrollTop = 0;
expect(fireEvent.wheel(output, { deltaY: -4 })).toBe(true);
// With the end out of view, the next chunk doesn't pull the reader away from the section.
expect(screen.queryByRole("button", { name: "Jump to Latest" }) !== null).toBe(away);
});
it("keeps following when the view grows taller and the browser pulls the offset back", () => {
@@ -1077,8 +989,6 @@ describe("scrolling", () => {
value: 400,
});
output.style.overflowY = "auto";
Object.defineProperty(output, "scrollHeight", { configurable: true, value: 300 });
Object.defineProperty(output, "clientHeight", { configurable: true, value: 100 });
output.scrollTop = 100;
el.scrollTop = 600;
fireEvent.scroll(el);
@@ -2619,7 +2529,7 @@ describe("import sessions dialog", () => {
backend.external = sessions;
open();
await listed("Login fix");
expect(screen.getByRole("dialog", { name: "Import Sessions" })).toBeInTheDocument();
expect(screen.getByRole("dialog", { name: "Import Sessions from Other Apps" })).toBeInTheDocument();
});
it("imports the selected session and opens it", async () => {
@@ -3136,7 +3046,7 @@ describe("last turn changes", () => {
const pane = await screen.findByRole("complementary", { name: "Changes" });
expect(await within(pane).findByText("a.ts")).toBeInTheDocument();
fireEvent.click(within(pane).getByRole("tab", { name: "Last Turn" }));
fireEvent.click(within(pane).getByRole("radio", { name: "Last Turn" }));
await waitFor(() => expect(within(pane).queryByText("a.ts")).toBeNull());
expect(within(pane).getByText("b.ts")).toBeInTheDocument();
expect(within(pane).getByText("Since the last turn started")).toBeInTheDocument();
@@ -3149,7 +3059,7 @@ describe("last turn changes", () => {
backend.turnChanges = [];
fireEvent.click(within(pane).getByRole("button", { name: "Refresh" }));
expect(await within(pane).findByText("The last turn changed no files")).toBeInTheDocument();
fireEvent.click(within(pane).getByRole("tab", { name: "Whole Task" }));
fireEvent.click(within(pane).getByRole("radio", { name: "Whole Task" }));
expect(await within(pane).findByText("a.ts")).toBeInTheDocument();
});
});
+7 -6
View File
@@ -2,23 +2,24 @@ import { lazyComponent } from "@/ui";
import { registerSettingsPages } from "@/workbench/contributions";
import { AGENTS_GROUP, MCP_PAGE, POLICY_PAGE, REGISTRY_PAGE, SKILLS_PAGE } from "./model";
/** Settings › Agents › Coding Agents, External MCP Servers, Skills, and Command Permissions (also used by the Settings window). */
export function activateSettingsPages(): () => void {
return registerSettingsPages([
{
id: REGISTRY_PAGE,
title: "Agent Setup",
title: "Coding Agents",
group: AGENTS_GROUP,
// First in Agents, which sits after Languages & Frameworks and before Tools.
order: 450,
keywords: ["agent", "acp", "registry", "install", "update", "Coding Agents"],
keywords: ["agent", "acp", "registry", "install", "update", "coding agent"],
component: lazyComponent(() => import("./AgentRegistryPage").then((m) => m.AgentRegistryPage)),
},
{
id: MCP_PAGE,
title: "MCP Connections",
title: "External MCP Servers",
group: AGENTS_GROUP,
order: 475,
keywords: ["mcp", "model context protocol", "servers", "tools", "agent", "External MCP Servers"],
keywords: ["mcp", "model context protocol", "servers", "tools", "agent"],
component: lazyComponent(() => import("./McpServersPage").then((m) => m.McpServersPage)),
},
{
@@ -31,10 +32,10 @@ export function activateSettingsPages(): () => void {
},
{
id: POLICY_PAGE,
title: "Command Rules",
title: "Command Permissions",
group: AGENTS_GROUP,
order: 490,
keywords: ["agent", "policy", "security", "whitelist", "blacklist", "Command Permissions", "exec"],
keywords: ["agent", "policy", "security", "whitelist", "blacklist", "permission", "command", "exec"],
component: lazyComponent(() => import("./AgentPolicyPage").then((m) => m.AgentPolicyPage)),
},
]);
+1 -1
View File
@@ -136,7 +136,7 @@ interface AgentsState {
external: ExternalSession[];
/** Why the external sessions could not be listed. */
externalError: string | null;
/** The Import Sessions dialog is open. */
/** The Import Sessions from Other Apps dialog is open. */
importOpen: boolean;
/** External sessions being imported (`provider:sessionId`), so none is imported twice. */
importing: ReadonlySet<string>;
+6 -13
View File
@@ -1,6 +1,6 @@
import type { AgentTask } from "@/bindings";
import type { Action } from "@/platform/actions";
import { t, tx } from "@/platform/i18n";
import { tx } from "@/platform/i18n";
import { auxiliaryWindow } from "@/platform/auxWindow";
import { useProject } from "@/platform/project";
import type { MenuItem } from "@/ui";
@@ -165,7 +165,7 @@ function arrangeMenu(tasks: AgentTask[], ids: string[]): MenuItem[] {
{
kind: "item",
id: "move-to-group",
label: "Group",
label: "Move to Group",
icon: "folder",
submenu: groupSubmenu(
ids,
@@ -194,7 +194,7 @@ function groupSubmenu(ids: string[], groups: OrganizeGroup[], current: Array<str
{
kind: "item",
id: "group:none",
label: "No Group",
label: "Remove from Group",
run: () => moveTasksToGroup(ids, null),
},
] satisfies MenuItem[])
@@ -213,11 +213,11 @@ export function groupMenu(group: OrganizeGroup): MenuItem[] {
export const taskActions: Action[] = [
{
id: "agents.importSessions",
title: "Import Sessions…",
title: "Import Sessions from Other Apps…",
category: "Agents",
icon: "download",
when: "projectOpen",
keywords: ["import", "other apps", "claude", "codex", "history", "transcript"],
keywords: ["import", "claude", "codex", "history", "transcript"],
run: showImportSessions,
},
{
@@ -398,14 +398,7 @@ export function taskMenu(tasks: AgentTask[]): MenuItem[] {
? ([
{ kind: "action", action: "agents.renameTask", label: "Rename…", icon: "edit", arg: task.id },
...(!auxiliaryWindow()
? ([
{
kind: "action",
action: "agents.moveToNewWindow",
label: t("app.window.askNew"),
arg: task.id,
},
] satisfies MenuItem[])
? ([{ kind: "action", action: "agents.moveToNewWindow", arg: task.id }] satisfies MenuItem[])
: []),
...(hasTaskTerminal(task, projectRoot)
? ([
@@ -78,7 +78,7 @@
}
.row {
display: grid;
grid-template-columns: min(38%, 176px) 5ch minmax(0, 1fr);
grid-template-columns: min(34%, 176px) 5ch minmax(0, 1fr);
align-items: center;
gap: var(--space-2);
min-width: 0;
@@ -365,29 +365,3 @@ it("prefers the same configuration over another selected tab with the same name"
expect(tabIds()).toEqual([1, 3]);
expect(useDebug.getState().sessions[3]?.runConfig?.id).toBe("b");
});
it("keeps a rerun tab in place and selected while its adapter starts", async () => {
ipc.debugStart.mockResolvedValueOnce({ status: "ok", data: 1 }).mockResolvedValueOnce({ status: "ok", data: 2 });
await startSession({ ...config("launch"), name: "main.c" });
await startSession({ ...config("launch"), name: "layout.c" });
useDebug.setState({ active: 1 });
let respond!: (r: { status: "ok"; data: number }) => void;
ipc.debugStart.mockImplementationOnce(() => new Promise((resolve) => (respond = resolve)) as never);
const rerun = rerunSession(1);
await vi.advanceTimersByTimeAsync(0);
handleDebugEvent(1, { kind: "terminated" });
// Stopped, the old tab still holds its place and the selection.
expect(tabIds()).toEqual([1, 2]);
expect(useDebug.getState().active).toBe(1);
// The adapter announces the new session before `debugStart` returns: it takes the tab at once.
handleDebugEvent(3, { kind: "started", name: "main.c", adapter: "lldb", parent: null } as never);
expect(tabIds()).toEqual([3, 2]);
expect(useDebug.getState().active).toBe(3);
respond({ status: "ok", data: 3 });
await rerun;
expect(tabIds()).toEqual([3, 2]);
expect(useDebug.getState().active).toBe(3);
});
+1 -1
View File
@@ -140,6 +140,7 @@ export async function javaLaunchConfig(
root: string,
preparation?: JavaPreparation,
): Promise<LaunchConfig> {
const cwd = rc.cwd ? join(root, rc.cwd) : root;
rc = await withEnvFiles(rc, root);
const parsed = parseJavaArgs(rc.args);
if (!parsed.mainClass) throw new Error(`No main class in '${rc.name}'`);
@@ -154,7 +155,6 @@ export async function javaLaunchConfig(
},
},
);
const cwd = resolved.cwd ? join(root, resolved.cwd) : root;
if (info.errorCount > 0 && !preparation?.report)
notifications().notify({
group: "run",
+9 -48
View File
@@ -348,19 +348,7 @@ function ownSession(id: DebugSessionId, event: DebugEvent): DebugSession | null
}
if (pendingStarts === 0) return null;
provisional.add(id);
// The new root session takes the tab it replaces now, not once `debugStart` returns.
const replaced = pendingReplacements[0];
const slot = replaced ? { tabOrder: replaced.tabOrder, pinned: replaced.pinned } : {};
const s =
event.kind === "started"
? adoptSession(id, { name: event.name, adapter: event.adapter, ...slot })
: adoptSession(id, slot);
if (replaced) {
takeReplacement(replaced);
useDebug.setState({ active: id });
publishContext();
}
return s;
return event.kind === "started" ? adoptSession(id, { name: event.name, adapter: event.adapter }) : adoptSession(id);
}
/**
@@ -392,26 +380,10 @@ function settleStart(id: DebugSessionId | null, discard = false) {
/** The session being rerun: its tab is the one the new session takes, pinned or not. */
let rerunOf: DebugSessionId | null = null;
/** Sessions whose Rerun is in progress: their tab stays selected when they terminate. */
const rerunning = new Set<DebugSessionId>();
interface ReplacedTab {
pinned?: boolean;
tabOrder?: number;
/** The finished tab, kept until the new session takes its place (`defer`). */
session?: DebugSessionId;
}
/** Finished tabs whose starting replacements have no session yet, oldest start first. */
const pendingReplacements: ReplacedTab[] = [];
/** The new session is shown: the finished tab it replaces gives way. */
function takeReplacement(r: ReplacedTab | undefined) {
if (!r) return;
const i = pendingReplacements.indexOf(r);
if (i >= 0) pendingReplacements.splice(i, 1);
if (r.session != null && useDebug.getState().sessions[r.session]) removeSession(r.session);
r.session = undefined;
}
/**
@@ -420,20 +392,17 @@ function takeReplacement(r: ReplacedTab | undefined) {
* then the selected one; other finished tabs stay. The returned slot lets the new backend
* session keep the tab where the replaced one was.
*/
function replaceFinished(name: string, configId?: string, defer = false): ReplacedTab {
function replaceFinished(name: string, configId?: string): ReplacedTab {
const { sessions, active } = useDebug.getState();
const own = rerunOf != null ? sessions[rerunOf] : undefined;
rerunOf = null;
// Rerun's Stop waits for the adapter, even if this window has not handled its terminated event yet.
if (own) {
const tabOrder = tabOrderOf(own);
if (defer) return { pinned: own.pinned, tabOrder, session: own.id };
removeSession(own.id);
return { pinned: own.pinned, tabOrder };
}
const finished = sessionsInTabOrder(sessions).filter(
(s) => s.parent == null && !isLive(s) && !s.pinned && !pendingReplacements.some((r) => r.session === s.id),
);
const finished = sessionsInTabOrder(sessions).filter((s) => s.parent == null && !isLive(s) && !s.pinned);
const selected = active != null ? sessions[active] : undefined;
const ordered =
selected && finished.includes(selected) ? [selected, ...finished.filter((s) => s !== selected)] : finished;
@@ -444,7 +413,6 @@ function replaceFinished(name: string, configId?: string, defer = false): Replac
const pinned = workflowSettings().run.pinTabs || undefined;
if (!reused) return { pinned };
const tabOrder = tabOrderOf(reused);
if (defer) return { pinned, tabOrder, session: reused.id };
removeSession(reused.id);
return { pinned, tabOrder };
}
@@ -888,10 +856,7 @@ export async function startSession(
// Attaching to a JVM that may be gone: the finished session stays until the attach succeeds.
const afterDetach = justDetached(options.process);
const previousActive = useDebug.getState().active;
// The finished tab stays in place until the new session appears there.
let replaced =
!afterDetach && !options.preparation ? replaceFinished(launch.name, options.runConfig?.id, true) : undefined;
if (replaced?.session != null) pendingReplacements.push(replaced);
let replaced = !afterDetach && !options.preparation ? replaceFinished(launch.name, options.runConfig?.id) : undefined;
try {
if (options.show !== false && workflowSettings().run.showOnStart) toolWindowService().show("debug");
} catch {
@@ -914,7 +879,6 @@ export async function startSession(
return null;
}
flushConsoleOutput();
takeReplacement(replaced);
const preparation = options.preparation && useDebug.getState().sessions[options.preparation.id];
useDebug.setState((s) => {
const cur = s.sessions[id] ?? blank(id, { status: "running" });
@@ -958,7 +922,6 @@ export async function startSession(
void syncSpecial();
return id;
} catch (e) {
takeReplacement(replaced);
settleStart(null, afterDetach);
if (afterDetach) {
// The JVM that announced the port ended as its previous debugger detached.
@@ -1114,18 +1077,16 @@ export async function rerunSession(id: DebugSessionId, options: { show?: boolean
const root = rootOf(s);
const launch = root.launch;
if (!root.runConfig && !launch) return;
rerunning.add(root.id);
if (isLive(root)) await stopSession(root.id);
rerunOf = root.id;
// A session debugged in place from Services reruns there too.
const show = options.show ?? (root.inPlace ? false : undefined);
try {
if (isLive(root)) await stopSession(root.id);
rerunOf = root.id;
// A session debugged in place from Services reruns there too.
const show = options.show ?? (root.inPlace ? false : undefined);
if (root.runConfig)
await executeAction("run.debugConfig", show === false ? { config: root.runConfig, show: false } : root.runConfig);
else await startSession(launch!, { show });
} finally {
rerunOf = null;
rerunning.delete(root.id);
}
}
@@ -1174,7 +1135,7 @@ function markTerminated(id: DebugSessionId) {
if (serverPages.delete(id) && page != null) void stopSession(page);
patch(id, { status: "terminated", endedAt: Date.now(), frames: [], selectedFrame: null, stoppedThread: null });
const st = useDebug.getState();
if (st.active === id && !rerunning.has(id)) {
if (st.active === id) {
// Prefer another live session (e.g. the parent of a finished child).
const other = sessionsInTabOrder(st.sessions).find(isLive);
if (other) useDebug.setState({ active: other.id });
+13 -44
View File
@@ -31,6 +31,9 @@
.bold {
font-weight: 600;
}
.flex {
flex: 1;
}
.ellipsis {
min-width: 0;
overflow: hidden;
@@ -437,49 +440,29 @@
display: flex;
flex-direction: column;
gap: var(--space-2);
width: 500px;
max-width: calc(100vw - 12px);
height: 200px;
max-height: calc(100vh - 12px);
padding: var(--space-3);
overflow: auto;
width: var(--submit-width);
min-width: 320px;
height: var(--submit-height);
min-height: 160px;
padding: 12px;
overflow: hidden;
resize: both;
}
.submitHeader {
display: flex;
flex: none;
align-items: flex-start;
justify-content: space-between;
gap: var(--space-1);
}
.submitHeading {
display: flex;
flex-wrap: wrap;
align-items: baseline;
align-self: center;
gap: var(--space-0-5) var(--space-2);
min-width: 0;
overflow-wrap: anywhere;
}
.submitCount {
color: var(--fg-secondary);
font-size: var(--fs-small);
}
.submitHeaderActions {
display: flex;
flex: none;
align-items: center;
gap: var(--space-1);
gap: 5px;
}
.submitEditor {
flex: 1;
min-height: 40px;
padding: var(--space-1) var(--space-2);
padding: 4px 6px;
border: 1px solid var(--border);
border-radius: var(--radius-control);
background: var(--bg-input);
color: var(--fg);
font: inherit;
line-height: var(--lh-code);
resize: none;
outline: none;
}
@@ -487,26 +470,12 @@
border-color: var(--focus-ring);
}
.submitError {
flex: 0 1 auto;
min-height: 0;
max-height: 35%;
overflow: auto;
overflow-wrap: anywhere;
flex: none;
color: var(--danger);
}
.submitButtons {
display: flex;
flex: none;
flex-wrap: wrap;
align-items: center;
gap: var(--space-1-5);
}
.submitButtons > button {
max-width: 100%;
height: auto;
min-height: var(--h-button);
padding-block: var(--space-1);
line-height: 1.2;
white-space: normal;
overflow-wrap: anywhere;
}
@@ -5,11 +5,9 @@
* Request Changes (not for the author) and Comment. Shown above the button that opened
* it, or centred in the window. 500×200, resizable.
*/
import { useEffect, useState } from "react";
import { useEffect, useState, type CSSProperties } from "react";
import { Button, IconButton, Popup, Spinner, T } from "@/ui";
import { resolveMonoFont } from "@/platform/fonts";
import { useTx, tx } from "@/platform/i18n";
import { useProject } from "@/platform/project";
import { ask } from "@/workbench/messages";
import { errorMessage } from "../api/client";
import type { GHPullRequestReviewEvent } from "../api/types";
@@ -27,25 +25,26 @@ export function showSubmitReview(number: number, anchor?: Element | null): Promi
// The details and the pending review are needed for the buttons and the header.
void loadPullRequestData(number, "details").catch(() => undefined);
void loadPullRequestData(number, "pendingReview").catch(() => undefined);
const at = anchor?.isConnected
? anchor
: { x: Math.round(window.innerWidth / 2) - 250, y: Math.round(window.innerHeight / 3) };
return openDialog<true>((done) => (
<SubmitReview
number={number}
draftKey={draftKey}
anchor={anchor?.isConnected ? anchor : "center"}
onClose={() => done(null)}
/>
<SubmitReview number={number} draftKey={draftKey} anchor={at} onClose={() => done(null)} />
));
}
function SubmitReview(props: { number: number; draftKey: string; anchor: Element | "center"; onClose: () => void }) {
const { number, draftKey, anchor, onClose } = props;
function SubmitReview(props: {
number: number;
draftKey: string;
anchor: Element | { x: number; y: number };
onClose: () => void;
}) {
const { number, draftKey, onClose } = props;
const t = useTx();
const details = usePullRequestData(number, "details").value;
const pending = usePullRequestData(number, "pendingReview").value;
const text = useReviewText((s) => s.text[draftKey] ?? "");
const activeDraftKey = useGhRepository((s) => reviewDraftKey(s.connection, number));
const editor = useProject((s) => s.settings?.editor);
const { family, size } = resolveMonoFont(undefined, editor);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
@@ -95,11 +94,12 @@ function SubmitReview(props: { number: number; draftKey: string; anchor: Element
setBusy(false);
}
};
const anchored = "getBoundingClientRect" in props.anchor;
return (
<Popup
open
anchor={anchor}
placement="top-start"
anchor={props.anchor}
placement={anchored ? "top-start" : "bottom-start"}
onClose={(reason) => {
// A click outside does not drop a review while it is being sent.
if (reason !== "outside" || !busy) onClose();
@@ -107,38 +107,26 @@ function SubmitReview(props: { number: number; draftKey: string; anchor: Element
role="dialog"
aria-label={t("Submit Review")}
className={styles.submitPopup}
resizable="both"
minWidth={260}
minHeight={160}
style={{ "--submit-width": "500px", "--submit-height": "200px" } as CSSProperties}
>
<div className={styles.submitHeader}>
<div className={styles.submitHeading}>
<span className={styles.bold}>
<T>Submit Review</T>
</span>
{comments > 0 && (
<span className={styles.submitCount}>
{comments === 1 ? t`${comments} pending comment` : t`${comments} pending comments`}
</span>
)}
</div>
<div className={styles.submitHeaderActions}>
{pending && comments > 0 && (
<IconButton icon="trash" size="small" title="Discard pending comments" disabled={busy} onClick={discard} />
)}
<IconButton icon="close" size="small" title="Close" onClick={onClose} />
</div>
<span className={styles.bold}>
<T>Submit Review</T>
</span>
{comments > 0 && (
<span>{comments === 1 ? t`${comments} pending comment` : t`${comments} pending comments`}</span>
)}
<span className={styles.flex} />
{pending && comments > 0 && (
<IconButton icon="trash" size="small" title="Discard pending comments" disabled={busy} onClick={discard} />
)}
<IconButton icon="close" size="small" title="Close" onClick={onClose} />
</div>
<textarea
data-autofocus
className={styles.submitEditor}
placeholder={t("Review comment")}
aria-label={t("Review comment")}
style={{
fontFamily: family,
fontSize: size,
lineHeight: editor?.lineHeight ? `${editor.lineHeight}px` : undefined,
}}
value={text}
onChange={(e) => {
setError(null);
@@ -146,7 +134,7 @@ function SubmitReview(props: { number: number; draftKey: string; anchor: Element
}}
/>
{error && (
<div className={styles.submitError} role="alert">
<div className={styles.submitError}>
<T>Failed to submit review</T>
<div className={styles.secondary}>{error}</div>
</div>
@@ -2,17 +2,22 @@ import { EditorView } from "@codemirror/view";
import { activeEditor, editorsFor, useEditorRegistry, type TextEditorHandle } from "@/editor/api";
import { tx } from "@/platform/i18n";
import { call, commands, emitLocalIdeEvent, IpcError } from "@/platform/ipc";
import { scratchesDir } from "@/platform/scratchesDir";
import { appDataDir } from "@/platform/platformInfo";
import { editorService } from "@/workbench/contributions";
import { appendRequests } from "./spring/request";
export const GENERATED_REQUESTS = "generated-requests.http";
async function scratchFile(): Promise<{ path: string; created: boolean }> {
const path = `${await scratchesDir()}/${GENERATED_REQUESTS}`;
const dir = `${await appDataDir()}/scratches`;
const ignoreExisting = (e: unknown) => {
if (!(e instanceof IpcError && e.kind === "alreadyExists")) throw e;
};
await call(commands.fsCreateDir(dir)).catch(ignoreExisting);
const path = `${dir}/${GENERATED_REQUESTS}`;
let created = true;
await call(commands.fsCreateFile(path)).catch((e) => {
if (!(e instanceof IpcError && e.kind === "alreadyExists")) throw e;
ignoreExisting(e);
created = false;
});
return { path, created };
+6 -8
View File
@@ -8,8 +8,8 @@
import { activeEditor, registerEditorContribution, registerLanguageMode } from "@/editor/api";
import { executeAction, getAction, registerActions } from "@/platform/actions";
import { call, commands, emitLocalIdeEvent, IpcError, isTauri } from "@/platform/ipc";
import { appDataDir } from "@/platform/platformInfo";
import { useProject } from "@/platform/project";
import { scratchesDir } from "@/platform/scratchesDir";
import {
editorService,
notifications,
@@ -116,13 +116,11 @@ function directoryArg(arg: unknown): string | null {
/** New HTTP Request: `requests[_n].http` in `directory`, else a scratch, with an example request. */
async function newRequest(directory?: string) {
try {
const dir = directory ?? (await scratchesDir());
if (directory) {
try {
await call(commands.fsCreateDir(dir));
} catch (e) {
if (!(e instanceof IpcError && e.kind === "alreadyExists")) throw e;
}
const dir = directory ?? `${await appDataDir()}/scratches`;
try {
await call(commands.fsCreateDir(dir));
} catch (e) {
if (!(e instanceof IpcError && e.kind === "alreadyExists")) throw e;
}
const names = new Set((await call(commands.fsReadDir(dir))).map((e) => e.name.toLowerCase()));
let name = "requests.http";
Loaded 100 of 192 files, more files were not shown because too many files have changed in this diff. Show more