mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-25 02:44:03 -10:00
Compare commits
43
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e6ad1bee8f | ||
|
|
3ed4fa6836 | ||
|
|
4990a90bbf | ||
|
|
762b509b66 | ||
|
|
2964b2ffc5 | ||
|
|
704952a6ae | ||
|
|
65007093e7 | ||
|
|
696ab0c3ba | ||
|
|
e282546697 | ||
|
|
93fb7b6a85 | ||
|
|
e691aa9fb3 | ||
|
|
44a12abbd7 | ||
|
|
497b25bf4a | ||
|
|
4ecfb98c94 | ||
|
|
f1d6b0dc1b | ||
|
|
f2cfe38931 | ||
|
|
d18ac58b56 | ||
|
|
0021a764c3 | ||
|
|
a30103d410 | ||
|
|
89798baa3c | ||
|
|
c09c9b8aaf | ||
|
|
995a9563f7 | ||
|
|
893d9af6e6 | ||
|
|
73496669e7 | ||
|
|
add914f7fb | ||
|
|
0fd0f08865 | ||
|
|
054d2ba517 | ||
|
|
738dc12ef7 | ||
|
|
6135a5326d | ||
|
|
403bb28ca4 | ||
|
|
3249d4ee90 | ||
|
|
79e41c85ff | ||
|
|
f0a7cca1b1 | ||
|
|
21f1e2bbb4 | ||
|
|
ffdb5d74f2 | ||
|
|
d4d9e7d191 | ||
|
|
6a41509fd2 | ||
|
|
6efece99a4 | ||
|
|
0fab45689f | ||
|
|
71090202b6 | ||
|
|
8ed08510ed | ||
|
|
500df4ffc4 | ||
|
|
81aa9418aa |
No files matched your search
+146
-32
@@ -359,6 +359,9 @@ struct TaskFile {
|
||||
/// `None` for a worktree task, and a task saved before these were recorded.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
touched: Option<BTreeSet<String>>,
|
||||
/// The checkout as the last turn started, its copies in the store's `<id>.turn` folder.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
turn: Option<worktree::TurnStart>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
subagents: Vec<SavedSubagent>,
|
||||
/// Turns to drop from the session once it is loaded (a fork of an earlier point).
|
||||
@@ -382,6 +385,8 @@ struct TaskState {
|
||||
saved: Option<String>,
|
||||
/// See `TaskFile::touched`.
|
||||
touched: Option<Arc<BTreeSet<String>>>,
|
||||
/// See `TaskFile::turn`.
|
||||
turn: Option<Arc<worktree::TurnStart>>,
|
||||
pending_rollback: u32,
|
||||
/// The user named the task; see `TaskFile::title_renamed`.
|
||||
title_renamed: bool,
|
||||
@@ -753,6 +758,7 @@ impl AgentManager {
|
||||
before: BTreeMap::new(),
|
||||
saved: None,
|
||||
touched: Some(BTreeSet::new()),
|
||||
turn: None,
|
||||
subagents: Vec::new(),
|
||||
pending_rollback: 0,
|
||||
title_renamed: true,
|
||||
@@ -866,6 +872,7 @@ impl AgentManager {
|
||||
before,
|
||||
saved,
|
||||
touched: (req.isolation == Isolation::Local).then(BTreeSet::new),
|
||||
turn: None,
|
||||
subagents: Vec::new(),
|
||||
pending_rollback: 0,
|
||||
title_renamed: false,
|
||||
@@ -1189,6 +1196,8 @@ impl AgentManager {
|
||||
before: (*s.before).clone(),
|
||||
saved: s.saved.clone(),
|
||||
touched: s.touched.as_deref().cloned(),
|
||||
// The source's next turn replaces its copies: the fork's last turn is one of its own.
|
||||
turn: None,
|
||||
subagents: s.conversation.saved_subagents(),
|
||||
pending_rollback: total - keep,
|
||||
title_renamed: s.title_renamed,
|
||||
@@ -1528,6 +1537,7 @@ impl AgentManager {
|
||||
self.tasks.write().remove(id);
|
||||
*task.deleted.lock() = true;
|
||||
let _ = std::fs::remove_file(self.shared.paths.store_dir.join(format!("{id}.json")));
|
||||
let _ = std::fs::remove_dir_all(task.turn_dir());
|
||||
let saved = task.state.lock().saved.clone();
|
||||
if let Some(saved) = saved
|
||||
&& !self.tasks.read().values().any(|t| t.state.lock().saved.as_ref() == Some(&saved))
|
||||
@@ -1570,18 +1580,47 @@ impl AgentManager {
|
||||
.await
|
||||
}
|
||||
|
||||
/// Content of `path` (in the task's directory) when the task started.
|
||||
pub async fn base_text(&self, id: &str, path: PathBuf) -> IdeResult<Option<String>> {
|
||||
let at = self.task(id)?.base();
|
||||
blocking(move || match at.rev()? {
|
||||
Some(rev) => worktree::file_at(at.cwd(), &path, &rev),
|
||||
None => Ok(None),
|
||||
/// The files the task's last turn changed, against the checkout as it started (while a
|
||||
/// turn runs: that turn's so far). None before the task's first turn.
|
||||
pub async fn turn_changes(&self, id: &str) -> IdeResult<Vec<AgentChange>> {
|
||||
let (cwd, turn, dir) = self.task(id)?.last_turn();
|
||||
let Some(turn) = turn else { return Ok(Vec::new()) };
|
||||
blocking(move || {
|
||||
let changed = match &turn.changed {
|
||||
Some(changed) => changed.clone(),
|
||||
None => worktree::changed_in_turn(&cwd, &turn)?.1,
|
||||
};
|
||||
worktree::turn_changes(&cwd, &turn, &dir, &changed)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Content of `path` (in the task's directory) as `view` compares it: when the task
|
||||
/// started, in `HEAD`, or when the last turn started.
|
||||
pub async fn base_text(&self, id: &str, path: PathBuf, view: AgentChangesView) -> IdeResult<Option<String>> {
|
||||
let task = self.task(id)?;
|
||||
if view == AgentChangesView::LastTurn {
|
||||
let (cwd, turn, dir) = task.last_turn();
|
||||
let Some(turn) = turn else { return Ok(None) };
|
||||
return blocking(move || worktree::turn_text(&cwd, &path, &turn, &dir)).await;
|
||||
}
|
||||
let at = task.base();
|
||||
blocking(move || {
|
||||
let rev = match view {
|
||||
AgentChangesView::Group => worktree::head_commit(at.cwd())?,
|
||||
_ => at.rev()?,
|
||||
};
|
||||
match rev {
|
||||
Some(rev) => worktree::file_at(at.cwd(), &path, &rev),
|
||||
None => Ok(None),
|
||||
}
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Rollback: puts the task's changed files among `rel_paths` (all with `None`) back as
|
||||
/// `view` compares them: as they were when it started, or as they are in `HEAD`.
|
||||
/// `view` compares them: as they were when it started, as they are in `HEAD`, or as they
|
||||
/// were when its last turn started.
|
||||
pub async fn rollback_changes(
|
||||
&self,
|
||||
id: &str,
|
||||
@@ -1592,15 +1631,18 @@ impl AgentManager {
|
||||
if task.state.lock().busy {
|
||||
return Err(IdeError::invalid("the agent is working: stop it before rolling back its changes"));
|
||||
}
|
||||
if view == AgentChangesView::LastTurn {
|
||||
return self.rollback_turn(&task, rel_paths).await;
|
||||
}
|
||||
let at = task.base();
|
||||
let (before, saved, touched) = {
|
||||
let s = task.state.lock();
|
||||
(s.before.clone(), s.saved.as_ref().map(|name| self.shared.paths.store_dir.join(name)), s.touched.clone())
|
||||
};
|
||||
let restamped = blocking(move || {
|
||||
let (restamped, restored) = blocking(move || {
|
||||
let (changes, rev) = match view {
|
||||
AgentChangesView::Group => (at.grouped_changes(&before)?.uncommitted, worktree::head_commit(at.cwd())?),
|
||||
AgentChangesView::SinceStart => (at.changes(&before)?, at.rev()?),
|
||||
AgentChangesView::SinceStart | AgentChangesView::LastTurn => (at.changes(&before)?, at.rev()?),
|
||||
};
|
||||
let changes = worktree::made_by_task(changes, touched.as_deref());
|
||||
let sources = match rev.as_deref() {
|
||||
@@ -1608,6 +1650,7 @@ impl AgentManager {
|
||||
None => Default::default(),
|
||||
};
|
||||
let mut restamped = Vec::new();
|
||||
let mut restored = Vec::new();
|
||||
for change in changes.iter().filter(|c| rel_paths.as_ref().is_none_or(|p| p.contains(&c.rel_path))) {
|
||||
// A rename goes back to its old path too; the new one is taken away first, so a
|
||||
// case-only rename on a case-insensitive disk ends as the old file.
|
||||
@@ -1617,6 +1660,58 @@ impl AgentManager {
|
||||
if before.contains_key(&change.rel_path) {
|
||||
restamped.push((change.rel_path.clone(), worktree::stamp(&change.path.0)));
|
||||
}
|
||||
restored.push(change.rel_path.clone());
|
||||
}
|
||||
}
|
||||
Ok((restamped, restored))
|
||||
})
|
||||
.await?;
|
||||
{
|
||||
let mut s = task.state.lock();
|
||||
if !restamped.is_empty() {
|
||||
let mut before = (*s.before).clone();
|
||||
before.extend(restamped);
|
||||
s.before = Arc::new(before);
|
||||
}
|
||||
// Rolled back further than the last turn: what it changed there is gone, not the turn's to list.
|
||||
if let Some(turn) = &s.turn
|
||||
&& let Some(changed) = &turn.changed
|
||||
&& restored.iter().any(|rel| changed.contains(rel))
|
||||
{
|
||||
let changed = changed.iter().filter(|rel| !restored.contains(rel)).cloned().collect();
|
||||
s.turn = Some(Arc::new(worktree::TurnStart { changed: Some(changed), ..(**turn).clone() }));
|
||||
}
|
||||
}
|
||||
task.persist();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Puts the last turn's changed files among `rel_paths` (all with `None`) back as they
|
||||
/// were when it started.
|
||||
async fn rollback_turn(&self, task: &Task, rel_paths: Option<Vec<String>>) -> IdeResult<()> {
|
||||
let (cwd, turn, dir) = task.last_turn();
|
||||
let Some(turn) = turn else { return Ok(()) };
|
||||
let (before, saved) = {
|
||||
let s = task.state.lock();
|
||||
(s.before.clone(), s.saved.as_ref().map(|name| self.shared.paths.store_dir.join(name)))
|
||||
};
|
||||
let restamped = blocking(move || {
|
||||
let changed = match &turn.changed {
|
||||
Some(changed) => changed.clone(),
|
||||
None => worktree::changed_in_turn(&cwd, &turn)?.1,
|
||||
};
|
||||
let mut restamped = Vec::new();
|
||||
for change in worktree::turn_changes(&cwd, &turn, &dir, &changed)?
|
||||
.iter()
|
||||
.filter(|c| rel_paths.as_ref().is_none_or(|p| p.contains(&c.rel_path)))
|
||||
{
|
||||
worktree::restore_turn(&cwd, &turn, &dir, change)?;
|
||||
// Back to the user's own edits from before the task: not a change of the task.
|
||||
if let Some(Some(_)) = before.get(&change.rel_path)
|
||||
&& let Some(copy) = saved.as_deref().and_then(|d| worktree::saved_copy(d, &change.rel_path))
|
||||
&& std::fs::read(&change.path.0).is_ok_and(|now| now == copy)
|
||||
{
|
||||
restamped.push((change.rel_path.clone(), worktree::stamp(&change.path.0)));
|
||||
}
|
||||
}
|
||||
Ok(restamped)
|
||||
@@ -1752,6 +1847,7 @@ impl Task {
|
||||
before: Arc::new(file.before),
|
||||
saved: file.saved,
|
||||
touched: file.touched.map(Arc::new),
|
||||
turn: file.turn.map(Arc::new),
|
||||
pending_rollback: file.pending_rollback,
|
||||
title_renamed: file.title_renamed,
|
||||
busy: false,
|
||||
@@ -1785,31 +1881,48 @@ impl Task {
|
||||
(s.before.clone(), s.touched.clone())
|
||||
}
|
||||
|
||||
/// The changed files of the checkout as a turn starts, when the task records what its turns change.
|
||||
async fn checkout_before_turn(&self) -> Option<Snapshot> {
|
||||
let cwd = {
|
||||
let s = self.state.lock();
|
||||
s.touched.as_ref()?;
|
||||
s.task.cwd.0.clone()
|
||||
};
|
||||
blocking(move || worktree::snapshot(&cwd)).await.ok()
|
||||
/// Where the copies of the files already changed as the last turn started are kept.
|
||||
fn turn_dir(&self) -> PathBuf {
|
||||
self.shared.paths.store_dir.join(format!("{}.turn", self.id))
|
||||
}
|
||||
|
||||
/// Records the files that changed in the checkout since `start`, as the turn ends, as the task's.
|
||||
async fn record_turn_changes(&self, start: Option<Snapshot>) {
|
||||
let Some(start) = start else { return };
|
||||
let cwd = self.state.lock().task.cwd.0.clone();
|
||||
let Ok(end) = blocking(move || worktree::snapshot(&cwd)).await else { return };
|
||||
let changed = worktree::changed_between(&start, &end);
|
||||
if changed.is_empty() {
|
||||
return;
|
||||
}
|
||||
/// The checkout as the last turn started, with the folder of its copies.
|
||||
fn last_turn(&self) -> (PathBuf, Option<Arc<worktree::TurnStart>>, PathBuf) {
|
||||
let s = self.state.lock();
|
||||
(s.task.cwd.0.clone(), s.turn.clone(), self.turn_dir())
|
||||
}
|
||||
|
||||
/// Records the checkout as a turn starts: what the turn's changes are compared with.
|
||||
async fn checkout_before_turn(&self) {
|
||||
let (cwd, previous, dir) = self.last_turn();
|
||||
let turn = match blocking(move || worktree::start_turn(&cwd, &dir, previous.as_deref())).await {
|
||||
Ok(turn) => Some(Arc::new(turn)),
|
||||
Err(e) => {
|
||||
tracing::warn!("recording the checkout as a turn of agent task {} starts: {e}", self.id);
|
||||
None
|
||||
}
|
||||
};
|
||||
self.state.lock().turn = turn;
|
||||
self.persist();
|
||||
}
|
||||
|
||||
/// Records the files that changed in the checkout while the turn ran: the turn's, and in
|
||||
/// the project's own checkout also the task's.
|
||||
async fn record_turn_changes(&self) {
|
||||
let (cwd, turn, _) = self.last_turn();
|
||||
let Some(turn) = turn else { return };
|
||||
let start = turn.clone();
|
||||
let Ok((in_worktree, all)) = blocking(move || worktree::changed_in_turn(&cwd, &start)).await else { return };
|
||||
{
|
||||
let mut s = self.state.lock();
|
||||
let Some(touched) = &s.touched else { return };
|
||||
let mut touched = (**touched).clone();
|
||||
touched.extend(changed);
|
||||
s.touched = Some(Arc::new(touched));
|
||||
if !in_worktree.is_empty()
|
||||
&& let Some(touched) = &s.touched
|
||||
{
|
||||
let mut touched = (**touched).clone();
|
||||
touched.extend(in_worktree);
|
||||
s.touched = Some(Arc::new(touched));
|
||||
}
|
||||
s.turn = Some(Arc::new(worktree::TurnStart { changed: Some(all), ..(*turn).clone() }));
|
||||
}
|
||||
self.persist();
|
||||
}
|
||||
@@ -1926,6 +2039,7 @@ impl Task {
|
||||
before: (*s.before).clone(),
|
||||
saved: s.saved.clone(),
|
||||
touched: s.touched.as_deref().cloned(),
|
||||
turn: s.turn.as_deref().cloned(),
|
||||
subagents: s.conversation.saved_subagents(),
|
||||
pending_rollback: s.pending_rollback,
|
||||
title_renamed: s.title_renamed,
|
||||
@@ -1977,11 +2091,11 @@ impl Task {
|
||||
/// the user stops one. The caller set `busy`.
|
||||
async fn run(self: Arc<Self>, mut prompt: AgentPrompt) {
|
||||
loop {
|
||||
let start = self.checkout_before_turn().await;
|
||||
self.checkout_before_turn().await;
|
||||
let result = self.turn(&prompt).await;
|
||||
self.cancel_pending.store(false, Ordering::Release);
|
||||
tokio::time::sleep(TURN_GRACE).await;
|
||||
self.record_turn_changes(start).await;
|
||||
self.record_turn_changes().await;
|
||||
let changed = self.state.lock().conversation.end_turn(Some(now_ms()));
|
||||
self.mark_dirty(changed);
|
||||
let send_now = self.send_now.swap(false, Ordering::AcqRel);
|
||||
|
||||
@@ -672,6 +672,8 @@ pub enum AgentChangesView {
|
||||
SinceStart,
|
||||
/// The uncommitted files against `HEAD`; commits made since the start stay.
|
||||
Group,
|
||||
/// What the last turn changed, against the checkout as that turn started.
|
||||
LastTurn,
|
||||
}
|
||||
|
||||
/// A task's uncommitted files and the commits made since it started.
|
||||
|
||||
@@ -2852,7 +2852,10 @@ async fn task_project_root_controls_local_and_worktree_repositories() {
|
||||
let changes = mgr.changes(&task.id).await.unwrap();
|
||||
assert_eq!(changes.len(), 1);
|
||||
assert_eq!(changes[0].path.0, task.cwd.0.join("file.txt"));
|
||||
assert_eq!(mgr.base_text(&task.id, changes[0].path.0.clone()).await.unwrap().as_deref(), Some("original\n"));
|
||||
assert_eq!(
|
||||
mgr.base_text(&task.id, changes[0].path.0.clone(), AgentChangesView::SinceStart).await.unwrap().as_deref(),
|
||||
Some("original\n")
|
||||
);
|
||||
let saved = std::fs::read(root.join("store").join(format!("{}.json", task.id))).unwrap();
|
||||
assert!(String::from_utf8(saved).unwrap().contains("projectRoot"));
|
||||
let mut old = serde_json::to_value(&task).unwrap();
|
||||
@@ -3636,6 +3639,178 @@ async fn changed(mgr: &AgentManager, id: &str) -> Vec<String> {
|
||||
mgr.changes(id).await.unwrap().into_iter().map(|c| c.rel_path).collect()
|
||||
}
|
||||
|
||||
/// Waits until the turn asks for permission, runs `work` (what the agent does), then stops it.
|
||||
async fn one_turn(mgr: &AgentManager, id: &str, prompt: Option<&str>, work: impl FnOnce()) {
|
||||
if let Some(prompt) = prompt {
|
||||
mgr.prompt(id, text(prompt), false).await.unwrap();
|
||||
}
|
||||
wait_for(mgr, id, AgentStatus::NeedsInput).await;
|
||||
work();
|
||||
mgr.cancel(id, None).unwrap();
|
||||
wait_for(mgr, id, AgentStatus::Ready).await;
|
||||
}
|
||||
|
||||
async fn turn_changed(mgr: &AgentManager, id: &str) -> Vec<(String, ide_vcs::ChangeKind, u32, u32)> {
|
||||
let changes = mgr.turn_changes(id).await.unwrap();
|
||||
changes.into_iter().map(|c| (c.rel_path, c.kind, c.added, c.removed)).collect()
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn the_last_turn_lists_and_rolls_back_only_its_own_changes() {
|
||||
use ide_vcs::ChangeKind::{Added, Deleted, Modified};
|
||||
for isolation in [Isolation::Local, Isolation::Worktree] {
|
||||
for eol in EOLS {
|
||||
let repo = Checkout::new(eol);
|
||||
repo.write("a.txt", "base\n");
|
||||
repo.write("gone.txt", "base\n");
|
||||
repo.write("mine.txt", "base\n");
|
||||
repo.commit("init");
|
||||
let mgr = manager(&repo.dir, Arc::new(FakeAgent::default()));
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
prompt: text("Hello"),
|
||||
provider: "claude".into(),
|
||||
isolation,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let cwd = task.cwd.0.clone();
|
||||
let write = |rel: &str, text: &str| {
|
||||
let text = match eol {
|
||||
Eol::Lf => text.to_owned(),
|
||||
Eol::Crlf => text.replace('\n', "\r\n"),
|
||||
};
|
||||
std::fs::write(cwd.join(rel), text).unwrap();
|
||||
};
|
||||
let read = |rel: &str| std::fs::read_to_string(cwd.join(rel)).unwrap().replace("\r\n", "\n");
|
||||
let case = format!("{isolation:?} {eol:?}");
|
||||
assert!(mgr.turn_changes(&task.id).await.unwrap().is_empty(), "{case}: no turn has ended yet");
|
||||
|
||||
one_turn(&mgr, &task.id, None, || {
|
||||
write("a.txt", "base\nturn 1\n");
|
||||
write("one.txt", "one\n");
|
||||
})
|
||||
.await;
|
||||
// The user's own work between the turns belongs to neither.
|
||||
write("mine.txt", "base\nmine\n");
|
||||
one_turn(&mgr, &task.id, Some("more"), || {
|
||||
write("a.txt", "base\nturn 1\nturn 2\n");
|
||||
write("one.txt", "one\ntwo\n");
|
||||
write("two.txt", "two\n");
|
||||
std::fs::remove_file(cwd.join("gone.txt")).unwrap();
|
||||
})
|
||||
.await;
|
||||
// And after the turn.
|
||||
write("later.txt", "mine\n");
|
||||
|
||||
assert_eq!(
|
||||
turn_changed(&mgr, &task.id).await,
|
||||
[
|
||||
("a.txt".into(), Modified, 1, 0),
|
||||
("gone.txt".into(), Deleted, 0, 1),
|
||||
("one.txt".into(), Modified, 1, 0),
|
||||
("two.txt".into(), Added, 1, 0),
|
||||
],
|
||||
"{case}"
|
||||
);
|
||||
let turn_base = |rel: &str| {
|
||||
let path = cwd.join(rel);
|
||||
let mgr = &mgr;
|
||||
let id = task.id.clone();
|
||||
async move {
|
||||
let text = mgr.base_text(&id, path, AgentChangesView::LastTurn).await.unwrap();
|
||||
text.map(|t| t.replace("\r\n", "\n"))
|
||||
}
|
||||
};
|
||||
assert_eq!(turn_base("a.txt").await.as_deref(), Some("base\nturn 1\n"), "{case}");
|
||||
assert_eq!(turn_base("gone.txt").await.as_deref(), Some("base\n"), "{case}");
|
||||
assert_eq!(turn_base("two.txt").await, None, "{case}");
|
||||
let whole: Vec<String> = changed(&mgr, &task.id).await;
|
||||
assert!(["a.txt", "one.txt"].iter().all(|f| whole.iter().any(|w| w == f)), "{case}: {whole:?}");
|
||||
|
||||
// One file, then the rest, after a restart: from the copies saved as the turn started.
|
||||
mgr.rollback_changes(&task.id, Some(vec!["one.txt".into()]), AgentChangesView::LastTurn).await.unwrap();
|
||||
assert_eq!(read("one.txt"), "one\n", "{case}");
|
||||
assert_eq!(turn_changed(&mgr, &task.id).await.len(), 3, "{case}");
|
||||
mgr.shutdown();
|
||||
let mgr = manager(&repo.dir, Arc::new(FakeAgent::default()));
|
||||
mgr.rollback_changes(&task.id, None, AgentChangesView::LastTurn).await.unwrap();
|
||||
assert_eq!(read("a.txt"), "base\nturn 1\n", "{case}");
|
||||
assert_eq!(read("gone.txt"), "base\n", "{case}");
|
||||
assert!(!cwd.join("two.txt").exists(), "{case}");
|
||||
assert_eq!(read("mine.txt"), "base\nmine\n", "{case}: the user's edit between turns stays");
|
||||
assert_eq!(read("later.txt"), "mine\n", "{case}: and the one after");
|
||||
assert!(mgr.turn_changes(&task.id).await.unwrap().is_empty(), "{case}");
|
||||
// The task's own changes from its first turn stay.
|
||||
let whole: Vec<String> = changed(&mgr, &task.id).await;
|
||||
assert!(["a.txt", "one.txt"].iter().all(|f| whole.iter().any(|w| w == f)), "{case}: {whole:?}");
|
||||
|
||||
mgr.delete(&task.id, true).await.unwrap();
|
||||
assert!(!repo.dir.join("store").join(format!("{}.turn", task.id)).exists(), "{case}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn rolling_back_the_whole_task_leaves_the_last_turn_nothing_to_list() {
|
||||
let repo = Checkout::new(Eol::Lf);
|
||||
repo.write("a.txt", "base\n");
|
||||
repo.commit("init");
|
||||
let mgr = manager(&repo.dir, Arc::new(FakeAgent::default()));
|
||||
let task = mgr
|
||||
.create(NewAgentTask { prompt: text("Hello"), provider: "claude".into(), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
one_turn(&mgr, &task.id, None, || repo.write("a.txt", "base\nturn 1\n")).await;
|
||||
one_turn(&mgr, &task.id, Some("more"), || repo.write("a.txt", "base\nturn 1\nturn 2\n")).await;
|
||||
assert_eq!(turn_changed(&mgr, &task.id).await.len(), 1);
|
||||
mgr.rollback_changes(&task.id, None, AgentChangesView::SinceStart).await.unwrap();
|
||||
assert_eq!(repo.read("a.txt"), "base\n");
|
||||
assert!(mgr.turn_changes(&task.id).await.unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_commit_made_in_the_last_turn_is_among_its_changes() {
|
||||
let repo = Checkout::new(Eol::Lf);
|
||||
repo.write("a.txt", "base\n");
|
||||
repo.commit("init");
|
||||
let mgr = manager(&repo.dir, Arc::new(FakeAgent::default()));
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
prompt: text("Hello"),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Worktree,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let cwd = task.cwd.0.clone();
|
||||
let git = |args: &[&str]| {
|
||||
let ok = std::process::Command::new("git")
|
||||
.args(["-c", "user.name=t", "-c", "user.email=t@t", "-c", "commit.gpgsign=false"])
|
||||
.args(args)
|
||||
.current_dir(&cwd)
|
||||
.status()
|
||||
.unwrap()
|
||||
.success();
|
||||
assert!(ok, "{args:?}");
|
||||
};
|
||||
one_turn(&mgr, &task.id, None, || {
|
||||
std::fs::write(cwd.join("a.txt"), "base\nagent\n").unwrap();
|
||||
std::fs::write(cwd.join("new.txt"), "new\n").unwrap();
|
||||
git(&["add", "."]);
|
||||
git(&["commit", "-q", "-m", "agent"]);
|
||||
})
|
||||
.await;
|
||||
let rel: Vec<String> = mgr.turn_changes(&task.id).await.unwrap().into_iter().map(|c| c.rel_path).collect();
|
||||
assert_eq!(rel, ["a.txt", "new.txt"]);
|
||||
mgr.rollback_changes(&task.id, None, AgentChangesView::LastTurn).await.unwrap();
|
||||
assert_eq!(std::fs::read_to_string(cwd.join("a.txt")).unwrap(), "base\n");
|
||||
assert!(!cwd.join("new.txt").exists());
|
||||
mgr.delete(&task.id, true).await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn work_uncommitted_by_a_reset_during_a_local_task_is_not_rolled_back() {
|
||||
for eol in EOLS {
|
||||
@@ -3652,7 +3827,7 @@ async fn work_uncommitted_by_a_reset_during_a_local_task_is_not_rolled_back() {
|
||||
repo.git(&["reset", "-q", "--soft", "HEAD~1"]);
|
||||
assert_eq!(changed(&mgr, &task.id).await, ["a.txt"], "{eol:?}");
|
||||
|
||||
let base = mgr.base_text(&task.id, repo.dir.join("a.txt")).await.unwrap();
|
||||
let base = mgr.base_text(&task.id, repo.dir.join("a.txt"), AgentChangesView::SinceStart).await.unwrap();
|
||||
assert_eq!(base.map(|b| b.replace("\r\n", "\n")).as_deref(), Some("base\n"), "{eol:?}");
|
||||
mgr.rollback_changes(&task.id, None, AgentChangesView::SinceStart).await.unwrap();
|
||||
assert_eq!(repo.read("a.txt"), "base\n", "{eol:?}");
|
||||
@@ -3792,7 +3967,11 @@ async fn a_local_task_in_a_repository_without_commits_lists_and_rolls_back_its_c
|
||||
let (mgr, task) = repo.task().await;
|
||||
repo.write("new.txt", "agent\n");
|
||||
assert_eq!(changed(&mgr, &task.id).await, ["new.txt"], "{eol:?}");
|
||||
assert_eq!(mgr.base_text(&task.id, repo.dir.join("new.txt")).await.unwrap(), None, "{eol:?}");
|
||||
assert_eq!(
|
||||
mgr.base_text(&task.id, repo.dir.join("new.txt"), AgentChangesView::SinceStart).await.unwrap(),
|
||||
None,
|
||||
"{eol:?}"
|
||||
);
|
||||
|
||||
mgr.rollback_changes(&task.id, None, AgentChangesView::SinceStart).await.unwrap();
|
||||
assert!(!repo.dir.join("new.txt").exists(), "{eol:?}");
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
use crate::model::{AgentChange, AgentChanges, AgentCommit};
|
||||
use ide_core::{IdeError, IdeResult, IpcPath};
|
||||
use ide_vcs::{ChangeKind, LogQuery, Repo};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{Duration, UNIX_EPOCH};
|
||||
@@ -610,7 +611,6 @@ pub(crate) fn restore(
|
||||
before: &BTreeMap<String, Stamp>,
|
||||
saved: Option<&Path>,
|
||||
) -> IdeResult<()> {
|
||||
let path = &change.path.0;
|
||||
let content = match before.get(&change.rel_path) {
|
||||
Some(None) => None,
|
||||
Some(Some(_)) => {
|
||||
@@ -626,11 +626,16 @@ pub(crate) fn restore(
|
||||
None => match rev {
|
||||
Some(rev) => {
|
||||
let repo = Repo::discover(cwd)?.ok_or_else(|| IdeError::invalid("not in a git repository"))?;
|
||||
repo.file_bytes_at(path, Some(rev))?
|
||||
repo.file_bytes_at(&change.path.0, Some(rev))?
|
||||
}
|
||||
None => None,
|
||||
},
|
||||
};
|
||||
put(&change.path.0, content)
|
||||
}
|
||||
|
||||
/// Writes `content` to `path`, or removes the file when there is none.
|
||||
fn put(path: &Path, content: Option<Vec<u8>>) -> IdeResult<()> {
|
||||
match content {
|
||||
Some(bytes) => {
|
||||
if let Some(parent) = path.parent() {
|
||||
@@ -646,6 +651,187 @@ pub(crate) fn restore(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The bytes of the copy of `rel` saved in `dir`, if there is one.
|
||||
pub(crate) fn saved_copy(dir: &Path, rel: &str) -> Option<Vec<u8>> {
|
||||
std::fs::read(dir.join(saved_name(rel))).ok()
|
||||
}
|
||||
|
||||
/// The checkout as the task's last turn started: what that turn's changes are compared with
|
||||
/// and rolled back to. Recorded like the task's own start: `HEAD`, the files already changed,
|
||||
/// and copies of those.
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(crate) struct TurnStart {
|
||||
/// `HEAD` then (`None` outside a repository or before its first commit).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub head: Option<String>,
|
||||
/// The files already changed then, stamped.
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub before: BTreeMap<String, Stamp>,
|
||||
/// The files among `before` with a copy in the task's turn folder.
|
||||
#[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
|
||||
pub saved: BTreeSet<String>,
|
||||
/// The files that changed while the turn ran, recorded as it ended (`None` while it runs).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub changed: Option<BTreeSet<String>>,
|
||||
}
|
||||
|
||||
/// Records the checkout at `cwd` as a turn starts, with copies of its changed files in `dir`.
|
||||
/// The copies `previous` saved of files unchanged since are kept rather than made again, so
|
||||
/// starting a turn copies little more than what the turn before it changed.
|
||||
pub(crate) fn start_turn(cwd: &Path, dir: &Path, previous: Option<&TurnStart>) -> IdeResult<TurnStart> {
|
||||
let Some(repo) = discover(cwd)? else { return Ok(TurnStart::default()) };
|
||||
let head = repo.head()?.1;
|
||||
// As the turn's end is read, so the two compare.
|
||||
let before = snapshot(cwd)?;
|
||||
let mut saved = BTreeSet::new();
|
||||
match previous {
|
||||
Some(previous) => {
|
||||
for rel in &previous.saved {
|
||||
let unchanged =
|
||||
before.get(rel).is_some_and(|now| now.is_some() && previous.before.get(rel) == Some(now));
|
||||
if unchanged {
|
||||
saved.insert(rel.clone());
|
||||
} else {
|
||||
let _ = std::fs::remove_file(dir.join(saved_name(rel)));
|
||||
}
|
||||
}
|
||||
}
|
||||
None => {
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
}
|
||||
for (rel, stamp) in &before {
|
||||
let path = repo.root().join(rel);
|
||||
if stamp.is_none()
|
||||
|| saved.contains(rel)
|
||||
|| !std::fs::metadata(&path).is_ok_and(|m| m.is_file() && m.len() <= SAVED_MAX)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
std::fs::create_dir_all(dir)?;
|
||||
// One that can't be copied is listed but can't be rolled back, as a large one.
|
||||
if std::fs::copy(&path, dir.join(saved_name(rel))).is_ok() {
|
||||
saved.insert(rel.clone());
|
||||
}
|
||||
}
|
||||
Ok(TurnStart { head, before, saved, changed: None })
|
||||
}
|
||||
|
||||
/// The files that changed in `cwd` since the turn `start` began: in the working tree (as
|
||||
/// `changed_between` sees them), and in the commits made since.
|
||||
pub(crate) fn changed_in_turn(cwd: &Path, start: &TurnStart) -> IdeResult<(Vec<String>, BTreeSet<String>)> {
|
||||
let end = snapshot(cwd)?;
|
||||
let worktree = changed_between(&start.before, &end);
|
||||
let mut all: BTreeSet<String> = worktree.iter().cloned().collect();
|
||||
if let Some(repo) = discover(cwd)?
|
||||
&& let (Some(from), Some(to)) = (&start.head, repo.head()?.1)
|
||||
&& *from != to
|
||||
{
|
||||
for f in repo.diff_revisions(from, &to)? {
|
||||
all.extend(f.old_path);
|
||||
all.insert(f.path);
|
||||
}
|
||||
}
|
||||
Ok((worktree, all))
|
||||
}
|
||||
|
||||
/// The content of `rel` as the turn `start` began (`None`: no file), its copies in `dir`.
|
||||
fn at_turn_start(repo: &Repo, rel: &str, start: &TurnStart, dir: &Path) -> IdeResult<Option<Vec<u8>>> {
|
||||
match start.before.get(rel) {
|
||||
Some(None) => Ok(None),
|
||||
Some(Some(_)) => match start.saved.contains(rel).then(|| saved_copy(dir, rel)).flatten() {
|
||||
Some(bytes) => Ok(Some(bytes)),
|
||||
None => Err(IdeError::invalid(format!(
|
||||
"{rel} had changes when the turn started that weren't saved; roll it back in Git instead"
|
||||
))),
|
||||
},
|
||||
None => match &start.head {
|
||||
Some(head) => repo.file_bytes_at(&repo.root().join(rel), Some(head)),
|
||||
None => Ok(None),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Added and removed lines from `old` to `new`; none for binary content.
|
||||
fn line_stats(old: Option<&[u8]>, new: Option<&[u8]>) -> (u32, u32) {
|
||||
if [old, new].iter().flatten().any(|b| b.contains(&0)) {
|
||||
return (0, 0);
|
||||
}
|
||||
let text = |b: Option<&[u8]>| b.map(|b| String::from_utf8_lossy(b).into_owned()).unwrap_or_default();
|
||||
ide_vcs::diff_hunks(&text(old), &text(new))
|
||||
.iter()
|
||||
.fold((0, 0), |(added, removed), h| (added + h.lines, removed + h.old_lines))
|
||||
}
|
||||
|
||||
/// The files among `changed` that differ from how they were as the turn `start` began.
|
||||
pub(crate) fn turn_changes(
|
||||
cwd: &Path,
|
||||
start: &TurnStart,
|
||||
dir: &Path,
|
||||
changed: &BTreeSet<String>,
|
||||
) -> IdeResult<Vec<AgentChange>> {
|
||||
let Some(repo) = discover(cwd)? else { return Ok(Vec::new()) };
|
||||
let mut out = Vec::new();
|
||||
for rel in changed {
|
||||
let path = repo.root().join(rel);
|
||||
// A folder (a submodule, say) or a file that can't be read has nothing to compare.
|
||||
let Some(now) = existing(&path) else { continue };
|
||||
let (kind, (added, removed)) = match at_turn_start(&repo, rel, start, dir) {
|
||||
Ok(then) if then == now => continue,
|
||||
Ok(then) => {
|
||||
let kind = match (&then, &now) {
|
||||
(None, _) => ChangeKind::Added,
|
||||
(_, None) => ChangeKind::Deleted,
|
||||
_ => ChangeKind::Modified,
|
||||
};
|
||||
(kind, line_stats(then.as_deref(), now.as_deref()))
|
||||
}
|
||||
// Its start wasn't saved: listed, without counts.
|
||||
Err(_) => (ChangeKind::Modified, (0, 0)),
|
||||
};
|
||||
out.push(AgentChange { path: IpcPath(path), rel_path: rel.clone(), kind, added, removed, old_path: None });
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The text of `path` as the turn `start` began, `None` when there was no file.
|
||||
pub(crate) fn turn_text(cwd: &Path, path: &Path, start: &TurnStart, dir: &Path) -> IdeResult<Option<String>> {
|
||||
let Some(repo) = discover(cwd)? else { return Ok(None) };
|
||||
let rel = rel_in(repo.root(), path)?;
|
||||
if let (None, Some(head)) = (start.before.get(&rel), &start.head) {
|
||||
return file_at(cwd, path, head);
|
||||
}
|
||||
let Some(bytes) = at_turn_start(&repo, &rel, start, dir)? else { return Ok(None) };
|
||||
let encoding = match ide_vfs::load_text(path) {
|
||||
Ok(loaded) => encoding_rs::Encoding::for_label(loaded.encoding.as_bytes()).unwrap_or(encoding_rs::UTF_8),
|
||||
Err(_) => ide_vfs::detect_encoding(&bytes, None),
|
||||
};
|
||||
Ok(Some(encoding.decode(&bytes).0.into_owned()))
|
||||
}
|
||||
|
||||
/// `path` relative to the repository at `root`, with `/` separators.
|
||||
fn rel_in(root: &Path, path: &Path) -> IdeResult<String> {
|
||||
let rel = path
|
||||
.strip_prefix(root)
|
||||
.map(Path::to_path_buf)
|
||||
.ok()
|
||||
.or_else(|| {
|
||||
// Another spelling of the same place (a link, `/var` and `/private/var`); the file may be gone.
|
||||
let root = dunce::canonicalize(root).ok()?;
|
||||
let parent = dunce::canonicalize(path.parent()?).ok()?;
|
||||
Some(parent.strip_prefix(&root).ok()?.join(path.file_name()?))
|
||||
})
|
||||
.ok_or_else(|| IdeError::invalid(format!("{} is outside the repository", path.display())))?;
|
||||
Ok(rel.components().map(|c| c.as_os_str().to_string_lossy()).collect::<Vec<_>>().join("/"))
|
||||
}
|
||||
|
||||
/// Puts `change` back as it was when the turn `start` began.
|
||||
pub(crate) fn restore_turn(cwd: &Path, start: &TurnStart, dir: &Path, change: &AgentChange) -> IdeResult<()> {
|
||||
let repo = repo_at(cwd)?;
|
||||
put(&change.path.0, at_turn_start(&repo, &change.rel_path, start, dir)?)
|
||||
}
|
||||
|
||||
pub(crate) fn file_at(cwd: &Path, path: &Path, rev: &str) -> IdeResult<Option<String>> {
|
||||
let Some(repo) = discover(cwd)? else { return Ok(None) };
|
||||
let encoding = match ide_vfs::load_text(path) {
|
||||
@@ -815,6 +1001,67 @@ mod tests {
|
||||
assert!(!created.path.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_turn_copies_only_what_changed_since_the_last_one() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let repo = tmp.path().join("repo");
|
||||
std::fs::create_dir(&repo).unwrap();
|
||||
git(&repo, &["init", "-q", "-b", "main"]);
|
||||
std::fs::write(repo.join("a.txt"), "base\n").unwrap();
|
||||
git(&repo, &["add", "."]);
|
||||
git(&repo, &["commit", "-q", "-m", "init"]);
|
||||
let dir = tmp.path().join("turn");
|
||||
let set = |names: &[&str]| names.iter().map(|n| (*n).to_owned()).collect::<BTreeSet<_>>();
|
||||
|
||||
std::fs::write(repo.join("a.txt"), "turn 1\n").unwrap();
|
||||
std::fs::write(repo.join("b.txt"), "b\n").unwrap();
|
||||
let first = start_turn(&repo, &dir, None).unwrap();
|
||||
assert_eq!(first.saved, set(&["a.txt", "b.txt"]));
|
||||
// A copy made again would replace this mark.
|
||||
std::fs::write(dir.join(saved_name("b.txt")), "kept\n").unwrap();
|
||||
|
||||
std::thread::sleep(std::time::Duration::from_millis(10));
|
||||
std::fs::write(repo.join("a.txt"), "turn two\n").unwrap();
|
||||
let second = start_turn(&repo, &dir, Some(&first)).unwrap();
|
||||
assert_eq!(second.saved, set(&["a.txt", "b.txt"]));
|
||||
assert_eq!(saved_copy(&dir, "a.txt").as_deref(), Some(&b"turn two\n"[..]));
|
||||
assert_eq!(saved_copy(&dir, "b.txt").as_deref(), Some(&b"kept\n"[..]));
|
||||
|
||||
// Back as committed: nothing to keep a copy of.
|
||||
git(&repo, &["checkout", "--", "a.txt"]);
|
||||
let third = start_turn(&repo, &dir, Some(&second)).unwrap();
|
||||
assert_eq!(third.saved, set(&["b.txt"]));
|
||||
assert_eq!(saved_copy(&dir, "a.txt"), None);
|
||||
// Without a record of the last turn (a task from before), every copy is made afresh.
|
||||
let fresh = start_turn(&repo, &dir, None).unwrap();
|
||||
assert_eq!(fresh.saved, set(&["b.txt"]));
|
||||
assert_eq!(saved_copy(&dir, "b.txt").as_deref(), Some(&b"b\n"[..]));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_turns_start_is_found_through_another_spelling_of_the_checkout() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let repo = dunce::canonicalize(tmp.path()).unwrap().join("repo");
|
||||
std::fs::create_dir(&repo).unwrap();
|
||||
git(&repo, &["init", "-q", "-b", "main"]);
|
||||
std::fs::write(repo.join("a.txt"), "base\n").unwrap();
|
||||
git(&repo, &["add", "."]);
|
||||
git(&repo, &["commit", "-q", "-m", "init"]);
|
||||
std::fs::write(repo.join("a.txt"), "turn 1\n").unwrap();
|
||||
let dir = tmp.path().join("turn");
|
||||
let start = start_turn(&repo, &dir, None).unwrap();
|
||||
std::fs::write(repo.join("a.txt"), "turn 2\n").unwrap();
|
||||
std::fs::write(repo.join("new.txt"), "new\n").unwrap();
|
||||
let link = tmp.path().join("link");
|
||||
std::os::unix::fs::symlink(&repo, &link).unwrap();
|
||||
for at in [&repo, &link] {
|
||||
assert_eq!(turn_text(&repo, &at.join("a.txt"), &start, &dir).unwrap().as_deref(), Some("turn 1\n"));
|
||||
assert_eq!(turn_text(&repo, &at.join("new.txt"), &start, &dir).unwrap(), None);
|
||||
}
|
||||
assert!(turn_text(&repo, &tmp.path().join("elsewhere.txt"), &start, &dir).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn commits_since_the_base_are_listed_with_their_files() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -536,7 +536,9 @@ impl PathMap {
|
||||
let abs = if p.is_absolute() {
|
||||
p.to_path_buf()
|
||||
} else {
|
||||
let in_base = base.map(|b| Path::new(b).join(p)).filter(|c| c.exists());
|
||||
// rustc prints workspace members' files relative to the workspace root, above
|
||||
// the member's manifest directory (`base`) when a member is built on its own.
|
||||
let in_base = base.and_then(|b| Path::new(b).ancestors().map(|a| a.join(p)).find(|c| c.exists()));
|
||||
in_base.unwrap_or_else(|| cwd.join(p))
|
||||
};
|
||||
let abs = normalize(&abs);
|
||||
@@ -1303,6 +1305,22 @@ mod tests {
|
||||
assert_eq!(identifier_len("x é_1 c", 2), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolves_a_member_build_s_workspace_relative_paths() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().to_path_buf();
|
||||
write(&root, "client/src/main.rs", "fn main() {}\n");
|
||||
write(&root, "client/src/lib.rs", "\n");
|
||||
write(&root, "src/lib.rs", "\n");
|
||||
let map = PathMap { root: root.clone(), canonical: None };
|
||||
let member = root.join("client");
|
||||
let base = member.to_str();
|
||||
// Build Module runs in the member; rustc names its files from the workspace root.
|
||||
assert_eq!(map.resolve("client/src/main.rs", &member, base), root.join("client/src/main.rs"));
|
||||
// A crate built from its own directory names them from there.
|
||||
assert_eq!(map.resolve("src/lib.rs", &member, base), member.join("src/lib.rs"));
|
||||
}
|
||||
|
||||
// Uses Unix absolute paths for the canonical root.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
|
||||
@@ -1875,6 +1875,14 @@ pub fn goto_declaration(text: &str, path: &Path, pos: Pos, local_repo: Option<Pa
|
||||
goto_declaration_in(text, path, pos, local_repo, Vec::new)
|
||||
}
|
||||
|
||||
/// The declaration of the property `name` in the pom at `path`, for files it configures
|
||||
/// outside the pom itself (a YAML resource's `@name@`): the first `<properties>` entry
|
||||
/// along the parent chain declaring it, `project.*` built-ins included.
|
||||
pub fn property_declaration(pom: &Path, name: &str, local_repo: Option<PathBuf>) -> Option<PomGoto> {
|
||||
let text = xml::read_text(pom)?;
|
||||
property_target(&text, pom, name, local_repo)
|
||||
}
|
||||
|
||||
/// [`goto_declaration`], where a `<parent>` and a dependency or plugin whose version no
|
||||
/// management entry provides (or a management entry itself) go to the artifact's own
|
||||
/// POM: the project module among `modules` with its coordinates, else the local
|
||||
|
||||
+117
-11
@@ -19,10 +19,16 @@ struct State {
|
||||
settings: Vec<(String, String)>,
|
||||
read_only: bool,
|
||||
session_id: String,
|
||||
session: Mutex<bool>,
|
||||
session: Mutex<Session>,
|
||||
closed: CancellationToken,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Session {
|
||||
initialized: bool,
|
||||
strict_read_only: bool,
|
||||
}
|
||||
|
||||
/// The response format: a names line, a types line, then one JSON array per row, so rows past
|
||||
/// the grid's limit are skipped without being parsed.
|
||||
const FORMAT: &str = "JSONCompactEachRowWithNamesAndTypes";
|
||||
@@ -109,12 +115,23 @@ impl ClickhousePool {
|
||||
settings: setup.params,
|
||||
read_only: source.read_only,
|
||||
session_id: uuid::Uuid::new_v4().to_string(),
|
||||
session: Mutex::new(false),
|
||||
session: Mutex::new(Session::default()),
|
||||
closed: CancellationToken::new(),
|
||||
}));
|
||||
let cancel = CancellationToken::new();
|
||||
let initialize = async {
|
||||
pool.execute("SELECT 1", 1, &cancel).await?;
|
||||
if let Err(error) = pool.execute("SELECT 1", 1, &cancel).await {
|
||||
if !rejects_driver_setting(&error) {
|
||||
return Err(error);
|
||||
}
|
||||
// Retry only the connection probe. Keep relying on the server for write protection
|
||||
// only after verifying strict read-only mode in this same session.
|
||||
pool.0.session.lock().await.strict_read_only = true;
|
||||
let result = pool.execute("SELECT getSetting('readonly')", 1, &cancel).await?;
|
||||
if result.rows.first().and_then(|row| row.first()).and_then(Option::as_deref) != Some("1") {
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
for sql in setup.statements {
|
||||
pool.execute(&sql, 0, &cancel).await?;
|
||||
}
|
||||
@@ -151,7 +168,7 @@ impl ClickhousePool {
|
||||
}
|
||||
|
||||
/// `max_rows`: the rows the server may send (the skipped ones included).
|
||||
fn request(&self, client: &Client, query_id: &str, max_rows: usize, initialized: bool) -> RequestBuilder {
|
||||
fn request(&self, client: &Client, query_id: &str, max_rows: usize, session: &Session) -> RequestBuilder {
|
||||
let mut request = client
|
||||
.post(self.0.endpoint.clone())
|
||||
.basic_auth(&self.0.user, Some(&self.0.password))
|
||||
@@ -162,16 +179,20 @@ impl ClickhousePool {
|
||||
("session_timeout", "3600".into()),
|
||||
("query_id", query_id.to_owned()),
|
||||
("default_format", FORMAT.into()),
|
||||
]);
|
||||
if !session.strict_read_only {
|
||||
request = request.query(&[
|
||||
("output_format_json_quote_denormals", "1".into()),
|
||||
("max_result_rows", max_rows.saturating_add(1).to_string()),
|
||||
("result_overflow_mode", "break".into()),
|
||||
]);
|
||||
if initialized {
|
||||
}
|
||||
if session.initialized {
|
||||
request = request.query(&[("session_check", "1")]);
|
||||
} else {
|
||||
request = request.query(&[("database", &self.0.database)]);
|
||||
}
|
||||
if self.0.read_only {
|
||||
if self.0.read_only && !session.strict_read_only {
|
||||
request = request.query(&[("readonly", "1")]);
|
||||
}
|
||||
request
|
||||
@@ -200,7 +221,7 @@ impl ClickhousePool {
|
||||
};
|
||||
let client = self.client()?;
|
||||
let query_id = uuid::Uuid::new_v4().to_string();
|
||||
let request = self.request(&client, &query_id, skip.saturating_add(max_rows), *session).body(sql.to_owned());
|
||||
let request = self.request(&client, &query_id, skip.saturating_add(max_rows), &session).body(sql.to_owned());
|
||||
let started = Instant::now();
|
||||
let fetch = async {
|
||||
let mut response = request.send().await.map_err(http_error)?;
|
||||
@@ -254,7 +275,7 @@ impl ClickhousePool {
|
||||
match result {
|
||||
Some(result) => {
|
||||
if result.is_ok() {
|
||||
*session = true;
|
||||
session.initialized = true;
|
||||
}
|
||||
result
|
||||
}
|
||||
@@ -323,9 +344,9 @@ type DecodedResult = (Vec<ResultColumn>, Vec<Vec<Option<String>>>, bool);
|
||||
|
||||
/// Decodes a streamed [`FORMAT`] body. Reads past the first `skip` rows unparsed (a later
|
||||
/// page), then keeps `max_rows` rows; later rows only set `has_more` and are read past
|
||||
/// unparsed, so a grid limit bounds memory however large the block
|
||||
/// `result_overflow_mode=break` lets the server send. A line that is not a JSON array
|
||||
/// starts the exception ClickHouse writes when a query fails mid-stream.
|
||||
/// unparsed, so a grid limit bounds memory even if a strict read-only server does not allow
|
||||
/// per-query result limits. A line that is not a JSON array starts the exception ClickHouse
|
||||
/// writes when a query fails mid-stream.
|
||||
struct RowReader {
|
||||
skip: usize,
|
||||
max_rows: usize,
|
||||
@@ -479,6 +500,20 @@ fn read_pem(path: &str, label: &str) -> IdeResult<Vec<u8>> {
|
||||
.map_err(|error| IdeError::new(ErrorKind::Io, format!("cannot read ClickHouse {label}: {error}")))
|
||||
}
|
||||
|
||||
fn rejects_driver_setting(error: &IdeError) -> bool {
|
||||
error
|
||||
.message
|
||||
.split_once(": ")
|
||||
.and_then(|(_, detail)| detail.strip_prefix("Code: 164. DB::Exception: Cannot modify '"))
|
||||
.and_then(|detail| detail.split_once("' setting in readonly mode"))
|
||||
.is_some_and(|(name, _)| {
|
||||
matches!(
|
||||
name,
|
||||
"output_format_json_quote_denormals" | "max_result_rows" | "result_overflow_mode" | "readonly"
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn reserved_setting(name: &str) -> bool {
|
||||
let name = name.to_ascii_lowercase();
|
||||
name.starts_with("output_format_json_")
|
||||
@@ -726,6 +761,77 @@ mod tests {
|
||||
task.await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn connects_when_server_forbids_settings_in_readonly_mode() {
|
||||
let (port, requests) = server(vec![
|
||||
(
|
||||
"500 Internal Server Error",
|
||||
"X-ClickHouse-Exception-Code: 164\r\n",
|
||||
"Code: 164. DB::Exception: Cannot modify 'output_format_json_quote_denormals' setting in readonly mode. (READONLY)",
|
||||
),
|
||||
("200 OK", "", ONE),
|
||||
("200 OK", "", "[\"n\"]\n[\"UInt64\"]\n[1]\n[2]\n"),
|
||||
])
|
||||
.await;
|
||||
let source = DataSource {
|
||||
read_only: true,
|
||||
properties: vec![DbProperty { name: "max_threads".into(), value: "2".into() }],
|
||||
..source(port)
|
||||
};
|
||||
let pool = Pool::connect(&source, None, None).await.unwrap();
|
||||
let result = pool.execute("SELECT number FROM numbers(2)", 1, &CancellationToken::new()).await.unwrap();
|
||||
assert_eq!(result.rows, vec![vec![Some("1".into())]]);
|
||||
assert!(result.has_more);
|
||||
|
||||
let requests = requests.await.unwrap();
|
||||
assert!(requests[0].ends_with("SELECT 1"));
|
||||
assert!(requests[0].contains("output_format_json_quote_denormals=1"));
|
||||
assert!(requests[1].ends_with("SELECT getSetting('readonly')"));
|
||||
assert!(requests[2].contains("session_check=1"));
|
||||
for request in &requests[1..] {
|
||||
assert!(request.contains("default_format=JSONCompactEachRowWithNamesAndTypes"));
|
||||
assert!(request.contains("max_threads=2"));
|
||||
for setting in
|
||||
["output_format_json_quote_denormals=", "max_result_rows=", "result_overflow_mode=", "readonly="]
|
||||
{
|
||||
assert!(!request.contains(setting), "{setting} is not allowed in a strict read-only session");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn readonly_probe_does_not_disable_settings_on_a_writable_session() {
|
||||
let (port, requests) = server(vec![
|
||||
(
|
||||
"500 Internal Server Error",
|
||||
"X-ClickHouse-Exception-Code: 164\r\n",
|
||||
"Code: 164. DB::Exception: Cannot modify 'max_result_rows' setting in readonly mode. (READONLY)",
|
||||
),
|
||||
("200 OK", "", "[\"readonly\"]\n[\"UInt64\"]\n[0]\n"),
|
||||
])
|
||||
.await;
|
||||
let source = DataSource { read_only: true, ..source(port) };
|
||||
let error = Pool::connect(&source, None, None).await.err().expect("writable session must stay rejected");
|
||||
assert!(error.message.contains("Cannot modify 'max_result_rows'"));
|
||||
assert!(requests.await.unwrap()[1].ends_with("SELECT getSetting('readonly')"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn readonly_probe_matches_only_the_driver_settings() {
|
||||
for (code, setting, expected) in [
|
||||
(164, "max_result_rows", true),
|
||||
(164, "result_overflow_mode", true),
|
||||
(164, "readonly", true),
|
||||
(164, "max_threads", false),
|
||||
(516, "max_result_rows", false),
|
||||
] {
|
||||
let error = IdeError::invalid(format!(
|
||||
"ClickHouse HTTP 500: Code: {code}. DB::Exception: Cannot modify '{setting}' setting in readonly mode. (READONLY)"
|
||||
));
|
||||
assert_eq!(rejects_driver_setting(&error), expected, "{setting}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn server_errors_keep_details_and_hide_passwords() {
|
||||
let (port, requests) = server(vec![(
|
||||
|
||||
@@ -236,7 +236,7 @@ impl Tool {
|
||||
destructive: false,
|
||||
output_schema: None,
|
||||
input_schema: json!({ "type": "object", "properties": {
|
||||
"projectPath": { "type": "string", "description": "Any directory inside an open project. Optional when only one project is open." }
|
||||
"projectPath": { "type": "string", "description": "Any directory inside an open project. Defaults to the connection's project (`?project=`) or the only open one." }
|
||||
}, "required": [] }),
|
||||
},
|
||||
handler: Arc::new(move |call| Box::pin(handler(call))),
|
||||
|
||||
@@ -369,10 +369,21 @@ pub async fn agent_delete(host: &Host, window: &str, task: String, remove_worktr
|
||||
host.project(window)?.agents.delete(&task, remove_worktree).await
|
||||
}
|
||||
|
||||
/// The task's changed files as `view` compares them (without: since it started).
|
||||
#[command(trust = trusted)]
|
||||
pub async fn agent_changes(host: &Host, window: &str, task: String) -> IdeResult<Vec<AgentChange>> {
|
||||
pub async fn agent_changes(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
task: String,
|
||||
view: Option<AgentChangesView>,
|
||||
) -> IdeResult<Vec<AgentChange>> {
|
||||
host.require_trust(window)?;
|
||||
host.project(window)?.agents.changes(&task).await
|
||||
let agents = &host.project(window)?.agents;
|
||||
match view.unwrap_or_default() {
|
||||
AgentChangesView::SinceStart => agents.changes(&task).await,
|
||||
AgentChangesView::Group => Ok(agents.grouped_changes(&task).await?.uncommitted),
|
||||
AgentChangesView::LastTurn => agents.turn_changes(&task).await,
|
||||
}
|
||||
}
|
||||
|
||||
/// The task's uncommitted changes and the commits made since it started.
|
||||
@@ -382,11 +393,17 @@ pub async fn agent_grouped_changes(host: &Host, window: &str, task: String) -> I
|
||||
host.project(window)?.agents.grouped_changes(&task).await
|
||||
}
|
||||
|
||||
/// Content of `path` when the task started (left side of its diff).
|
||||
/// Content of `path` as `view` compares it (without: when the task started), the left side of its diff.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn agent_base_text(host: &Host, window: &str, task: String, path: IpcPath) -> IdeResult<Option<String>> {
|
||||
pub async fn agent_base_text(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
task: String,
|
||||
path: IpcPath,
|
||||
view: Option<AgentChangesView>,
|
||||
) -> IdeResult<Option<String>> {
|
||||
host.require_trust(window)?;
|
||||
host.project(window)?.agents.base_text(&task, path.into_path_buf()).await
|
||||
host.project(window)?.agents.base_text(&task, path.into_path_buf(), view.unwrap_or_default()).await
|
||||
}
|
||||
|
||||
/// Rollback: the task's changed files among `paths` (all without) back as `view` compares them.
|
||||
|
||||
@@ -359,10 +359,22 @@ pub async fn lsp_goto(host: &Host, window: &str, doc: DocId, pos: Pos, kind: Got
|
||||
if kind != GotoKind::Definition {
|
||||
return result;
|
||||
}
|
||||
let Some((plugins, d)) = plugin_providers(host, window, doc, ProviderKind::Definition) else { return result };
|
||||
// A Maven placeholder (`@profileActive@` in `application.yml` or `.properties`) navigates to its pom.
|
||||
let maven = super::maven_placeholder::definition(host, window, doc, pos).await;
|
||||
let Some((plugins, d)) = plugin_providers(host, window, doc, ProviderKind::Definition) else {
|
||||
return match maven {
|
||||
None => result,
|
||||
Some(found) => {
|
||||
let in_string = in_string_literal(host, window, doc, pos).await;
|
||||
definition_targets(result, vec![found], in_string)
|
||||
}
|
||||
};
|
||||
};
|
||||
let found = plugin_call(move || plugins.provide_definition(&d, pos)).await.unwrap_or_default();
|
||||
let found: Vec<Location> =
|
||||
found.into_iter().map(|l| Location { path: l.path.into(), range: l.range, uri: None }).collect();
|
||||
let found: Vec<Location> = maven
|
||||
.into_iter()
|
||||
.chain(found.into_iter().map(|l| Location { path: l.path.into(), range: l.range, uri: None }))
|
||||
.collect();
|
||||
let in_string = !found.is_empty() && in_string_literal(host, window, doc, pos).await;
|
||||
definition_targets(result, found, in_string)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
//! ⌘B on a Maven resource-filtering placeholder: `@property@` in a YAML or properties
|
||||
//! resource (Spring's `application.yml` / `application.properties`) jumps to the `<properties>` entry that defines it,
|
||||
//! in the nearest `pom.xml` above the file, up through the project root. Parent
|
||||
//! poms the nearest pom declares itself are followed from there; a parent outside
|
||||
//! that walk that no pom declares is not.
|
||||
|
||||
use super::doc::blocking;
|
||||
use crate::Host;
|
||||
use ide_build::maven;
|
||||
use ide_core::{DocId, Location, Pos};
|
||||
use std::path::Path;
|
||||
|
||||
/// The definition location of the placeholder under `pos` in `doc`, when `doc` is a
|
||||
/// YAML or properties file holding a `@token@` there and a pom above it defines that property.
|
||||
pub(crate) async fn definition(host: &Host, window: &str, doc: DocId, pos: Pos) -> Option<Location> {
|
||||
let project = host.project(window).ok()?;
|
||||
blocking(move || {
|
||||
let snap = project.documents.text_snapshot(doc)?;
|
||||
if snap.large || !matches!(snap.language.as_str(), "yaml" | "properties") {
|
||||
return Ok(None);
|
||||
}
|
||||
let path = project.documents.identity(doc)?.0;
|
||||
let Some((name, _token_at)) = placeholder_at(&snap.text, pos) else { return Ok(None) };
|
||||
Ok(pom_defining(&project.root, &path, &name))
|
||||
})
|
||||
.await
|
||||
.ok()
|
||||
.flatten()
|
||||
}
|
||||
|
||||
/// The `@token@` enclosing `pos` on its line, with the token's range (UTF-16 columns).
|
||||
fn placeholder_at(text: &str, pos: Pos) -> Option<(String, ide_core::Range)> {
|
||||
let line = text.split_inclusive('\n').nth(pos.line as usize)?;
|
||||
let line = line.trim_end_matches(['\n', '\r']);
|
||||
let cursor = utf16_to_byte(line, pos.col)?;
|
||||
let mut opener: Option<usize> = None;
|
||||
for (i, b) in line.as_bytes().iter().enumerate() {
|
||||
if *b != b'@' {
|
||||
continue;
|
||||
}
|
||||
if let Some(start) = opener.replace(i) {
|
||||
let token = &line[start + 1..i];
|
||||
let valid =
|
||||
!token.is_empty() && token.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_'));
|
||||
if valid && start <= cursor && cursor <= i {
|
||||
let col = |byte: usize| line[..byte].encode_utf16().count() as u32;
|
||||
return Some((
|
||||
token.to_owned(),
|
||||
ide_core::Range::new(Pos::new(pos.line, col(start)), Pos::new(pos.line, col(i + 1))),
|
||||
));
|
||||
}
|
||||
opener = None;
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The nearest `pom.xml` above `from` (up to and including `root`) defining `name`.
|
||||
fn pom_defining(root: &Path, from: &Path, name: &str) -> Option<Location> {
|
||||
let mut dir = from.parent()?.to_path_buf();
|
||||
loop {
|
||||
let pom = dir.join("pom.xml");
|
||||
if pom.is_file()
|
||||
&& let Some(found) = maven::property_declaration(&pom, name, maven::default_local_repo())
|
||||
{
|
||||
return Some(Location::file(found.path, found.range));
|
||||
}
|
||||
if dir == root || !dir.starts_with(root) {
|
||||
return None;
|
||||
}
|
||||
dir = dir.parent()?.to_path_buf();
|
||||
}
|
||||
}
|
||||
|
||||
/// UTF-16 column → byte offset within one line.
|
||||
fn utf16_to_byte(line: &str, col: u32) -> Option<usize> {
|
||||
let col = col as usize;
|
||||
let mut units = 0usize;
|
||||
for (byte, c) in line.char_indices() {
|
||||
if units == col {
|
||||
return Some(byte);
|
||||
}
|
||||
units += c.len_utf16();
|
||||
if units > col {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
(units == col).then_some(line.len())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use ide_core::Pos;
|
||||
|
||||
fn at(line: u32, col: u32) -> Pos {
|
||||
Pos::new(line, col)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finds_the_placeholder_under_the_cursor_and_its_range() {
|
||||
let text = "spring:\n profiles:\n active: @profileActive@\n";
|
||||
let (name, range) = placeholder_at(text, at(2, 20)).unwrap();
|
||||
assert_eq!(name, "profileActive");
|
||||
assert_eq!(range.start, at(2, 12));
|
||||
assert_eq!(range.end, at(2, 27));
|
||||
// The `@`s themselves and inside the token navigate; just past the token does not.
|
||||
for col in [12u32, 13, 26] {
|
||||
assert_eq!(placeholder_at(text, at(2, col)).unwrap().0, "profileActive");
|
||||
}
|
||||
// A second pair on the line and unrelated cursors stay unresolved.
|
||||
let multi = "a: @one@ @two@\n";
|
||||
assert_eq!(placeholder_at(multi, at(0, 4)).unwrap().0, "one");
|
||||
assert_eq!(placeholder_at(multi, at(0, 10)).unwrap().0, "two");
|
||||
assert!(placeholder_at(multi, at(0, 8)).is_none(), "between the pairs");
|
||||
assert!(placeholder_at(multi, at(0, 9)).is_some(), "the opening @ of the next pair");
|
||||
assert!(placeholder_at(multi, at(0, 14)).is_none(), "just past the last pair");
|
||||
assert!(placeholder_at("value: plain\n", at(0, 7)).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_nearest_pom_wins_and_the_walk_stops_at_the_project_root() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
let deep = root.join("core/src/main/resources");
|
||||
std::fs::create_dir_all(&deep).unwrap();
|
||||
std::fs::write(
|
||||
root.join("pom.xml"),
|
||||
"<project>\n <properties>\n <parentName>parent</parentName>\n </properties>\n</project>\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::create_dir_all(root.join("core")).unwrap();
|
||||
std::fs::write(
|
||||
root.join("core/pom.xml"),
|
||||
"<project>\n <properties>\n <name>module</name>\n </properties>\n</project>\n",
|
||||
)
|
||||
.unwrap();
|
||||
let from = deep.join("application.yml");
|
||||
// The module pom defines `name` first: its file wins, pointing at its `<name>` entry.
|
||||
let found = pom_defining(&root, &from, "name").unwrap();
|
||||
assert_eq!(found.path, root.join("core/pom.xml"));
|
||||
assert_eq!(found.range.start.line, 2);
|
||||
// A property only the parent defines resolves there; unknown ones resolve nowhere.
|
||||
let parent = pom_defining(&root, &from, "parentName").unwrap();
|
||||
assert_eq!(parent.path, root.join("pom.xml"));
|
||||
assert_eq!(parent.range.start.line, 2);
|
||||
assert!(pom_defining(&root, &from, "missing").is_none());
|
||||
// A file outside the project root has no pom walk.
|
||||
let outside = tmp.path().join("elsewhere/application.yml");
|
||||
std::fs::create_dir_all(tmp.path().join("elsewhere")).unwrap();
|
||||
assert!(pom_defining(&root, &outside, "name").is_none());
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,7 @@ pub mod history;
|
||||
pub mod java;
|
||||
pub mod jvm_icons;
|
||||
pub mod lsp;
|
||||
pub mod maven_placeholder;
|
||||
pub mod nav;
|
||||
pub mod notebook;
|
||||
pub mod project;
|
||||
|
||||
@@ -15,6 +15,9 @@ impl ReplaceHost for DocumentsHost<'_> {
|
||||
Some(doc) => (doc, false),
|
||||
None => (docs.open(path)?.id, true),
|
||||
};
|
||||
// A buffer without unsaved changes (open only for the search preview, or a clean
|
||||
// tab) is saved like a closed file; one the user is editing is left unsaved.
|
||||
let save = transient || !docs.is_dirty(doc)?;
|
||||
let result = (|| {
|
||||
// Recompute if the user typed between reading the text and applying.
|
||||
for _ in 0..3 {
|
||||
@@ -27,7 +30,7 @@ impl ReplaceHost for DocumentsHost<'_> {
|
||||
continue;
|
||||
}
|
||||
docs.apply_edits(doc, &edits)?;
|
||||
if transient {
|
||||
if save {
|
||||
docs.save(doc)?;
|
||||
}
|
||||
return Ok(edits.len() as u32);
|
||||
@@ -46,8 +49,8 @@ impl ReplaceHost for DocumentsHost<'_> {
|
||||
///
|
||||
/// Edits go through the document layer as one patch per file, so open editors
|
||||
/// update live and undo the whole file's replacements in one step. Unsaved
|
||||
/// editor buffers are replaced in place and left unsaved; files that were not
|
||||
/// open are opened transiently, saved and closed.
|
||||
/// editor buffers are replaced in place and left unsaved; other open documents
|
||||
/// are saved, and files that were not open are opened transiently, saved and closed.
|
||||
///
|
||||
/// With `all_in_scope` (Replace All after the search hit its match limit) the
|
||||
/// scope is searched again without the limit and every match in it is replaced,
|
||||
|
||||
@@ -324,7 +324,7 @@ impl Host {
|
||||
let syntax = Arc::new(SyntaxCache::new(self.syntax()));
|
||||
documents.add_observer(Arc::new(SyntaxObserver(syntax.clone())));
|
||||
documents.add_observer(Arc::new(LspObserver(lsp.clone())));
|
||||
documents.add_observer(Arc::new(HistoryObserver(history.clone())));
|
||||
documents.add_observer(Arc::new(HistoryObserver::new(history.clone())));
|
||||
documents.add_observer(Arc::new(DeployObserver {
|
||||
remote: self.remote.clone(),
|
||||
settings: settings.clone(),
|
||||
@@ -785,7 +785,7 @@ impl Host {
|
||||
lsp.set_servers_hook(Box::new(|_, _| Vec::new()));
|
||||
let syntax = Arc::new(SyntaxCache::new(self.syntax()));
|
||||
documents.add_observer(Arc::new(SyntaxObserver(syntax.clone())));
|
||||
documents.add_observer(Arc::new(HistoryObserver(history.clone())));
|
||||
documents.add_observer(Arc::new(HistoryObserver::new(history.clone())));
|
||||
let watcher = match watch_dir {
|
||||
Some(dir) => light_watcher(dir, &sink, &documents, &history)?,
|
||||
// A quiet private folder stands in until the first save brings a
|
||||
@@ -1890,14 +1890,42 @@ impl DocumentObserver for SyntaxObserver {
|
||||
}
|
||||
}
|
||||
|
||||
struct HistoryObserver(Arc<LocalHistory>);
|
||||
struct HistoryObserver {
|
||||
history: Arc<LocalHistory>,
|
||||
/// Documents edited since they were opened: only the first edit looks for a missing original.
|
||||
edited: Mutex<HashSet<ide_core::DocId>>,
|
||||
}
|
||||
|
||||
impl HistoryObserver {
|
||||
fn new(history: Arc<LocalHistory>) -> Self {
|
||||
Self { history, edited: Mutex::default() }
|
||||
}
|
||||
}
|
||||
|
||||
impl DocumentObserver for HistoryObserver {
|
||||
fn saved(&self, _doc: ide_core::DocId, path: &Path, text: &str) {
|
||||
if let Err(e) = self.0.record(path, text, "Saved") {
|
||||
fn changed(
|
||||
&self,
|
||||
doc: ide_core::DocId,
|
||||
path: &Path,
|
||||
_version: u32,
|
||||
_changes: &[AppliedChange],
|
||||
_full_text: &dyn Fn() -> String,
|
||||
) {
|
||||
// The file on disk still has its content from before the edit.
|
||||
if self.edited.lock().insert(doc)
|
||||
&& let Err(e) = self.history.record_original(path)
|
||||
{
|
||||
tracing::warn!("local history: {e}");
|
||||
}
|
||||
}
|
||||
fn saved(&self, _doc: ide_core::DocId, path: &Path, text: &str) {
|
||||
if let Err(e) = self.history.record(path, text, "Saved") {
|
||||
tracing::warn!("local history: {e}");
|
||||
}
|
||||
}
|
||||
fn closed(&self, doc: ide_core::DocId, _path: &Path) {
|
||||
self.edited.lock().remove(&doc);
|
||||
}
|
||||
}
|
||||
|
||||
/// Uploads saved files: remote files' local copies, and automatic upload to the default server.
|
||||
|
||||
@@ -146,3 +146,52 @@ async fn replace_all_covers_matches_past_the_limit() {
|
||||
host.close_project("main");
|
||||
}
|
||||
}
|
||||
|
||||
/// #4202: a file the search preview holds open (no unsaved changes) is saved like a closed
|
||||
/// one; a buffer with unsaved edits is replaced in place and left for the editor to save.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn replace_all_saves_open_buffers_without_unsaved_changes() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
for name in ["previewed.txt", "edited.txt", "closed.txt"] {
|
||||
std::fs::write(root.join(name), "TOKEN\n").unwrap();
|
||||
}
|
||||
let host = Host::new(HostConfig {
|
||||
config_dir: base.join("config"),
|
||||
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,
|
||||
});
|
||||
host.trust.decide(&root, true, false).unwrap();
|
||||
host.open_project("main", &root).unwrap();
|
||||
let project = host.project("main").unwrap();
|
||||
project.documents.open(&root.join("previewed.txt")).unwrap();
|
||||
let edited = project.documents.open(&root.join("edited.txt")).unwrap().id;
|
||||
project.documents.replace_all(edited, "TOKEN\nmore\n").unwrap();
|
||||
ops::search::replace_in_files(
|
||||
&host,
|
||||
"main",
|
||||
RequestId::next(),
|
||||
query("TOKEN", false),
|
||||
"DONE".into(),
|
||||
false,
|
||||
vec![],
|
||||
true,
|
||||
ops::Channel::new(|_| {}),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let disk = |name: &str| std::fs::read_to_string(root.join(name)).unwrap();
|
||||
assert_eq!(disk("previewed.txt"), "DONE\n");
|
||||
assert_eq!(disk("closed.txt"), "DONE\n");
|
||||
assert_eq!(disk("edited.txt"), "TOKEN\n", "unsaved edits stay unsaved");
|
||||
assert_eq!(project.documents.text_snapshot(edited).unwrap().text, "DONE\nmore\n");
|
||||
host.close_project("main");
|
||||
}
|
||||
@@ -65,6 +65,28 @@ pub(crate) fn lenient_diagnostics(server: &str, items: Value) -> Vec<lsp::Diagno
|
||||
parsed
|
||||
}
|
||||
|
||||
/// rust-analyzer publishes its own analysis next to `cargo check`'s (flycheck): one type
|
||||
/// mismatch then arrives as `rust-analyzer(E0308)` and `rustc(E0308)`. Its own entry is
|
||||
/// dropped when the compiler reports the same code and severity over an overlapping range.
|
||||
fn drop_compiler_duplicates(diagnostics: &mut Vec<lsp::Diagnostic>) {
|
||||
let overlaps = |a: &lsp::Range, b: &lsp::Range| a.start <= b.end && b.start <= a.end;
|
||||
let compiler: Vec<(lsp::Range, Option<lsp::NumberOrString>, Option<lsp::DiagnosticSeverity>)> = diagnostics
|
||||
.iter()
|
||||
.filter(|d| d.source.as_deref() == Some("rustc") && d.code.is_some())
|
||||
.map(|d| (d.range, d.code.clone(), d.severity))
|
||||
.collect();
|
||||
if compiler.is_empty() {
|
||||
return;
|
||||
}
|
||||
diagnostics.retain(|d| {
|
||||
d.source.as_deref() != Some("rust-analyzer")
|
||||
|| d.code.is_none()
|
||||
|| !compiler
|
||||
.iter()
|
||||
.any(|(range, code, severity)| code == &d.code && severity == &d.severity && overlaps(range, &d.range))
|
||||
});
|
||||
}
|
||||
|
||||
impl ClientHandler {
|
||||
pub fn new(mgr: Weak<LspManager>, server: Arc<Server>, generation: u64) -> Self {
|
||||
Self { mgr, server, generation }
|
||||
@@ -293,11 +315,20 @@ impl ClientHandler {
|
||||
}
|
||||
};
|
||||
params.diagnostics = lenient_diagnostics(&self.server.name, raw.unwrap_or(Value::Null));
|
||||
drop_compiler_duplicates(&mut params.diagnostics);
|
||||
let Some(path) = uri_to_path(params.uri.as_str())
|
||||
.or_else(|| crate::notebook::is_cell_uri(params.uri.as_str()).then(|| PathBuf::from(params.uri.as_str())))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
if self.server.name == crate::compose::SERVER {
|
||||
// Maven resource-filtering placeholders (`@profileActive@`) parse as invalid
|
||||
// YAML but are replaced before the file is ever read: their parser error is noise.
|
||||
let text = mgr.docs.lock().values().find(|d| d.path == path).map(|d| d.text.as_str().to_owned());
|
||||
if let Some(text) = text {
|
||||
params.diagnostics.retain(|d| !crate::maven_placeholder::false_positive(&text, d));
|
||||
}
|
||||
}
|
||||
if self.server.name == "jdtls"
|
||||
&& let Some(failure) = crate::jdtls::build_plan_failure(&path, &self.server.root, ¶ms.diagnostics)
|
||||
{
|
||||
@@ -701,6 +732,28 @@ mod tests {
|
||||
use std::path::PathBuf;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
#[test]
|
||||
fn rust_analyzer_s_own_entry_yields_to_the_compiler_s_for_the_same_error() {
|
||||
let diagnostic = |source: &str, code: &str, line: u32, severity| lsp::Diagnostic {
|
||||
range: lsp::Range::new(lsp::Position::new(line, 21), lsp::Position::new(line, 27)),
|
||||
severity: Some(severity),
|
||||
code: Some(lsp::NumberOrString::String(code.into())),
|
||||
source: Some(source.into()),
|
||||
message: format!("{source} {code}"),
|
||||
..Default::default()
|
||||
};
|
||||
let error = lsp::DiagnosticSeverity::ERROR;
|
||||
let mut items = vec![
|
||||
diagnostic("rust-analyzer", "E0308", 1, error),
|
||||
diagnostic("rustc", "E0308", 1, error),
|
||||
diagnostic("rust-analyzer", "E0308", 5, error),
|
||||
diagnostic("rust-analyzer", "unused_variables", 1, lsp::DiagnosticSeverity::WARNING),
|
||||
];
|
||||
drop_compiler_duplicates(&mut items);
|
||||
let left: Vec<_> = items.iter().map(|d| (d.message.as_str(), d.range.start.line)).collect();
|
||||
assert_eq!(left, [("rustc E0308", 1), ("rust-analyzer E0308", 5), ("rust-analyzer unused_variables", 1)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tsserver_aborts_are_out_of_memory() {
|
||||
assert!(tsserver_ran_out_of_memory("TSServer exited. Code: 134. Signal: null"));
|
||||
|
||||
@@ -25,6 +25,7 @@ mod kotlin_lsp;
|
||||
mod launch;
|
||||
mod library_source;
|
||||
mod loading;
|
||||
mod maven_placeholder;
|
||||
mod message_requests;
|
||||
mod notebook;
|
||||
mod phoxite;
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
//! `@property@` placeholders in YAML resources: Maven resource filtering replaces
|
||||
//! them before the file is ever read as YAML, so Spring projects use them unquoted
|
||||
//! (`spring.profiles.active: @profileActive@`). The YAML spec reserves `@` and the
|
||||
//! `yaml` parser behind `yaml-language-server` therefore reports
|
||||
//! "Plain value cannot start with reserved character @" for every one of them.
|
||||
//! The diagnostic is dropped when the reported scalar is exactly a Maven
|
||||
//! placeholder; anything else the parser flags keeps showing.
|
||||
|
||||
use lsp_types as lsp;
|
||||
|
||||
const RESERVED_AT: &str = "Plain value cannot start with reserved character @";
|
||||
|
||||
/// Whether `diagnostic` is the reserved-`@` parser error on a scalar whose text in
|
||||
/// `text` is exactly a Maven placeholder (`@token@`).
|
||||
pub(crate) fn false_positive(text: &str, diagnostic: &lsp::Diagnostic) -> bool {
|
||||
diagnostic.message == RESERVED_AT && placeholder_at(text, &diagnostic.range).is_some()
|
||||
}
|
||||
|
||||
/// The name between the `@`s of the diagnostic range, when it covers one whole placeholder.
|
||||
fn placeholder_at(text: &str, range: &lsp::Range) -> Option<String> {
|
||||
if range.start.line != range.end.line {
|
||||
return None;
|
||||
}
|
||||
let line = text.split_inclusive('\n').nth(range.start.line as usize)?;
|
||||
let line = line.trim_end_matches(['\n', '\r']);
|
||||
let start = utf16_to_byte(line, range.start.character)?.min(line.len());
|
||||
// The parser's scalar range ends one past the line (its newline), so the end clamps.
|
||||
let end = utf16_to_byte(line, range.end.character).unwrap_or(line.len());
|
||||
if end < start {
|
||||
return None;
|
||||
}
|
||||
let inner = line[start..end].strip_prefix('@')?.strip_suffix('@')?;
|
||||
(!inner.is_empty() && inner.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_')))
|
||||
.then(|| inner.to_owned())
|
||||
}
|
||||
|
||||
/// UTF-16 column → byte offset within one line, `None` inside a surrogate pair or past the line.
|
||||
fn utf16_to_byte(line: &str, col: u32) -> Option<usize> {
|
||||
let col = col as usize;
|
||||
let mut units = 0usize;
|
||||
for (byte, c) in line.char_indices() {
|
||||
if units == col {
|
||||
return Some(byte);
|
||||
}
|
||||
units += c.len_utf16();
|
||||
if units > col {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
(units == col).then_some(line.len())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use lsp_types::{Position, Range};
|
||||
|
||||
fn at(line: u32, from: u32, to: u32) -> Range {
|
||||
Range { start: Position::new(line, from), end: Position::new(line, to) }
|
||||
}
|
||||
|
||||
fn across(from: (u32, u32), to: (u32, u32)) -> Range {
|
||||
Range { start: Position::new(from.0, from.1), end: Position::new(to.0, to.1) }
|
||||
}
|
||||
|
||||
fn diagnostic(range: Range) -> lsp::Diagnostic {
|
||||
lsp::Diagnostic { range, message: RESERVED_AT.to_owned(), ..Default::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_maven_placeholder_placeholder_is_a_false_positive() {
|
||||
let text = "spring:\n profiles:\n active: @profileActive@\n";
|
||||
assert!(false_positive(text, &diagnostic(at(2, 12, 27))));
|
||||
// The parser ends the scalar's range one past the line (its newline): still caught.
|
||||
assert!(false_positive(text, &diagnostic(at(2, 12, 28))));
|
||||
// Columns also decode on a line with non-ASCII text before the scalar.
|
||||
let text = "name: 项目\nvalue: @profileActive@\n";
|
||||
assert!(false_positive(text, &diagnostic(at(1, 7, 22))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_reserved_character_errors_and_shapes_still_show() {
|
||||
let text = "active: @profileActive@\n";
|
||||
// Not the parser's message (a backtick, a different wording).
|
||||
assert!(!false_positive(
|
||||
text,
|
||||
&lsp::Diagnostic {
|
||||
message: "Plain value cannot start with reserved character `".to_owned(),
|
||||
..diagnostic(at(0, 8, 11))
|
||||
}
|
||||
));
|
||||
// The error's range is stale and no longer covers a placeholder.
|
||||
assert!(!false_positive(text, &diagnostic(at(0, 0, 10))));
|
||||
// A single `@`, an unpaired one or a name with spaces is no placeholder.
|
||||
assert!(!false_positive("active: @\n", &diagnostic(at(0, 8, 9))));
|
||||
assert!(!false_positive("active: @profile\n", &diagnostic(at(0, 8, 16))));
|
||||
assert!(!false_positive("active: @pro file@\n", &diagnostic(at(0, 8, 18))));
|
||||
// A range crossing lines is kept.
|
||||
assert!(!false_positive("a: @x@\nb: y\n", &diagnostic(across((0, 3), (1, 0)))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn utf16_columns_decode_multi_byte_and_surrogate_pairs() {
|
||||
// "é" is one UTF-16 unit; "😀" is two, and a column inside it is out of range.
|
||||
let line = "é😀@token@";
|
||||
assert_eq!(utf16_to_byte(line, 0), Some(0));
|
||||
assert_eq!(utf16_to_byte(line, 1), Some(2));
|
||||
assert_eq!(utf16_to_byte(line, 2), None);
|
||||
assert_eq!(utf16_to_byte(line, 3), Some(6));
|
||||
assert_eq!(utf16_to_byte(line, 4), Some(7));
|
||||
assert_eq!(utf16_to_byte(line, 10), Some(line.len()));
|
||||
}
|
||||
}
|
||||
+257
-9
@@ -239,7 +239,7 @@ fn event_handler(state: Weak<DirState>, polled: bool) -> impl FnMut(notify::Resu
|
||||
Ok(event) if !is_change_event(&event) => {}
|
||||
Ok(event) if polled && is_dir_touch(&event) => {}
|
||||
Ok(event) => {
|
||||
state.queue.lock().push((event, Instant::now()));
|
||||
state.queue.lock().push(event, Instant::now());
|
||||
state.wake.notify_one();
|
||||
}
|
||||
Err(e) => tracing::warn!("file watcher: {e}"),
|
||||
@@ -280,13 +280,53 @@ fn watcher_error(what: &str, error: notify::Error) -> IdeError {
|
||||
}
|
||||
}
|
||||
|
||||
/// Only adjacent identical file modifications are redundant before classification.
|
||||
/// Keep the arrival window separately so compaction cannot extend MAX_DELAY.
|
||||
#[derive(Default)]
|
||||
struct PendingEvents {
|
||||
events: Vec<Event>,
|
||||
first: Option<Instant>,
|
||||
last: Option<Instant>,
|
||||
received: usize,
|
||||
}
|
||||
|
||||
impl PendingEvents {
|
||||
fn is_empty(&self) -> bool {
|
||||
self.events.is_empty()
|
||||
}
|
||||
|
||||
fn push(&mut self, event: Event, now: Instant) {
|
||||
self.first.get_or_insert(now);
|
||||
self.last = Some(now);
|
||||
self.received += 1;
|
||||
let redundant = event.paths.len() == 1
|
||||
&& event.flag().is_none()
|
||||
&& matches!(event.kind, EventKind::Modify(ModifyKind::Any | ModifyKind::Data(_) | ModifyKind::Metadata(_)))
|
||||
&& self.events.last().is_some_and(|previous| {
|
||||
// Reject different spellings before Path's component-wise equality.
|
||||
// Keeping a normalized alias is safe; only exact duplicates compact.
|
||||
previous.paths.len() == 1
|
||||
&& previous.paths[0].as_os_str() == event.paths[0].as_os_str()
|
||||
&& previous == &event
|
||||
&& previous.attrs.process_id() == event.attrs.process_id()
|
||||
});
|
||||
if !redundant {
|
||||
self.events.push(event);
|
||||
}
|
||||
}
|
||||
|
||||
fn deadline(&self) -> Option<Instant> {
|
||||
Some((self.last? + DEBOUNCE).min(self.first? + MAX_DELAY))
|
||||
}
|
||||
}
|
||||
|
||||
/// Shared with the notify callback (weakly) and the debounce thread.
|
||||
struct DirState {
|
||||
filter: EventFilter,
|
||||
mode: WatchMode,
|
||||
watcher: Mutex<Option<Box<dyn notify::Watcher + Send>>>,
|
||||
watched: Mutex<HashSet<PathBuf>>,
|
||||
queue: Mutex<Vec<(notify::Event, Instant)>>,
|
||||
queue: Mutex<PendingEvents>,
|
||||
wake: Condvar,
|
||||
stop: AtomicBool,
|
||||
/// Set when a `watch()` call reports the OS watch limit (inotify
|
||||
@@ -317,34 +357,48 @@ impl DirState {
|
||||
if self.stopped() {
|
||||
return;
|
||||
}
|
||||
let first = q[0].1;
|
||||
|
||||
loop {
|
||||
let last = q.last().map_or(first, |e| e.1);
|
||||
let deadline = q.deadline().expect("nonempty event queue");
|
||||
let now = Instant::now();
|
||||
if self.stopped() {
|
||||
return;
|
||||
}
|
||||
if now >= last + DEBOUNCE || now >= first + MAX_DELAY {
|
||||
if now >= deadline {
|
||||
break;
|
||||
}
|
||||
let wait = (last + DEBOUNCE).min(first + MAX_DELAY) - now;
|
||||
let wait = deadline - now;
|
||||
self.wake.wait_for(&mut q, wait);
|
||||
}
|
||||
std::mem::take(&mut *q)
|
||||
};
|
||||
// A scan may publish a path before its create event is delivered:
|
||||
// keep create + remove pairs so the consumer still sees the removal.
|
||||
let events: Vec<Event> = events.into_iter().map(|(e, _)| e).collect();
|
||||
let (mut batch, rule_dirs) = self.filter.batch_detailed(&events);
|
||||
let processing = Instant::now();
|
||||
let queue_age_ms = processing.duration_since(events.first.expect("nonempty event queue")).as_millis();
|
||||
let received = events.received;
|
||||
let queued = events.events.len();
|
||||
let (mut batch, rule_dirs) = self.filter.batch_detailed(&events.events);
|
||||
if self.mode == WatchMode::PerDirectory {
|
||||
self.update_watches(&mut batch, &rule_dirs);
|
||||
// Again once polling: a refused directory was not read, and
|
||||
// the poller won't report what is already in it.
|
||||
polled = polled || self.poll_if_exhausted(|| self.update_watches(&mut batch, &rule_dirs));
|
||||
}
|
||||
let processing_ms = processing.elapsed().as_millis();
|
||||
let callback = Instant::now();
|
||||
if !batch.is_empty() && !self.stopped() {
|
||||
emit(&batch);
|
||||
}
|
||||
tracing::debug!(
|
||||
received,
|
||||
queued,
|
||||
coalesced = received - queued,
|
||||
queue_age_ms,
|
||||
processing_ms,
|
||||
callback_ms = callback.elapsed().as_millis(),
|
||||
"file watcher batch"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -785,6 +839,10 @@ impl EventFilter {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "watch_pipeline_tests.rs"]
|
||||
mod pipeline_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -794,6 +852,196 @@ mod tests {
|
||||
Event { kind, paths, attrs: Default::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pending_modifications_keep_the_original_debounce_window() {
|
||||
let start = Instant::now();
|
||||
// ReadDirectoryChangesW reports ordinary Windows writes as Modify(Any).
|
||||
let event = ev(EventKind::Modify(ModifyKind::Any), vec!["file.rs".into()]);
|
||||
let mut pending = PendingEvents::default();
|
||||
assert_eq!(pending.deadline(), None);
|
||||
for n in 0..10_000 {
|
||||
pending.push(event.clone(), start + Duration::from_micros(n * 95));
|
||||
}
|
||||
assert_eq!(pending.received, 10_000);
|
||||
assert_eq!(pending.events.len(), 1);
|
||||
assert_eq!(pending.first, Some(start));
|
||||
assert_eq!(pending.last, Some(start + Duration::from_micros(9_999 * 95)));
|
||||
assert_eq!(pending.deadline(), Some(start + MAX_DELAY));
|
||||
let drained = std::mem::take(&mut pending);
|
||||
assert_eq!(drained.events, vec![event.clone()]);
|
||||
assert!(pending.is_empty());
|
||||
assert_eq!(pending.deadline(), None);
|
||||
pending.push(event, start + MAX_DELAY);
|
||||
assert_eq!(pending.received, 1);
|
||||
assert_eq!(pending.deadline(), Some(start + MAX_DELAY + DEBOUNCE));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pending_events_preserve_boundaries_and_attributes() {
|
||||
let now = Instant::now();
|
||||
let modify = ev(EventKind::Modify(ModifyKind::Data(DataChange::Content)), vec!["a".into()]);
|
||||
let variants = [
|
||||
modify.clone().set_tracker(1),
|
||||
modify.clone().set_info("backend detail"),
|
||||
modify.clone().set_process_id(2),
|
||||
modify.clone().set_flag(notify::event::Flag::Rescan),
|
||||
modify.clone().add_path("b".into()),
|
||||
ev(EventKind::Create(CreateKind::File), vec!["a".into()]),
|
||||
ev(EventKind::Remove(RemoveKind::File), vec!["a".into()]),
|
||||
ev(EventKind::Modify(ModifyKind::Name(RenameMode::Both)), vec!["a".into(), "b".into()]),
|
||||
ev(EventKind::Modify(ModifyKind::Name(RenameMode::From)), vec!["a".into()]),
|
||||
ev(EventKind::Modify(ModifyKind::Name(RenameMode::To)), vec!["a".into()]),
|
||||
ev(EventKind::Any, vec!["a".into()]),
|
||||
];
|
||||
for middle in variants {
|
||||
let events = vec![modify.clone(), middle, modify.clone()];
|
||||
let mut pending = PendingEvents::default();
|
||||
for event in &events {
|
||||
pending.push(event.clone(), now);
|
||||
}
|
||||
assert_eq!(pending.events, events);
|
||||
}
|
||||
let mut interleaved = PendingEvents::default();
|
||||
for event in [
|
||||
modify.clone(),
|
||||
modify.clone().set_kind(EventKind::Create(CreateKind::File)).add_path("b".into()),
|
||||
modify.clone(),
|
||||
] {
|
||||
interleaved.push(event, now);
|
||||
}
|
||||
assert_eq!(interleaved.events.len(), 3);
|
||||
let mut interleaved = PendingEvents::default();
|
||||
for event in [modify.clone(), ev(modify.kind, vec!["b".into()]), modify.clone()] {
|
||||
interleaved.push(event, now);
|
||||
}
|
||||
assert_eq!(interleaved.events.len(), 3);
|
||||
for event in [
|
||||
modify.set_flag(notify::event::Flag::Rescan),
|
||||
ev(EventKind::Modify(ModifyKind::Name(RenameMode::From)), vec!["a".into()]),
|
||||
] {
|
||||
let mut pending = PendingEvents::default();
|
||||
pending.push(event.clone(), now);
|
||||
pending.push(event, now);
|
||||
assert_eq!(pending.events.len(), 2);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pending_keeps_different_spellings_of_the_same_path() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
std::fs::create_dir(root.join("src")).unwrap();
|
||||
std::fs::write(root.join("src/a.rs"), "x").unwrap();
|
||||
let paths = [root.join("src/a.rs"), root.join("src/./a.rs"), root.join("src//a.rs")];
|
||||
assert_eq!(paths[0], paths[1]);
|
||||
assert_ne!(paths[0].as_os_str(), paths[1].as_os_str());
|
||||
let events: Vec<_> =
|
||||
paths.into_iter().map(|path| Event::new(EventKind::Modify(ModifyKind::Any)).add_path(path)).collect();
|
||||
let mut pending = PendingEvents::default();
|
||||
for event in &events {
|
||||
pending.push(event.clone(), Instant::now());
|
||||
}
|
||||
assert_eq!(pending.events.len(), events.len());
|
||||
assert_same_batch(
|
||||
&EventFilter::new(root.clone(), &[]).batch(&events),
|
||||
&EventFilter::new(root, &[]).batch(&pending.events),
|
||||
);
|
||||
}
|
||||
|
||||
fn assert_same_batch(left: &FsBatch, right: &FsBatch) {
|
||||
assert_eq!(left.created, right.created);
|
||||
assert_eq!(left.modified, right.modified);
|
||||
assert_eq!(left.removed, right.removed);
|
||||
assert_eq!(left.vcs, right.vcs);
|
||||
assert_eq!(left.excluded_dirs, right.excluded_dirs);
|
||||
assert_eq!(left.ignored, right.ignored);
|
||||
assert_eq!(left.ignore_rules, right.ignore_rules);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pending_compaction_matches_uncompressed_change_sequences() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
std::fs::create_dir(root.join(".git")).unwrap();
|
||||
std::fs::create_dir(root.join("excluded")).unwrap();
|
||||
std::fs::write(root.join(".gitignore"), "*.ignored\n").unwrap();
|
||||
let excludes = vec!["excluded".to_owned()];
|
||||
let kinds = [
|
||||
EventKind::Create(CreateKind::File),
|
||||
EventKind::Remove(RemoveKind::File),
|
||||
EventKind::Modify(ModifyKind::Any),
|
||||
EventKind::Modify(ModifyKind::Data(DataChange::Content)),
|
||||
EventKind::Modify(ModifyKind::Metadata(MetadataKind::WriteTime)),
|
||||
EventKind::Modify(ModifyKind::Name(RenameMode::From)),
|
||||
EventKind::Modify(ModifyKind::Name(RenameMode::To)),
|
||||
];
|
||||
// All four-event histories, with both present and absent final state.
|
||||
for rel in ["source.rs", "file.ignored", "excluded/source.rs", ".git/HEAD"] {
|
||||
let path = root.join(rel);
|
||||
for exists in [false, true] {
|
||||
if exists {
|
||||
std::fs::write(&path, "x").unwrap();
|
||||
}
|
||||
for code in 0..kinds.len().pow(4) {
|
||||
let mut code = code;
|
||||
let mut events = Vec::new();
|
||||
let mut pending = PendingEvents::default();
|
||||
for _ in 0..4 {
|
||||
let event = ev(kinds[code % kinds.len()], vec![path.clone()]);
|
||||
code /= kinds.len();
|
||||
// Each event is repeated to exercise compaction after transitions.
|
||||
for _ in 0..2 {
|
||||
events.push(event.clone());
|
||||
pending.push(event.clone(), Instant::now());
|
||||
}
|
||||
}
|
||||
let plain = EventFilter::new(root.clone(), &excludes).batch(&events);
|
||||
let compact = EventFilter::new(root.clone(), &excludes).batch(&pending.events);
|
||||
assert_same_batch(&plain, &compact);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pending_compaction_keeps_rule_reload_and_rename_endpoints() {
|
||||
let excludes = vec!["excluded".to_owned()];
|
||||
for rule in [".gitignore", ".ignore", ".git/info/exclude"] {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
std::fs::create_dir_all(root.join(".git/info")).unwrap();
|
||||
std::fs::create_dir(root.join("excluded")).unwrap();
|
||||
std::fs::write(root.join(rule), "").unwrap();
|
||||
std::fs::write(root.join("file.ignored"), "x").unwrap();
|
||||
let plain = EventFilter::new(root.clone(), &excludes);
|
||||
let compact = EventFilter::new(root.clone(), &excludes);
|
||||
let touch = ev(EventKind::Modify(ModifyKind::Data(DataChange::Content)), vec![root.join("file.ignored")]);
|
||||
for filter in [&plain, &compact] {
|
||||
assert_eq!(filter.batch(std::slice::from_ref(&touch)).modified, vec![root.join("file.ignored")]);
|
||||
}
|
||||
std::fs::write(root.join(rule), "*.ignored\n").unwrap();
|
||||
let mut events = Vec::new();
|
||||
for path in ["file.ignored", rule] {
|
||||
let event = ev(EventKind::Modify(ModifyKind::Data(DataChange::Content)), vec![root.join(path)]);
|
||||
events.extend([event.clone(), event]);
|
||||
}
|
||||
events.push(ev(
|
||||
EventKind::Modify(ModifyKind::Name(RenameMode::Both)),
|
||||
vec![root.join("excluded/old.rs"), root.join("new.rs")],
|
||||
));
|
||||
std::fs::write(root.join("new.rs"), "x").unwrap();
|
||||
let mut pending = PendingEvents::default();
|
||||
for event in &events {
|
||||
pending.push(event.clone(), Instant::now());
|
||||
}
|
||||
let expected = plain.batch(&events);
|
||||
assert_eq!(expected.ignore_rules, vec![root.clone()]);
|
||||
assert_eq!(expected.ignored, vec![root.join("file.ignored")]);
|
||||
assert!(!expected.modified.contains(&root.join("file.ignored")));
|
||||
assert_same_batch(&expected, &compact.batch(&pending.events));
|
||||
}
|
||||
}
|
||||
|
||||
const TRANSIENT_PATHS: &[&str] = &["fresh.txt", "src/fresh.rs", "src/tasks/fresh.py"];
|
||||
|
||||
/// Delivers a whole debounce window without depending on OS scheduling.
|
||||
@@ -1530,7 +1778,7 @@ mod tests {
|
||||
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
|
||||
std::fs::write(&file, "x").unwrap();
|
||||
let created = Event::new(EventKind::Create(notify::event::CreateKind::Folder)).add_path(root.join("new"));
|
||||
inner.state.queue.lock().push((created, Instant::now()));
|
||||
inner.state.queue.lock().push(created, Instant::now());
|
||||
inner.state.wake.notify_all();
|
||||
// Written before polling took over, so the poller never reports it.
|
||||
assert!(wait_for(&batches, |b| all_paths(b).contains(&file)), "{:?}", batches.lock());
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
//! Queue-to-filter correctness comparisons, without timing or OS delivery.
|
||||
|
||||
use super::*;
|
||||
use notify::event::{CreateKind, Flag, RemoveKind};
|
||||
|
||||
fn compare_batches(left: &FsBatch, right: &FsBatch) {
|
||||
assert_eq!(
|
||||
(
|
||||
&left.created,
|
||||
&left.modified,
|
||||
&left.removed,
|
||||
&left.vcs,
|
||||
&left.excluded_dirs,
|
||||
&left.ignored,
|
||||
&left.ignore_rules
|
||||
),
|
||||
(
|
||||
&right.created,
|
||||
&right.modified,
|
||||
&right.removed,
|
||||
&right.vcs,
|
||||
&right.excluded_dirs,
|
||||
&right.ignored,
|
||||
&right.ignore_rules
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// Preserve the pre-change queue and drain operation for the comparison.
|
||||
fn original(input: &[Event], filter: &EventFilter) -> (usize, FsBatch) {
|
||||
let mut queue = Vec::new();
|
||||
for event in input {
|
||||
queue.push((event.clone(), Instant::now()));
|
||||
}
|
||||
let retained = queue.len();
|
||||
let events: Vec<Event> = std::mem::take(&mut queue).into_iter().map(|(event, _)| event).collect();
|
||||
(retained, filter.batch(&events))
|
||||
}
|
||||
|
||||
fn compact(input: &[Event], filter: &EventFilter) -> (usize, FsBatch) {
|
||||
let mut queue = PendingEvents::default();
|
||||
for event in input {
|
||||
queue.push(event.clone(), Instant::now());
|
||||
}
|
||||
let events = std::mem::take(&mut queue);
|
||||
(events.events.len(), filter.batch(&events.events))
|
||||
}
|
||||
|
||||
fn event(kind: EventKind, root: &Path, rel: &str) -> Event {
|
||||
Event::new(kind).add_path(root.join(rel))
|
||||
}
|
||||
|
||||
fn modify(root: &Path, n: usize) -> Event {
|
||||
event(EventKind::Modify(ModifyKind::Any), root, &format!("src/{n}.rs"))
|
||||
}
|
||||
|
||||
fn fixture(files: usize) -> tempfile::TempDir {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
for dir in ["src", "excluded", ".git/info", "renamed"] {
|
||||
std::fs::create_dir_all(tmp.path().join(dir)).unwrap();
|
||||
}
|
||||
std::fs::write(tmp.path().join(".gitignore"), "*.ignored\n").unwrap();
|
||||
std::fs::write(tmp.path().join("file.ignored"), "x").unwrap();
|
||||
for n in 0..files {
|
||||
std::fs::write(tmp.path().join(format!("src/{n}.rs")), "x").unwrap();
|
||||
if n % 8 == 4 {
|
||||
std::fs::write(tmp.path().join(format!("excluded/{n}.js")), "x").unwrap();
|
||||
}
|
||||
}
|
||||
tmp
|
||||
}
|
||||
|
||||
fn cases(root: &Path, count: usize) -> Vec<(&'static str, Vec<Event>)> {
|
||||
let repeated = vec![modify(root, 0); count];
|
||||
let distinct = (0..count).map(|n| modify(root, n)).collect();
|
||||
let interleaved = (0..count).map(|n| modify(root, n % 2)).collect();
|
||||
let pairs = (0..count).map(|n| modify(root, n / 2)).collect();
|
||||
let runs = (0..count).map(|n| modify(root, n / 10)).collect();
|
||||
let mixed = (0..count)
|
||||
.map(|n| match n % 8 {
|
||||
0 | 1 => modify(root, n / 8),
|
||||
2 => event(EventKind::Create(CreateKind::File), root, &format!("src/{}.rs", n / 8)),
|
||||
3 => event(EventKind::Remove(RemoveKind::File), root, &format!("gone/{n}.rs")),
|
||||
4 => event(EventKind::Create(CreateKind::File), root, &format!("excluded/{n}.js")),
|
||||
5 => event(EventKind::Remove(RemoveKind::File), root, &format!("excluded/{n}.js")),
|
||||
6 => event(EventKind::Modify(ModifyKind::Any), root, "file.ignored"),
|
||||
_ => event(EventKind::Modify(ModifyKind::Any), root, ".git/HEAD"),
|
||||
})
|
||||
.collect();
|
||||
vec![
|
||||
("repeated", repeated),
|
||||
("distinct", distinct),
|
||||
("interleaved", interleaved),
|
||||
("pairs", pairs),
|
||||
("runs10", runs),
|
||||
("mixed", mixed),
|
||||
]
|
||||
}
|
||||
|
||||
fn pair(input: &[Event], root: &Path, warm: bool, reverse: bool) -> (usize, usize) {
|
||||
let excludes = vec!["excluded".to_owned()];
|
||||
let a = EventFilter::new(root.to_path_buf(), &excludes);
|
||||
let b = EventFilter::new(root.to_path_buf(), &excludes);
|
||||
if warm {
|
||||
compare_batches(&a.batch(input), &b.batch(input));
|
||||
}
|
||||
let (a_retained, a_batch, b_retained, b_batch) = if reverse {
|
||||
let (b_retained, b_batch) = compact(input, &b);
|
||||
let (a_retained, a_batch) = original(input, &a);
|
||||
(a_retained, a_batch, b_retained, b_batch)
|
||||
} else {
|
||||
let (a_retained, a_batch) = original(input, &a);
|
||||
let (b_retained, b_batch) = compact(input, &b);
|
||||
(a_retained, a_batch, b_retained, b_batch)
|
||||
};
|
||||
compare_batches(&a_batch, &b_batch);
|
||||
(a_retained, b_retained)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pipeline_comparison_preserves_batches_and_rule_changes() {
|
||||
let tmp = fixture(32);
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
for (name, input) in cases(&root, 32) {
|
||||
for warm in [false, true] {
|
||||
for reverse in [false, true] {
|
||||
let (old, new) = pair(&input, &root, warm, reverse);
|
||||
assert_eq!(old, 32);
|
||||
let expected = match name {
|
||||
"repeated" => 1,
|
||||
"distinct" | "interleaved" => 32,
|
||||
"pairs" => 16,
|
||||
"runs10" => 4,
|
||||
"mixed" => 28,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
assert_eq!(new, expected, "{name}");
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut special = vec![
|
||||
modify(&root, 0).set_flag(Flag::Rescan),
|
||||
modify(&root, 0).set_flag(Flag::Rescan),
|
||||
modify(&root, 0).set_tracker(1),
|
||||
modify(&root, 0).set_tracker(2),
|
||||
modify(&root, 0).set_process_id(1),
|
||||
modify(&root, 0).set_process_id(2),
|
||||
modify(&root, 0).add_path(root.join("src/1.rs")),
|
||||
];
|
||||
for mode in [RenameMode::Both, RenameMode::From, RenameMode::To] {
|
||||
let rename = event(EventKind::Modify(ModifyKind::Name(mode)), &root, "old.rs");
|
||||
special.push(if mode == RenameMode::Both { rename.add_path(root.join("src/0.rs")) } else { rename });
|
||||
}
|
||||
let (old, new) = pair(&special, &root, true, false);
|
||||
assert_eq!(old, special.len());
|
||||
assert_eq!(new, special.len());
|
||||
for rule in [".gitignore", ".ignore", ".git/info/exclude"] {
|
||||
let tmp = fixture(1);
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
std::fs::write(root.join(".gitignore"), "").unwrap();
|
||||
std::fs::write(root.join(rule), "").unwrap();
|
||||
let a = EventFilter::new(root.clone(), &[]);
|
||||
let b = EventFilter::new(root.clone(), &[]);
|
||||
let touch = event(EventKind::Modify(ModifyKind::Any), &root, "file.ignored");
|
||||
for filter in [&a, &b] {
|
||||
assert_eq!(filter.batch(std::slice::from_ref(&touch)).modified, vec![root.join("file.ignored")]);
|
||||
}
|
||||
std::fs::write(root.join(rule), "*.ignored\n").unwrap();
|
||||
let change = event(EventKind::Modify(ModifyKind::Any), &root, rule);
|
||||
let input = [touch.clone(), touch, change.clone(), change];
|
||||
let (_, old) = original(&input, &a);
|
||||
let (_, new) = compact(&input, &b);
|
||||
compare_batches(&old, &new);
|
||||
assert_eq!(new.ignored, vec![root.join("file.ignored")]);
|
||||
assert_eq!(new.ignore_rules, vec![root]);
|
||||
}
|
||||
}
|
||||
@@ -92,6 +92,8 @@ pub const DEFAULT_MAX_AGE_DAYS: u32 = 5;
|
||||
pub const DEFAULT_MAX_BYTES: u64 = 512 * 1024 * 1024;
|
||||
/// Label of the snapshot taken before a file is deleted.
|
||||
pub const DELETED: &str = "Deleted";
|
||||
/// The label of a file's content from before its first edit ([`LocalHistory::record_original`]).
|
||||
pub const ORIGINAL: &str = "Original";
|
||||
/// Files larger than this are not snapshotted automatically (watcher, deletes, VCS).
|
||||
const AUTO_SNAPSHOT_LIMIT: u64 = 2 * 1024 * 1024;
|
||||
const DAY_MS: f64 = 86_400_000.0;
|
||||
@@ -121,7 +123,14 @@ fn read_snapshot_text(path: &Path) -> Option<String> {
|
||||
if bytes.iter().take(8192).any(|b| *b == 0) {
|
||||
return None;
|
||||
}
|
||||
String::from_utf8(bytes).ok()
|
||||
String::from_utf8(bytes).ok().map(|text| document_text(&text).into_owned())
|
||||
}
|
||||
|
||||
/// `text` as a document holds it: without the UTF-8 BOM and with `\n` line endings. Saves
|
||||
/// record the document's text, so a file read from disk must match it to dedupe, and
|
||||
/// Revert writes it back through the document, which adds the file's BOM and line endings.
|
||||
fn document_text(text: &str) -> std::borrow::Cow<'_, str> {
|
||||
ide_text::normalize_line_endings(text.strip_prefix('\u{feff}').unwrap_or(text))
|
||||
}
|
||||
|
||||
impl LocalHistory {
|
||||
@@ -188,6 +197,18 @@ impl LocalHistory {
|
||||
if !force && state.last.get(path) == Some(&id) {
|
||||
return Ok(());
|
||||
}
|
||||
self.store_locked(&mut state, path, id, content, label, now_ms())
|
||||
}
|
||||
|
||||
fn store_locked(
|
||||
&self,
|
||||
state: &mut HistoryState,
|
||||
path: &Path,
|
||||
id: String,
|
||||
content: &str,
|
||||
label: &str,
|
||||
timestamp_ms: f64,
|
||||
) -> IdeResult<()> {
|
||||
let blob = self.blob_path(&id);
|
||||
if !blob.exists() {
|
||||
fs::create_dir_all(blob.parent().expect("blob has a parent"))?;
|
||||
@@ -196,12 +217,12 @@ impl LocalHistory {
|
||||
let entry = HistoryEntry {
|
||||
id,
|
||||
path: path.into(),
|
||||
timestamp_ms: now_ms(),
|
||||
timestamp_ms,
|
||||
label: label.to_owned(),
|
||||
size: content.len() as u64,
|
||||
kind: HistoryKind::Snapshot,
|
||||
};
|
||||
self.append(&mut state, entry)
|
||||
self.append(state, entry)
|
||||
}
|
||||
|
||||
/// Records a snapshot unless it equals the latest one recorded for `path`.
|
||||
@@ -223,6 +244,31 @@ impl LocalHistory {
|
||||
}
|
||||
}
|
||||
|
||||
/// Before the first edit of a file with no history: its content on disk, so a label put
|
||||
/// before the edit can be reverted to. Dated by the file's modification time, since it
|
||||
/// has had that content from then on, but not before the oldest entry kept, so it neither
|
||||
/// adds a working day of its own nor falls to retention first. Returns whether one was recorded.
|
||||
pub fn record_original(&self, path: &Path) -> IdeResult<bool> {
|
||||
let Some(text) = read_snapshot_text(path) else { return Ok(false) };
|
||||
let modified = fs::metadata(path)
|
||||
.and_then(|m| m.modified())
|
||||
.ok()
|
||||
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
|
||||
.map(|d| d.as_secs_f64() * 1000.0);
|
||||
let mut state = self.state.lock();
|
||||
if state.entries.iter().any(|e| e.kind == HistoryKind::Snapshot && e.path == path) {
|
||||
return Ok(false);
|
||||
}
|
||||
let now = now_ms();
|
||||
let oldest = state.entries.iter().map(|e| e.timestamp_ms).reduce(f64::min);
|
||||
let timestamp = match (modified, oldest) {
|
||||
(Some(modified), Some(oldest)) => modified.max(oldest - 1.0).min(now),
|
||||
_ => now,
|
||||
};
|
||||
let id = blake3::hash(text.as_bytes()).to_hex().to_string();
|
||||
self.store_locked(&mut state, path, id, &text, ORIGINAL, timestamp).map(|()| true)
|
||||
}
|
||||
|
||||
/// Snapshots `path`, or every file below it when it is a folder (at most `limit`
|
||||
/// files), before it is deleted. Returns how many files were recorded.
|
||||
pub fn record_deletion(&self, path: &Path, limit: usize) -> usize {
|
||||
@@ -338,7 +384,10 @@ impl LocalHistory {
|
||||
return Err(IdeError::invalid(format!("invalid history id {id:?}")));
|
||||
}
|
||||
match fs::read(self.blob_path(id)) {
|
||||
Ok(bytes) => Ok(String::from_utf8(bytes).unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into())),
|
||||
Ok(bytes) => {
|
||||
let text = String::from_utf8(bytes).unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into());
|
||||
Ok(document_text(&text).into_owned())
|
||||
}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
|
||||
Err(IdeError::not_found(format!("history snapshot {id} not found")))
|
||||
}
|
||||
@@ -532,6 +581,25 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_read_from_disk_matches_the_saved_document_text() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().join("project");
|
||||
fs::create_dir_all(&root).unwrap();
|
||||
let h = LocalHistory::open(&tmp.path().join("history"), &root).unwrap();
|
||||
let a = root.join("a.txt");
|
||||
// A save records the document's text; the file on disk has a BOM and CRLF.
|
||||
fs::write(&a, b"\xEF\xBB\xBFheader\r\nbody\r\n").unwrap();
|
||||
h.record(&a, "header\nbody\n", "Saved").unwrap();
|
||||
assert!(h.record_file(&a, "External change", false).unwrap());
|
||||
let list = h.list(&a).unwrap();
|
||||
assert_eq!(list.iter().map(|e| e.label.as_str()).collect::<Vec<_>>(), ["Saved"], "no second revision");
|
||||
// A snapshot stored with its BOM before reads back as document text.
|
||||
h.record(&a, "\u{feff}old\r\n", "External change").unwrap();
|
||||
let old = &h.list(&a).unwrap()[0];
|
||||
assert_eq!(h.content(&old.id).unwrap(), "old\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn events_labels_and_deletions() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -630,4 +698,42 @@ mod tests {
|
||||
assert_eq!(h.list(Path::new("/p/a")).unwrap().len(), 1);
|
||||
assert_eq!(h.content(&old).unwrap_err().kind, ide_core::error::ErrorKind::NotFound);
|
||||
}
|
||||
#[test]
|
||||
fn a_files_original_content_is_there_at_a_label_put_before_its_first_edit() {
|
||||
use std::time::{Duration, SystemTime};
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().join("project");
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
let h = LocalHistory::open(&tmp.path().join("history"), &root).unwrap();
|
||||
let set_modified = |path: &Path, at: SystemTime| {
|
||||
std::fs::File::options().write(true).open(path).unwrap().set_modified(at).unwrap();
|
||||
};
|
||||
let old = root.join("old.txt");
|
||||
std::fs::write(&old, "as it was").unwrap();
|
||||
set_modified(&old, SystemTime::now() - Duration::from_secs(3600));
|
||||
h.record(&root.join("other.txt"), "x", "Saved").unwrap();
|
||||
std::thread::sleep(Duration::from_millis(2));
|
||||
h.put_label(&root, "checkpoint").unwrap();
|
||||
// Written after the label: it didn't have this content at the label.
|
||||
let new = root.join("new.txt");
|
||||
std::fs::write(&new, "fresh").unwrap();
|
||||
set_modified(&new, SystemTime::now() + Duration::from_secs(1));
|
||||
|
||||
assert!(h.record_original(&old).unwrap());
|
||||
assert!(h.record_original(&new).unwrap());
|
||||
// Only a file without history gets one.
|
||||
assert!(!h.record_original(&old).unwrap());
|
||||
h.record(&old, "edited", "Saved").unwrap();
|
||||
|
||||
let entries = h.list(&old).unwrap();
|
||||
let label = entries.iter().find(|e| e.kind == HistoryKind::Label).unwrap();
|
||||
let original = entries.iter().find(|e| e.label == ORIGINAL).unwrap();
|
||||
assert!(original.timestamp_ms < label.timestamp_ms);
|
||||
assert_eq!(h.content(&original.id).unwrap(), "as it was");
|
||||
// Not dated before the oldest entry kept: no working day of its own.
|
||||
let oldest = h.list(&root.join("other.txt")).unwrap().last().unwrap().timestamp_ms;
|
||||
assert!(original.timestamp_ms >= oldest - 1.0);
|
||||
let fresh = h.list(&new).unwrap().into_iter().find(|e| e.label == ORIGINAL).unwrap();
|
||||
assert!(fresh.timestamp_ms > label.timestamp_ms);
|
||||
}
|
||||
}
|
||||
@@ -96,7 +96,7 @@ Once an agent has run a task, new tasks start in its mode that approves everythi
|
||||
|
||||
### Review the changes
|
||||
|
||||
Click **Show changes** in the task header to list the files the task changed. A task in the project's own checkout lists only the files that changed while the agent was working, not what you or another task changed while it was idle. Click a file to open a diff between the task's starting point and now. For a worktree task, the changes live on its `agent/…` branch: open a terminal there with **Open in Terminal**, and merge or cherry-pick the branch with the Git tools (see [Version control](/en/guide/vcs)) when you are happy with it.
|
||||
Click **Show changes** in the task header to list the files the task changed. A task in the project's own checkout lists only the files that changed while the agent was working, not what you or another task changed while it was idle. Click a file to open a diff between the task's starting point and now. Switch the list from **Whole Task** to **Last Turn** to see only what the last turn changed, against the files as that turn started; rolling back then undoes only that turn. For a worktree task, the changes live on its `agent/…` branch: open a terminal there with **Open in Terminal**, and merge or cherry-pick the branch with the Git tools (see [Version control](/en/guide/vcs)) when you are happy with it.
|
||||
|
||||
Drag the pane's left edge to resize it. The width applies to every task and is remembered across restarts.
|
||||
|
||||
|
||||
@@ -45,14 +45,16 @@ If navigation, search or highlighting doesn't match the files, rebuild the cache
|
||||
|
||||
The Windows packages aren't code-signed yet, so Microsoft Defender SmartScreen may show an unknown-publisher warning. Choose **More info**, then **Run anyway**. See [Install](/en/guide/install#windows).
|
||||
|
||||
## The window stays blank on Linux
|
||||
## The window stays blank or stops responding on Linux
|
||||
|
||||
WebKitGTK's DMA-BUF renderer fails on Wayland with the NVIDIA driver. OpenIDEA detects this combination and sets `WEBKIT_DISABLE_DMABUF_RENDERER=1` itself. If you see a blank or broken window in another setup, quit OpenIDEA and start it from a terminal with that variable set, for example:
|
||||
WebKitGTK's DMA-BUF renderer fails on some Wayland setups. With the NVIDIA driver on Wayland, OpenIDEA turns the driver's explicit sync off for itself (`__NV_DISABLE_EXPLICIT_SYNC=1`), which avoids the failure and keeps the renderer. If the window stays blank, draws incorrectly, or stops reacting to the keyboard and mouse a few seconds after launch in another setup, quit OpenIDEA and start it from a terminal with the DMA-BUF renderer turned off, for example:
|
||||
|
||||
```sh
|
||||
WEBKIT_DISABLE_DMABUF_RENDERER=1 ./OpenIDEA_<version>_amd64.AppImage
|
||||
```
|
||||
|
||||
The page is then drawn without the GPU, so dragging large panels can be slower. To keep the setting for launches from the application menu with the deb or rpm package, copy `/usr/share/applications/OpenIDEA.desktop` to `~/.local/share/applications/` and change its `Exec=` line to `Exec=env WEBKIT_DISABLE_DMABUF_RENDERER=1 openidea`.
|
||||
|
||||
## OpenIDEA exits at startup with a data directory error
|
||||
|
||||
`OPENIDEA_LOCAL_DATA_DIR` is set to a relative path or to a folder that can't be written. Fix or remove the variable. See [Move the local data](/en/reference/data-directories#move-the-local-data).
|
||||
|
||||
@@ -96,7 +96,7 @@ agent 运行过一个任务后,新任务会以它自动批准所有操作的
|
||||
|
||||
### 查看改动
|
||||
|
||||
在任务标题栏中单击 **显示更改**,列出任务改动过的文件。直接在项目中运行的任务只列出 agent 工作期间改动的文件,不包括它空闲时你自己或其他任务做的修改。单击文件可以打开它从任务开始到现在的 diff。worktree 任务的改动在它的 `agent/…` 分支上:用 **在终端中打开** 在那里打开终端,满意后用 Git 工具合并或 cherry-pick 这个分支(见 [版本控制](/zh/guide/vcs))。
|
||||
在任务标题栏中单击 **显示更改**,列出任务改动过的文件。直接在项目中运行的任务只列出 agent 工作期间改动的文件,不包括它空闲时你自己或其他任务做的修改。单击文件可以打开它从任务开始到现在的 diff。把列表从 **整个任务** 切换到 **最近一轮**,就只列出最近一轮的改动,对比的是这一轮开始时的文件;此时回滚也只撤销这一轮的改动。worktree 任务的改动在它的 `agent/…` 分支上:用 **在终端中打开** 在那里打开终端,满意后用 Git 工具合并或 cherry-pick 这个分支(见 [版本控制](/zh/guide/vcs))。
|
||||
|
||||
拖动改动面板的左边缘可以调整宽度。宽度对所有任务生效,重启后保留。
|
||||
|
||||
|
||||
@@ -45,14 +45,16 @@ Java 语言服务器(jdtls)会分析它导入的每个模块,所以大型
|
||||
|
||||
Windows 安装包目前还没有代码签名,Microsoft Defender SmartScreen 可能提示“未知发布者”。点击 **更多信息**,再点击 **仍要运行**。参见[安装](/zh/guide/install)。
|
||||
|
||||
## Linux 上窗口一片空白
|
||||
## Linux 上窗口空白或无响应
|
||||
|
||||
在使用 NVIDIA 驱动的 Wayland 会话中,WebKitGTK 的 DMA-BUF 渲染器会出错。OpenIDEA 检测到这种组合时会自动设置 `WEBKIT_DISABLE_DMABUF_RENDERER=1`。如果在其他环境下也出现空白或显示异常的窗口,先退出 OpenIDEA,再在终端中带上这个变量启动,例如:
|
||||
在部分 Wayland 环境中,WebKitGTK 的 DMA-BUF 渲染器会出错。在使用 NVIDIA 驱动的 Wayland 会话中,OpenIDEA 会为自身关闭驱动的显式同步(`__NV_DISABLE_EXPLICIT_SYNC=1`),这样既能避开问题,又能保留该渲染器。如果在其他环境下窗口一片空白、显示异常,或启动几秒后键盘和鼠标都没有反应,先退出 OpenIDEA,再在终端中关闭 DMA-BUF 渲染器启动,例如:
|
||||
|
||||
```sh
|
||||
WEBKIT_DISABLE_DMABUF_RENDERER=1 ./OpenIDEA_<version>_amd64.AppImage
|
||||
```
|
||||
|
||||
这样页面不再用 GPU 绘制,拖动较大的面板可能变慢。使用 deb 或 rpm 包时,如果希望从应用菜单启动也带上这个设置,把 `/usr/share/applications/OpenIDEA.desktop` 复制到 `~/.local/share/applications/`,并把其中的 `Exec=` 一行改成 `Exec=env WEBKIT_DISABLE_DMABUF_RENDERER=1 openidea`。
|
||||
|
||||
## 启动时提示数据目录错误并退出
|
||||
|
||||
`OPENIDEA_LOCAL_DATA_DIR` 被设成了相对路径或不可写的文件夹。修正或删除这个变量即可。参见[数据目录与日志](/zh/reference/data-directories)。
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
import type { Locator, Page } from "@playwright/test";
|
||||
import type { AgentTask } from "../src/bindings";
|
||||
import { expect, test } from "./fixtures";
|
||||
|
||||
const task: AgentTask = {
|
||||
id: "composer-popup",
|
||||
title: "Composer popup task",
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
isolation: "local",
|
||||
model: null,
|
||||
cwd: "/dev/acme-api",
|
||||
branch: null,
|
||||
base: null,
|
||||
baseCommit: null,
|
||||
error: null,
|
||||
createdMs: 0,
|
||||
updatedMs: 0,
|
||||
config: [],
|
||||
commands: [],
|
||||
usage: null,
|
||||
queue: [],
|
||||
};
|
||||
|
||||
async function openTask(page: Page, delayFiles = false) {
|
||||
await page.evaluate(
|
||||
async ({ task, delayFiles }) => {
|
||||
// Load the workbench modules in Vite's browser realm, not the Playwright runner.
|
||||
const storePath = "/src/features/agents/store.ts";
|
||||
const ipcPath = "/src/platform/ipc.ts";
|
||||
const store = await import(storePath);
|
||||
const { commands } = await import(ipcPath);
|
||||
const { promise: filesReady, resolve } = Promise.withResolvers<void>();
|
||||
if (delayFiles) window.addEventListener("test:release-composer-files", () => resolve(), { once: true });
|
||||
else resolve();
|
||||
const file = (name: string) => ({ path: `${task.cwd}/${name}`, relPath: name, score: 1, indices: [] });
|
||||
commands.agentChanges = async () => ({ status: "ok", data: [] });
|
||||
commands.findFiles = async (query: string) => {
|
||||
if (!query) await filesReady;
|
||||
return {
|
||||
status: "ok",
|
||||
data: query ? [file("a.ts")] : Array.from({ length: 12 }, (_, i) => file(`file${i}.ts`)),
|
||||
};
|
||||
};
|
||||
commands.findDirs = async () => ({ status: "ok", data: [] });
|
||||
store.useAgents.setState({
|
||||
loaded: true,
|
||||
error: null,
|
||||
providers: [],
|
||||
tasks: new Map([[task.id, task]]),
|
||||
entries: new Map([[task.id, [{ type: "agent", text: "Reply" }]]]),
|
||||
composers: new Map(),
|
||||
unread: new Set(),
|
||||
docked: null,
|
||||
homeOpen: false,
|
||||
sessionLocation: "editor",
|
||||
});
|
||||
store.openTask(task.id);
|
||||
},
|
||||
{ task, delayFiles },
|
||||
);
|
||||
const editor = page.getByRole("textbox", { name: "Message", exact: true });
|
||||
await editor.click();
|
||||
return { editor, list: page.getByRole("listbox", { name: "Files", exact: true }) };
|
||||
}
|
||||
|
||||
function geometry(list: Locator) {
|
||||
return list.evaluate((list) => {
|
||||
const popup = list.closest<HTMLElement>("[data-popup]")!;
|
||||
const rect = popup.getBoundingClientRect();
|
||||
const caret = getSelection()!.getRangeAt(0).getBoundingClientRect();
|
||||
const footer = popup.querySelector("span:last-child > kbd")!.getBoundingClientRect();
|
||||
return {
|
||||
side: rect.bottom <= caret.top ? "above" : rect.top >= caret.bottom ? "below" : "overlap",
|
||||
height: popup.offsetHeight,
|
||||
listHeight: list.clientHeight,
|
||||
inViewport: rect.top >= 0 && rect.bottom <= innerHeight && rect.left >= 0 && rect.right <= innerWidth,
|
||||
footerVisible: footer.height > 0 && footer.top >= rect.top && footer.bottom <= rect.bottom,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
const fullList = { side: "above", listHeight: 300, inViewport: true, footerVisible: true };
|
||||
|
||||
test("erasing the @ filter restores the popup's fitting side and height", async ({ workbench: page }) => {
|
||||
const { editor, list } = await openTask(page);
|
||||
await editor.pressSequentially("@");
|
||||
await expect(list.getByText("file0.ts", { exact: true })).toBeVisible();
|
||||
await expect.poll(() => geometry(list)).toMatchObject(fullList);
|
||||
const initial = await geometry(list);
|
||||
|
||||
await editor.pressSequentially("a");
|
||||
await expect(list.getByText("a.ts", { exact: true })).toBeVisible();
|
||||
await expect.poll(() => geometry(list)).toMatchObject({ side: "below", footerVisible: true });
|
||||
await editor.press("Backspace");
|
||||
await expect(list.getByText("file0.ts", { exact: true })).toBeVisible();
|
||||
await expect.poll(() => geometry(list)).toEqual(initial);
|
||||
await expect(editor).toBeFocused();
|
||||
await expect(editor).toHaveText("@");
|
||||
});
|
||||
|
||||
test("first-open @ results can grow and flip after asynchronous file search", async ({ workbench: page }) => {
|
||||
const { editor, list } = await openTask(page, true);
|
||||
for (let i = 0; i < 3; i++) await editor.press("Shift+Enter");
|
||||
await editor.press("ArrowUp");
|
||||
await editor.press("ArrowUp");
|
||||
await editor.press("ArrowUp");
|
||||
await editor.pressSequentially("@");
|
||||
await expect(list.getByRole("option").first()).toBeVisible();
|
||||
await expect.poll(() => geometry(list)).toMatchObject({ side: "below", footerVisible: true });
|
||||
await expect(list.getByText("file0.ts", { exact: true })).toHaveCount(0);
|
||||
|
||||
await page.evaluate(() => window.dispatchEvent(new Event("test:release-composer-files")));
|
||||
await expect(list.getByText("file0.ts", { exact: true })).toBeVisible();
|
||||
await expect.poll(() => geometry(list)).toMatchObject(fullList);
|
||||
await expect(editor).toBeFocused();
|
||||
});
|
||||
+19
-5
@@ -136,34 +136,48 @@
|
||||
window.removeEventListener("unhandledrejection", onRejection);
|
||||
window.removeEventListener("openidea:boot-error", onBootError);
|
||||
window.removeEventListener("openidea:boot-ready", onReady);
|
||||
window.removeEventListener("openidea:boot-question", onQuestion);
|
||||
window.removeEventListener("openidea:boot-answer", onAnswer);
|
||||
document.removeEventListener("visibilitychange", onVisibility);
|
||||
};
|
||||
// The timeout counts only while the window shows: a hidden or covered window gets no
|
||||
// animation frames, and the splash waits for those to finish startup.
|
||||
// The timeout counts only while the window shows and nothing waits for the user: a hidden
|
||||
// or covered window gets no animation frames, and the splash waits for those to finish
|
||||
// startup; a question asked over the splash (Trust Project) holds it until answered.
|
||||
let remaining = 60_000;
|
||||
let armedAt = 0;
|
||||
let timer;
|
||||
let questions = 0;
|
||||
const arm = () => {
|
||||
if (failed || ready || timer !== undefined || document.hidden) return;
|
||||
if (failed || ready || timer !== undefined || document.hidden || questions > 0) return;
|
||||
armedAt = Date.now();
|
||||
timer = window.setTimeout(
|
||||
() => show(rejection === undefined ? text.timeout : `${text.timeout}\n\nUnhandled rejection: ${rejection}`),
|
||||
remaining,
|
||||
);
|
||||
};
|
||||
const onVisibility = () => {
|
||||
if (!document.hidden) return arm();
|
||||
const pause = () => {
|
||||
if (timer === undefined) return;
|
||||
window.clearTimeout(timer);
|
||||
timer = undefined;
|
||||
remaining -= Date.now() - armedAt;
|
||||
};
|
||||
const onVisibility = () => (document.hidden ? pause() : arm());
|
||||
const onQuestion = () => {
|
||||
questions += 1;
|
||||
pause();
|
||||
};
|
||||
const onAnswer = () => {
|
||||
questions = Math.max(0, questions - 1);
|
||||
arm();
|
||||
};
|
||||
arm();
|
||||
document.addEventListener("visibilitychange", onVisibility);
|
||||
window.addEventListener("error", onError, true);
|
||||
window.addEventListener("unhandledrejection", onRejection);
|
||||
window.addEventListener("openidea:boot-error", onBootError);
|
||||
window.addEventListener("openidea:boot-ready", onReady);
|
||||
window.addEventListener("openidea:boot-question", onQuestion);
|
||||
window.addEventListener("openidea:boot-answer", onAnswer);
|
||||
})();
|
||||
|
||||
// Runs before the app's CSS loads: restores the last theme (theme.ts stores it)
|
||||
|
||||
+24
-7
@@ -15,11 +15,24 @@ export const commands = {
|
||||
/** Answers a non-blocking question, without cancelling the current turn. */
|
||||
agentAnswerQuestion: (task: string, question: string, answer: string | null) => typedError<null, IdeError>(__TAURI_INVOKE("agent_answer_question", { task, question, answer })),
|
||||
agentArchive: (task: string) => typedError<null, IdeError>(__TAURI_INVOKE("agent_archive", { task })),
|
||||
/** Content of `path` when the task started (left side of its diff). */
|
||||
agentBaseText: (task: string, path: IpcPath) => typedError<string | null, IdeError>(__TAURI_INVOKE("agent_base_text", { task, path })),
|
||||
/** Content of `path` as `view` compares it (without: when the task started), the left side of its diff. */
|
||||
agentBaseText: (task: string, path: IpcPath, view:
|
||||
/** Everything since the commit the task started from. */
|
||||
"sinceStart" |
|
||||
/** The uncommitted files against `HEAD`; commits made since the start stay. */
|
||||
"group" |
|
||||
/** What the last turn changed, against the checkout as that turn started. */
|
||||
"lastTurn" | null) => typedError<string | null, IdeError>(__TAURI_INVOKE("agent_base_text", { task, path, view })),
|
||||
/** Stops the task's current turn, or with `subagent` only that subagent's work. */
|
||||
agentCancel: (task: string, subagent: string | null) => typedError<null, IdeError>(__TAURI_INVOKE("agent_cancel", { task, subagent })),
|
||||
agentChanges: (task: string) => typedError<AgentChange[], IdeError>(__TAURI_INVOKE("agent_changes", { task })),
|
||||
/** The task's changed files as `view` compares them (without: since it started). */
|
||||
agentChanges: (task: string, view:
|
||||
/** Everything since the commit the task started from. */
|
||||
"sinceStart" |
|
||||
/** The uncommitted files against `HEAD`; commits made since the start stay. */
|
||||
"group" |
|
||||
/** What the last turn changed, against the checkout as that turn started. */
|
||||
"lastTurn" | null) => typedError<AgentChange[], IdeError>(__TAURI_INVOKE("agent_changes", { task, view })),
|
||||
/**
|
||||
* Slash commands to complete for `provider` in `task`'s directory, or in the project
|
||||
* before a task exists (skills and custom commands on disk included).
|
||||
@@ -103,7 +116,9 @@ export const commands = {
|
||||
/** Everything since the commit the task started from. */
|
||||
"sinceStart" |
|
||||
/** The uncommitted files against `HEAD`; commits made since the start stay. */
|
||||
"group" | null) => typedError<null, IdeError>(__TAURI_INVOKE("agent_rollback_changes", { task, paths, view })),
|
||||
"group" |
|
||||
/** What the last turn changed, against the checkout as that turn started. */
|
||||
"lastTurn" | null) => typedError<null, IdeError>(__TAURI_INVOKE("agent_rollback_changes", { task, paths, view })),
|
||||
/** Sends a queued message now, interrupting the current turn. */
|
||||
agentSendQueuedNow: (task: string, queued: string) => typedError<null, IdeError>(__TAURI_INVOKE("agent_send_queued_now", { task, queued })),
|
||||
/**
|
||||
@@ -1295,8 +1310,8 @@ export const commands = {
|
||||
*
|
||||
* Edits go through the document layer as one patch per file, so open editors
|
||||
* update live and undo the whole file's replacements in one step. Unsaved
|
||||
* editor buffers are replaced in place and left unsaved; files that were not
|
||||
* open are opened transiently, saved and closed.
|
||||
* editor buffers are replaced in place and left unsaved; other open documents
|
||||
* are saved, and files that were not open are opened transiently, saved and closed.
|
||||
*
|
||||
* With `all_in_scope` (Replace All after the search hit its match limit) the
|
||||
* scope is searched again without the limit and every match in it is replaced,
|
||||
@@ -2071,7 +2086,9 @@ export type AgentChangesView =
|
||||
/** Everything since the commit the task started from. */
|
||||
"sinceStart" |
|
||||
/** The uncommitted files against `HEAD`; commits made since the start stay. */
|
||||
"group";
|
||||
"group" |
|
||||
/** What the last turn changed, against the checkout as that turn started. */
|
||||
"lastTurn";
|
||||
|
||||
export type AgentCommand = {
|
||||
/** Without the leading `/`. */
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { registerEditorKind, type EditorKindContribution } from "@/workbench/contributions";
|
||||
import { registerEditorKind, setFileDecorations, type EditorKindContribution } from "@/workbench/contributions";
|
||||
import { t } from "@/platform/i18n";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { confirm } from "@/workbench/messages";
|
||||
@@ -166,3 +166,18 @@ describe("editor kinds' isBusy on tab-limit eviction", () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("Close non-modified files first", () => {
|
||||
it("keeps a tab with a VCS change, as Close Unmodified Tabs does", async () => {
|
||||
controller = new EditorController(createMemoryBackend({ "/p/a.ts": "a", "/p/b.ts": "b", "/p/c.ts": "c" }));
|
||||
controller.start();
|
||||
useProject.setState({ settings: { editor: { tabs: { tabLimit: 2, closingPolicy: "unchanged" } } } as never });
|
||||
setFileDecorations("vcs", new Map([["/p/a.ts", { color: "modified" }]]));
|
||||
try {
|
||||
for (const path of ["/p/a.ts", "/p/b.ts", "/p/c.ts"]) await controller.openFile(path);
|
||||
expect(pane().tabs.map((tab) => tab.input.path)).toEqual(["/p/a.ts", "/p/c.ts"]);
|
||||
} finally {
|
||||
setFileDecorations("vcs", new Map());
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -272,6 +272,14 @@ export function tabTrailing(input: EditorInput, kinds: EditorKinds): ReactNode {
|
||||
}
|
||||
}
|
||||
|
||||
/** Unsaved changes or a VCS status: what Close Unmodified Tabs and the tab limit's policy keep. */
|
||||
function tabModified(tab: Tab): boolean {
|
||||
return (
|
||||
(inputDirty(tab.input, useContributions.getState().editorKinds) ?? false) ||
|
||||
!!(tab.input.path && (useDocMeta.getState()[tab.input.path]?.dirty || getFileDecoration(tab.input.path)?.color))
|
||||
);
|
||||
}
|
||||
|
||||
export class EditorController implements SlotHost {
|
||||
manager: DocumentManager;
|
||||
readonly slots = new Map<string, EditorSlot>();
|
||||
@@ -387,10 +395,11 @@ export class EditorController implements SlotHost {
|
||||
// Untitled buffers belong to the window, not a project: their tabs
|
||||
// survive the switch (the backend carries them into the new
|
||||
// registry) and their slots rebuild against the carried documents.
|
||||
// Closing to Welcome drops them; the leave guard already asked about them.
|
||||
const carriedUntitled: Tab[] = [];
|
||||
let carriedActive: string | null = null;
|
||||
const cs = useTabs.getState();
|
||||
for (const pane of Object.values(cs.panes)) {
|
||||
for (const pane of root || s.lightEdit ? Object.values(cs.panes) : []) {
|
||||
for (const tab of pane.tabs) {
|
||||
if (isUntitledUri(tab.input.path ?? "")) {
|
||||
carriedUntitled.push(tab);
|
||||
@@ -1440,8 +1449,7 @@ export class EditorController implements SlotHost {
|
||||
paneId,
|
||||
prefs.tabLimit,
|
||||
prefs.closingPolicy,
|
||||
(tab) =>
|
||||
inputDirty(tab.input, kinds) ?? !!(tab.input.path && useDocMeta.getState()[tab.input.path]?.dirty),
|
||||
tabModified,
|
||||
keep ?? current.panes[paneId]?.active ?? undefined,
|
||||
protect,
|
||||
)
|
||||
@@ -1725,13 +1733,10 @@ export class EditorController implements SlotHost {
|
||||
protect: (tab) => tab.pinned,
|
||||
});
|
||||
}
|
||||
/** Keeps tabs with unsaved changes or a VCS status (IDEA: tabs shown as modified). */
|
||||
/** Keeps tabs with unsaved changes or a VCS status (tabs shown as modified). */
|
||||
closeUnmodified(paneId: string): Promise<boolean> {
|
||||
const modified = (tab: Tab) =>
|
||||
(inputDirty(tab.input, useContributions.getState().editorKinds) ?? false) ||
|
||||
!!(tab.input.path && (useDocMeta.getState()[tab.input.path]?.dirty || getFileDecoration(tab.input.path)?.color));
|
||||
return this.removeGuarded((s) => (s.panes[paneId] ? closeUnmodified(s, paneId, modified) : s), {
|
||||
protect: (tab) => tab.pinned || modified(tab),
|
||||
return this.removeGuarded((s) => (s.panes[paneId] ? closeUnmodified(s, paneId, tabModified) : s), {
|
||||
protect: (tab) => tab.pinned || tabModified(tab),
|
||||
});
|
||||
}
|
||||
closeReadOnly(paneId: string): Promise<boolean> {
|
||||
|
||||
@@ -15,6 +15,7 @@ const { serializeSession } = await import("./model/session");
|
||||
const { useDocMeta } = await import("./model/document");
|
||||
const { save } = await import("@/platform/dialog");
|
||||
const editorKinds = await import("@/workbench/contributions");
|
||||
const { useProject } = await import("@/platform/project");
|
||||
|
||||
let ctrl: InstanceType<typeof EditorController> | null = null;
|
||||
let backend: MemoryBackend;
|
||||
@@ -158,6 +159,19 @@ describe("untitled editor input", () => {
|
||||
expect([...backend.files.keys()]).toEqual(["/p/main.rs"]);
|
||||
});
|
||||
|
||||
it("follows the window into another project but not to the Welcome screen", async () => {
|
||||
const project = (root: string) => ({ root, name: root, trusted: true, isGit: false, settings: {} }) as never;
|
||||
try {
|
||||
await ctrl!.openUntitled({ focus: false });
|
||||
useProject.setState({ project: project("/a") });
|
||||
expect(activeTab().input.kind).toBe("untitled");
|
||||
useProject.setState({ project: null });
|
||||
expect(Object.values(useTabs.getState().panes).flatMap((p) => p.tabs)).toEqual([]);
|
||||
} finally {
|
||||
useProject.setState({ project: null });
|
||||
}
|
||||
});
|
||||
|
||||
it("reuses the buffer for a re-opened untitled name and shares it across tabs", async () => {
|
||||
const info = await backend.openUntitled(null);
|
||||
const twice = await backend.openUntitled("untitled:Untitled-1");
|
||||
|
||||
@@ -36,6 +36,20 @@ describe("Go to Test / Test Subject", () => {
|
||||
expect(d.open).toHaveBeenCalledWith("/p/src/test/java/a/FooTest.java");
|
||||
});
|
||||
|
||||
it("uses the top-level class at the caret when a file declares several", async () => {
|
||||
const files = [
|
||||
"/p/src/main/java/a/Widget.java",
|
||||
"/p/src/test/java/a/WidgetTest.java",
|
||||
"/p/src/test/java/a/HelperTest.java",
|
||||
];
|
||||
const d = { ...deps(files), classAtCaret: async () => "Helper" };
|
||||
await gotoTestOrSubject("/p/src/main/java/a/Widget.java", "", d);
|
||||
expect(d.open).toHaveBeenCalledWith("/p/src/test/java/a/HelperTest.java");
|
||||
const other = { ...deps(files), classAtCaret: async () => null };
|
||||
await gotoTestOrSubject("/p/src/main/java/a/Widget.java", "", other);
|
||||
expect(other.open).toHaveBeenCalledWith("/p/src/test/java/a/WidgetTest.java");
|
||||
});
|
||||
|
||||
it("goes back from a test to its subject", async () => {
|
||||
const d = deps(["/p/src/main/java/a/Foo.java", "/p/src/test/java/a/FooTest.java"]);
|
||||
await gotoTestOrSubject("/p/src/test/java/a/FooTest.java", "", d);
|
||||
|
||||
@@ -36,6 +36,19 @@ export interface TestNavDeps {
|
||||
/** Create New Test… in `directory` (file templates), or a Rust test module in the file itself. */
|
||||
createTest: (req: { directory: string; name: string; extension: string; subject: string }) => void;
|
||||
createRustTestModule: () => void;
|
||||
/** Name of the top-level class, interface, enum or object around the caret, if any. */
|
||||
classAtCaret?: () => Promise<string | null>;
|
||||
}
|
||||
|
||||
/** Languages whose files are named after a class but may declare several top-level ones. */
|
||||
const CLASS_FILE = /\.(java|kt|scala|groovy|cs)$/;
|
||||
|
||||
/** The file name as the class at the caret would have it (`Helper.java` inside `Widget.java`), else the file's own. */
|
||||
async function subjectFileName(path: string, deps: TestNavDeps): Promise<string> {
|
||||
const name = basename(path);
|
||||
if (!CLASS_FILE.test(name) || !deps.classAtCaret) return name;
|
||||
const cls = await deps.classAtCaret().catch(() => null);
|
||||
return cls ? cls + splitName(name).ext : name;
|
||||
}
|
||||
|
||||
const isRustIntegrationTest = (path: string) => path.endsWith(".rs") && /\/tests\/[^/]+\.rs$/.test(path);
|
||||
@@ -88,7 +101,7 @@ function relLabel(root: string | null, path: string) {
|
||||
export async function gotoTestOrSubject(path: string, text: string, deps: TestNavDeps): Promise<void> {
|
||||
const roots = deps.roots();
|
||||
const root = deps.projectRoot();
|
||||
const name = basename(path);
|
||||
const name = await subjectFileName(path, deps);
|
||||
const rank = (paths: string[]) => rankCandidates(path, paths, belowRoot(root, roots));
|
||||
|
||||
if (isTestSide(path, roots)) {
|
||||
|
||||
@@ -22,7 +22,7 @@ import { registerRelatedProvider, relatedItems } from "@/editor/relatedProviders
|
||||
import { gotoTestOrSubject, type TestNavDeps } from "./gotoTest";
|
||||
import { headerSourceItems } from "./headerSource";
|
||||
import { projectPythonHierarchy, pythonSuperDeps } from "./pythonHierarchy";
|
||||
import { baseName, memberAt, methodStop, superMethods, type SuperDeps } from "./structureNav";
|
||||
import { baseName, memberAt, methodStop, superMethods, topLevelTypeAt, type SuperDeps } from "./structureNav";
|
||||
import { tx } from "@/platform/i18n";
|
||||
|
||||
const EDITOR_WHEN = "textEditorActive && (editorFocus || !toolWindowFocus)";
|
||||
@@ -150,6 +150,10 @@ function testDeps(view: EditorView, ctx: EditorDocContext): TestNavDeps {
|
||||
})),
|
||||
}),
|
||||
hint: (text) => showHint(view, text),
|
||||
classAtCaret: async () => {
|
||||
const outline = await call(commands.docOutline(ctx.doc));
|
||||
return topLevelTypeAt(outline, offsetToPos(view.state.doc, view.state.selection.main.head))?.name ?? null;
|
||||
},
|
||||
createTest: ({ directory, name, extension }) =>
|
||||
void executeAction("templates.newFromTemplate", { directory, name, extension, kindId: "test" }),
|
||||
createRustTestModule: () => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { HierarchyItem, OutlineItem, SymbolKind } from "@/platform/ipc";
|
||||
import { memberAt, methodStop, methodStops, superMethods } from "./structureNav";
|
||||
import { memberAt, methodStop, methodStops, superMethods, topLevelTypeAt } from "./structureNav";
|
||||
|
||||
const r = (l1: number, l2: number) => ({ start: { line: l1, col: 0 }, end: { line: l2, col: 1 } });
|
||||
function item(name: string, kind: SymbolKind, from: number, to: number, children: OutlineItem[] = []): OutlineItem {
|
||||
@@ -100,3 +100,12 @@ describe("Super Method", () => {
|
||||
expect(await lines("eat")).toEqual([2, 4]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("topLevelTypeAt", () => {
|
||||
it("answers the outermost type, through namespaces, and nothing outside a type", () => {
|
||||
expect(topLevelTypeAt(OUTLINE, { line: 13, col: 2 })?.name).toBe("Foo");
|
||||
expect(topLevelTypeAt(OUTLINE, { line: 23, col: 0 })).toBeNull();
|
||||
const ns = [item("App", "namespace", 0, 30, [item("Widget", "class", 1, 10), item("Helper", "class", 12, 20)])];
|
||||
expect(topLevelTypeAt(ns, { line: 15, col: 0 })?.name).toBe("Helper");
|
||||
});
|
||||
});
|
||||
@@ -36,6 +36,17 @@ export function methodStop(outline: readonly OutlineItem[], caret: Pos, dir: 1 |
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The outermost type around `caret`, looking through namespaces and packages (C#, Kotlin scripts). */
|
||||
export function topLevelTypeAt(outline: readonly OutlineItem[], caret: Pos): OutlineItem | null {
|
||||
let level: readonly OutlineItem[] = outline;
|
||||
for (;;) {
|
||||
const hit = level.find((i) => inside(i, caret));
|
||||
if (!hit) return null;
|
||||
if (hit.kind !== "namespace" && hit.kind !== "package") return TYPES.has(hit.kind) ? hit : null;
|
||||
level = hit.children;
|
||||
}
|
||||
}
|
||||
|
||||
export interface CaretMember {
|
||||
/** Innermost method at the caret. */
|
||||
method: OutlineItem | null;
|
||||
|
||||
@@ -444,7 +444,7 @@ function CostBadge({ category }: { category: string | null | undefined }) {
|
||||
}
|
||||
|
||||
/** Accessible segmented pill selector (`role="radiogroup"`) with Left/Right arrow navigation. */
|
||||
function SegmentedControl({
|
||||
export function SegmentedControl({
|
||||
ariaLabel,
|
||||
options,
|
||||
value,
|
||||
|
||||
@@ -1280,6 +1280,10 @@
|
||||
flex: none;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.changesScope {
|
||||
flex: none;
|
||||
padding: 6px 10px 2px;
|
||||
}
|
||||
.changesSummary {
|
||||
flex: none;
|
||||
overflow: hidden;
|
||||
|
||||
@@ -46,6 +46,8 @@ function TaskSession({ id, docked }: { id: string; docked: boolean }) {
|
||||
const review = useAgents((s) => s.groupedChanges.get(id));
|
||||
const changes = grouped ? (review?.uncommitted ?? null) : (sinceStart ?? null);
|
||||
const commits = grouped ? (review?.commits ?? []) : [];
|
||||
const scope = useChangesOptions((s) => s.scope);
|
||||
const lastTurn = useAgents((s) => s.turnChanges.get(id));
|
||||
const project = useProject((s) => s.project);
|
||||
const head = useLocalHead(
|
||||
task?.isolation === "local" ? task.status : null,
|
||||
@@ -189,9 +191,10 @@ function TaskSession({ id, docked }: { id: string; docked: boolean }) {
|
||||
{changesOpen && (
|
||||
<ChangesPane
|
||||
task={task}
|
||||
changes={changes ?? null}
|
||||
commits={commits}
|
||||
grouped={grouped}
|
||||
changes={scope === "turn" ? (lastTurn ?? null) : (changes ?? null)}
|
||||
commits={scope === "turn" ? [] : commits}
|
||||
grouped={grouped && scope === "task"}
|
||||
scope={scope}
|
||||
head={head}
|
||||
docked={docked}
|
||||
onHide={() => setChangesOpen(false)}
|
||||
|
||||
@@ -1,15 +1,19 @@
|
||||
/** Changes pane view options, persisted across sessions. */
|
||||
import { create } from "zustand";
|
||||
|
||||
/** What the pane lists: the whole task's changes, or the last turn's. */
|
||||
export type ChangesScope = "task" | "turn";
|
||||
|
||||
export interface ChangesOptions {
|
||||
/** Files grouped by the commit that changed them; otherwise the flat list since the task started. */
|
||||
groupByCommit: boolean;
|
||||
scope: ChangesScope;
|
||||
/** Width of the pane beside the conversation, in px; `null`: the stylesheet's default. */
|
||||
width: number | null;
|
||||
}
|
||||
|
||||
/** IDEA-like default: the review view. */
|
||||
export const DEFAULT_CHANGES_OPTIONS: ChangesOptions = { groupByCommit: true, width: null };
|
||||
export const DEFAULT_CHANGES_OPTIONS: ChangesOptions = { groupByCommit: true, scope: "task", width: null };
|
||||
|
||||
const MIN_CHANGES_WIDTH = 200;
|
||||
const MAX_CHANGES_WIDTH = 1600;
|
||||
@@ -26,6 +30,7 @@ function load(): ChangesOptions {
|
||||
const o = raw ? (JSON.parse(raw) as Record<string, unknown>) : {};
|
||||
return {
|
||||
groupByCommit: typeof o.groupByCommit === "boolean" ? o.groupByCommit : DEFAULT_CHANGES_OPTIONS.groupByCommit,
|
||||
scope: o.scope === "turn" ? "turn" : DEFAULT_CHANGES_OPTIONS.scope,
|
||||
width: typeof o.width === "number" && Number.isFinite(o.width) ? clampChangesWidth(o.width) : null,
|
||||
};
|
||||
} catch {
|
||||
|
||||
@@ -10,7 +10,8 @@ import { confirm } from "@/workbench/messages";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { ChangesResizer } from "../ChangesResizer";
|
||||
import styles from "../Session.module.css";
|
||||
import { setChangesOptions } from "../changesOptions";
|
||||
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";
|
||||
@@ -172,6 +173,7 @@ export function ChangesPane({
|
||||
changes,
|
||||
commits,
|
||||
grouped,
|
||||
scope,
|
||||
head,
|
||||
docked,
|
||||
onHide,
|
||||
@@ -180,20 +182,22 @@ export function ChangesPane({
|
||||
changes: AgentChange[] | null;
|
||||
commits: readonly AgentCommit[];
|
||||
grouped: boolean;
|
||||
scope: ChangesScope;
|
||||
head: string | null;
|
||||
docked: boolean;
|
||||
onHide: () => void;
|
||||
}) {
|
||||
// The two views key their rows differently: a selection doesn't carry over.
|
||||
// The views key their rows differently, and list different changes: a selection doesn't carry over.
|
||||
const view = scope === "turn" ? "turn" : grouped ? "grouped" : "flat";
|
||||
const [selection, setSelection] = useState<{
|
||||
grouped: boolean;
|
||||
view: string;
|
||||
keys: ReadonlySet<string>;
|
||||
}>(() => ({
|
||||
grouped,
|
||||
view,
|
||||
keys: NO_SELECTION,
|
||||
}));
|
||||
const selected = selection.grouped === grouped ? selection.keys : NO_SELECTION;
|
||||
const setSelected = (keys: ReadonlySet<string>) => setSelection({ grouped, keys });
|
||||
const selected = selection.view === view ? selection.keys : NO_SELECTION;
|
||||
const setSelected = (keys: ReadonlySet<string>) => setSelection({ view, keys });
|
||||
const rows = useMemo(() => changeRows(changes ?? [], commits, grouped), [changes, commits, grouped]);
|
||||
// Only the working files roll back; a commit's files are history.
|
||||
const rollbackable = useMemo(() => {
|
||||
@@ -226,13 +230,17 @@ export function ChangesPane({
|
||||
: tx`Roll back the changes to ${count} files?`}
|
||||
</p>
|
||||
<p>
|
||||
{grouped
|
||||
? tx("They go back to the last commit; changes made after it are lost.")
|
||||
: task.isolation === "worktree"
|
||||
? tx("They go back to how they were when the task started, in the task's worktree.")
|
||||
: tx(
|
||||
"They go back to how they were when the task started. Edits of yours made to them since then are lost too; edits from before the task are kept.",
|
||||
)}
|
||||
{scope === "turn"
|
||||
? tx(
|
||||
"They go back to how they were when the last turn started. Edits of yours made to them since then are lost too.",
|
||||
)
|
||||
: grouped
|
||||
? tx("They go back to the last commit; changes made after it are lost.")
|
||||
: task.isolation === "worktree"
|
||||
? tx("They go back to how they were when the task started, in the task's worktree.")
|
||||
: tx(
|
||||
"They go back to how they were when the task started. Edits of yours made to them since then are lost too; edits from before the task are kept.",
|
||||
)}
|
||||
</p>
|
||||
</>
|
||||
),
|
||||
@@ -244,7 +252,7 @@ export function ChangesPane({
|
||||
await rollbackChanges(
|
||||
task.id,
|
||||
picked.length ? picked.map((c) => c.relPath) : null,
|
||||
grouped ? "group" : "sinceStart",
|
||||
scope === "turn" ? "lastTurn" : grouped ? "group" : "sinceStart",
|
||||
);
|
||||
setSelected(new Set());
|
||||
} catch (e) {
|
||||
@@ -256,10 +264,11 @@ export function ChangesPane({
|
||||
}
|
||||
};
|
||||
const accept = async () => {
|
||||
// Accepting brings over the task's whole work, committed or not: grouping only changes the listing.
|
||||
// Accepting brings over the task's whole work, committed or not: grouping and the last turn
|
||||
// only change the listing.
|
||||
const all =
|
||||
grouped && !picked.length
|
||||
? await call(commands.agentChanges(task.id)).catch(() => changes ?? [])
|
||||
(grouped || scope === "turn") && !picked.length
|
||||
? await call(commands.agentChanges(task.id, null)).catch(() => changes ?? [])
|
||||
: (changes ?? []);
|
||||
const targets = picked.length ? picked : all;
|
||||
const count = targets.length;
|
||||
@@ -334,7 +343,7 @@ export function ChangesPane({
|
||||
onClick={() => void rollback()}
|
||||
/>
|
||||
<IconButton icon="refresh" title="Refresh" onClick={() => void refreshChanges(task.id)} />
|
||||
{task.isolation === "worktree" && (
|
||||
{task.isolation === "worktree" && scope === "task" && (
|
||||
<IconButton
|
||||
icon="eye"
|
||||
title="View Options"
|
||||
@@ -357,9 +366,29 @@ export function ChangesPane({
|
||||
)}
|
||||
{!docked && <IconButton icon="chevron-right" title={tx("Hide changes")} size="small" onClick={onHide} />}
|
||||
</div>
|
||||
{(grouped || head || task.base) && (
|
||||
<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}>
|
||||
<T>vs</T> {grouped ? "HEAD" : (head ?? task.base)}
|
||||
{scope === "turn" ? (
|
||||
<T>Since the last turn started</T>
|
||||
) : (
|
||||
<>
|
||||
<T>vs</T> {grouped ? "HEAD" : (head ?? task.base)}
|
||||
</>
|
||||
)}
|
||||
{changes && changes.length > 0 && (
|
||||
<>
|
||||
{" "}
|
||||
@@ -373,7 +402,7 @@ export function ChangesPane({
|
||||
<Spinner />
|
||||
) : (
|
||||
<Tree<ChangeRow>
|
||||
key={grouped ? "grouped" : "flat"}
|
||||
key={view}
|
||||
aria-label="Changed files"
|
||||
roots={rows}
|
||||
getKey={(n) => n.key}
|
||||
@@ -392,7 +421,7 @@ export function ChangesPane({
|
||||
if (n.type === "file") {
|
||||
if (n.commit) void openCommitDiff(task, n.commit, n.change.path);
|
||||
else if (grouped) void openUncommittedDiff(task, n.change.path);
|
||||
else void openChangeDiff(task, n.change.path);
|
||||
else void openChangeDiff(task, n.change.path, scope);
|
||||
} else if (n.type === "commit") {
|
||||
void openCommitDiff(task, n.commit, n.commit.files[0]?.path ?? "");
|
||||
}
|
||||
@@ -449,7 +478,7 @@ export function ChangesPane({
|
||||
}}
|
||||
empty={
|
||||
<div className={styles.changesEmpty}>
|
||||
<T>No changes yet</T>
|
||||
{scope === "turn" ? <T>The last turn changed no files</T> : <T>No changes yet</T>}
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
@@ -459,15 +488,18 @@ export function ChangesPane({
|
||||
);
|
||||
}
|
||||
|
||||
/** Opens the diff of `path` between the task's start and now. */
|
||||
export async function openChangeDiff(task: AgentTask, path: string) {
|
||||
const changed = (useAgents.getState().changes.get(task.id) ?? []).map((change) => change.path);
|
||||
/** Opens the diff of `path` between the task's start (or its last turn's) and now. */
|
||||
export async function openChangeDiff(task: AgentTask, path: string, scope: ChangesScope = "task") {
|
||||
const { changes, turnChanges } = useAgents.getState();
|
||||
const changed = ((scope === "turn" ? turnChanges : changes).get(task.id) ?? []).map((change) => change.path);
|
||||
const paths = changed.includes(path) ? changed : [path];
|
||||
const baseLabel = task.base ?? "Base";
|
||||
const baseLabel = scope === "turn" ? tx("Before Last Turn") : (task.base ?? "Base");
|
||||
const right = task.isolation === "worktree" ? branchLabel(task.branch) : "Working tree";
|
||||
const diffs = await Promise.all(
|
||||
paths.map(async (file): Promise<DiffData> => {
|
||||
const base = await call(commands.agentBaseText(task.id, file)).catch(() => null);
|
||||
const base = await call(commands.agentBaseText(task.id, file, scope === "turn" ? "lastTurn" : null)).catch(
|
||||
() => null,
|
||||
);
|
||||
return {
|
||||
path: file,
|
||||
left: { type: "text", text: base ?? "", label: baseLabel },
|
||||
|
||||
@@ -33,6 +33,7 @@ const backend = vi.hoisted(() => ({
|
||||
entries: new Map<string, AgentEntry[]>(),
|
||||
changes: [] as AgentChange[],
|
||||
changesCalls: 0,
|
||||
turnChanges: [] as AgentChange[],
|
||||
grouped: { uncommitted: [] as AgentChange[], commits: [] as AgentCommit[] },
|
||||
groupedCalls: 0,
|
||||
rolledBack: [] as Array<[string, string[] | null, string | null]>,
|
||||
@@ -84,7 +85,8 @@ vi.mock("@/platform/ipc", async (original) => ({
|
||||
};
|
||||
return { status: "ok", data: backend.entries.get(key) ?? [] };
|
||||
},
|
||||
agentChanges: async () => {
|
||||
agentChanges: async (_task: string, view: string | null) => {
|
||||
if (view === "lastTurn") return { status: "ok", data: backend.turnChanges };
|
||||
backend.changesCalls += 1;
|
||||
return { status: "ok", data: backend.changes };
|
||||
},
|
||||
@@ -230,12 +232,13 @@ beforeEach(() => {
|
||||
localStorage.clear();
|
||||
backend.changes = [];
|
||||
backend.changesCalls = 0;
|
||||
backend.turnChanges = [];
|
||||
backend.grouped = { uncommitted: [], commits: [] };
|
||||
backend.groupedCalls = 0;
|
||||
backend.rolledBack = [];
|
||||
backend.external = [];
|
||||
// The flat list unless a test asks for the grouped view, so counts and selections stay as before.
|
||||
useChangesOptions.setState({ groupByCommit: false });
|
||||
useChangesOptions.setState({ groupByCommit: false, scope: "task" });
|
||||
backend.imported = [];
|
||||
backend.importError = null;
|
||||
backend.importErrors = new Map();
|
||||
@@ -2970,6 +2973,43 @@ describe("accept changes", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("last turn changes", () => {
|
||||
const change = (path: string): AgentChange => ({
|
||||
path: `/project/${path}`,
|
||||
relPath: path,
|
||||
kind: "modified",
|
||||
added: 1,
|
||||
removed: 0,
|
||||
oldPath: null,
|
||||
});
|
||||
|
||||
it("lists and rolls back only what the last turn changed, the session still counting the whole task", async () => {
|
||||
backend.changes = [change("a.ts"), change("b.ts")];
|
||||
backend.turnChanges = [change("b.ts")];
|
||||
localStorage.setItem("openidea.agents.changesOpen.v1", JSON.stringify({ A: true }));
|
||||
useAgents.setState({ tasks: new Map([["A", { ...task("A"), status: "ready" }]]) });
|
||||
render(<SessionEditor input={input("A")} />);
|
||||
const pane = await screen.findByRole("complementary", { name: "Changes" });
|
||||
expect(await within(pane).findByText("a.ts")).toBeInTheDocument();
|
||||
|
||||
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();
|
||||
expect(useChangesOptions.getState().scope).toBe("turn");
|
||||
expect(screen.getByRole("button", { name: /2 changed files/ })).toBeInTheDocument();
|
||||
|
||||
fireEvent.click(within(pane).getByRole("button", { name: "Rollback All Changes…" }));
|
||||
await waitFor(() => expect(backend.rolledBack).toEqual([["A", null, "lastTurn"]]));
|
||||
|
||||
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("radio", { name: "Whole Task" }));
|
||||
expect(await within(pane).findByText("a.ts")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe("grouped changes", () => {
|
||||
const commit = (overrides: Partial<AgentCommit> = {}): AgentCommit => ({
|
||||
id: "a".repeat(40),
|
||||
|
||||
@@ -98,6 +98,8 @@ interface AgentsState {
|
||||
changes: Map<string, AgentChange[]>;
|
||||
/** The task's uncommitted changes and commits, when the Changes pane groups by commit. */
|
||||
groupedChanges: Map<string, AgentChanges>;
|
||||
/** What the task's last turn changed, when the Changes pane shows that. */
|
||||
turnChanges: Map<string, AgentChange[]>;
|
||||
/** Scroll position and follow-output preference by conversation, shared by both hosts. */
|
||||
scrollPositions: Map<string, { top: number; stick: boolean }>;
|
||||
providers: AgentProvider[];
|
||||
@@ -186,6 +188,7 @@ export const useAgents = create<AgentsState>(() => ({
|
||||
entryLoads: new Map(),
|
||||
changes: new Map(),
|
||||
groupedChanges: new Map(),
|
||||
turnChanges: new Map(),
|
||||
providers: [],
|
||||
limits: new Map(),
|
||||
modelCatalogs: new Map(),
|
||||
@@ -496,6 +499,7 @@ export async function connect(): Promise<void> {
|
||||
entryLoads: new Map(),
|
||||
changes: new Map(),
|
||||
groupedChanges: new Map(),
|
||||
turnChanges: new Map(),
|
||||
providers,
|
||||
organizeRoot,
|
||||
organize: pruneOrganize(loadOrganize(organizeRoot), tasks),
|
||||
@@ -599,12 +603,18 @@ function withoutTaskCache(s: AgentsState, taskId: string): Partial<AgentsState>
|
||||
groupedChanges = new Map(s.groupedChanges);
|
||||
groupedChanges.delete(taskId);
|
||||
}
|
||||
if (!entries && !entryLoads && !changes && !groupedChanges) return null;
|
||||
let turnChanges: Map<string, AgentChange[]> | undefined;
|
||||
if (s.turnChanges.has(taskId)) {
|
||||
turnChanges = new Map(s.turnChanges);
|
||||
turnChanges.delete(taskId);
|
||||
}
|
||||
if (!entries && !entryLoads && !changes && !groupedChanges && !turnChanges) return null;
|
||||
return {
|
||||
...(entries ? { entries } : {}),
|
||||
...(entryLoads ? { entryLoads } : {}),
|
||||
...(changes ? { changes } : {}),
|
||||
...(groupedChanges ? { groupedChanges } : {}),
|
||||
...(turnChanges ? { turnChanges } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -625,7 +635,7 @@ function isTaskOpenInUi(taskId: string): boolean {
|
||||
/** Whether a background trigger should reload a task's changes: only while they are shown or still cached. */
|
||||
function wantsChanges(taskId: string): boolean {
|
||||
const s = useAgents.getState();
|
||||
return s.changes.has(taskId) || s.groupedChanges.has(taskId) || isTaskOpenInUi(taskId);
|
||||
return s.changes.has(taskId) || s.groupedChanges.has(taskId) || s.turnChanges.has(taskId) || isTaskOpenInUi(taskId);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -667,6 +677,7 @@ export function disconnect() {
|
||||
entryLoads: new Map(),
|
||||
changes: new Map(),
|
||||
groupedChanges: new Map(),
|
||||
turnChanges: new Map(),
|
||||
modelCatalogs: new Map(),
|
||||
modelRequests: new Set(),
|
||||
modelRequestTargets: new Map(),
|
||||
@@ -846,11 +857,25 @@ export async function loadEntries(task: string, subagent: string | null = null):
|
||||
}
|
||||
|
||||
export async function refreshChanges(task: string): Promise<void> {
|
||||
// Discard a result that arrives after a project switch, the task's deletion, or its cache being dropped.
|
||||
const gen = generation;
|
||||
const drops = cacheDrops.get(task);
|
||||
// Discard a result that arrives after a project switch, the task's deletion, or its cache being dropped.
|
||||
const stillWanted = () =>
|
||||
gen === generation && useAgents.getState().tasks.has(task) && cacheDrops.get(task) === drops;
|
||||
// The whole task's changes are read in either scope: the session's summary counts them.
|
||||
await Promise.all([
|
||||
refreshTaskChanges(task, stillWanted),
|
||||
useChangesOptions.getState().scope === "turn" && refreshTurnChanges(task, stillWanted),
|
||||
]);
|
||||
}
|
||||
|
||||
async function refreshTurnChanges(task: string, stillWanted: () => boolean): Promise<void> {
|
||||
const changes = await call(commands.agentChanges(task, "lastTurn")).catch(() => []);
|
||||
if (!stillWanted()) return;
|
||||
useAgents.setState((s) => ({ turnChanges: new Map(s.turnChanges).set(task, changes) }));
|
||||
}
|
||||
|
||||
async function refreshTaskChanges(task: string, stillWanted: () => boolean): Promise<void> {
|
||||
// Local tasks have no commits of their own to group: the flat list is their only view.
|
||||
const grouped =
|
||||
useChangesOptions.getState().groupByCommit && useAgents.getState().tasks.get(task)?.isolation === "worktree";
|
||||
@@ -871,7 +896,7 @@ export async function refreshChanges(task: string): Promise<void> {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const changes = await call(commands.agentChanges(task));
|
||||
const changes = await call(commands.agentChanges(task, null));
|
||||
if (!stillWanted()) return;
|
||||
useAgents.setState((s) => ({
|
||||
changes: new Map(s.changes).set(task, changes),
|
||||
|
||||
@@ -56,7 +56,10 @@ vi.mock("@/platform/ipc", async (original) => ({
|
||||
agentProviders: async () => ({ status: "ok", data: [] }),
|
||||
agentChanges: async () => ({ status: "ok", data: [] }),
|
||||
agentGroupedChanges: async () => ({ status: "ok", data: { uncommitted: [], commits: [] } }),
|
||||
agentBaseText: async (_task: string, path: string) => ({ status: "ok", data: `base of ${path}` }),
|
||||
agentBaseText: async (_task: string, path: string, view: string | null) => ({
|
||||
status: "ok",
|
||||
data: view === "lastTurn" ? `before the last turn: ${path}` : `base of ${path}`,
|
||||
}),
|
||||
agentEntries: async () => ({ status: "ok", data: await backend.entries }),
|
||||
},
|
||||
}));
|
||||
@@ -522,6 +525,21 @@ describe("the diff of an agent change", () => {
|
||||
expect(input.data.chain[0].left.text).toBe("base of /project/a.ts");
|
||||
});
|
||||
|
||||
it("in the last turn, lists that turn's files against how they were as it started", async () => {
|
||||
useAgents.setState({
|
||||
changes: new Map([["one", [change("/project/a.ts"), change("/project/b.ts")]]]),
|
||||
turnChanges: new Map([["one", [change("/project/b.ts")]]]),
|
||||
});
|
||||
await openChangeDiff(task("one"), "/project/b.ts", "turn");
|
||||
const input = backend.openInput.mock.lastCall![0];
|
||||
expect(input.data.left).toEqual({
|
||||
type: "text",
|
||||
text: "before the last turn: /project/b.ts",
|
||||
label: "Before Last Turn",
|
||||
});
|
||||
expect(input.data.chain).toBeUndefined();
|
||||
});
|
||||
|
||||
it("opens a file outside the change list on its own", async () => {
|
||||
useAgents.setState({ changes: new Map([["one", [change("/project/a.ts")]]]) });
|
||||
await openChangeDiff(task("one"), "/project/c.ts");
|
||||
|
||||
@@ -1,9 +1,23 @@
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import type { Diagnostic, InspectEvent } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { installInspectionProfileSync, resetInspection, runInspection, useInspection } from "./inspect";
|
||||
import {
|
||||
installInspectionProfileSync,
|
||||
rerunInspection,
|
||||
resetInspection,
|
||||
runInspection,
|
||||
useInspection,
|
||||
} from "./inspect";
|
||||
|
||||
const mock = vi.hoisted(() => ({ channel: null as null | { onmessage: (event: InspectEvent) => void } }));
|
||||
const mock = vi.hoisted(() => ({
|
||||
channel: null as null | { onmessage: (event: InspectEvent) => void },
|
||||
scopes: [] as unknown[],
|
||||
active: "/p/a.ts",
|
||||
}));
|
||||
vi.mock("@/editor/api", async (original) => ({
|
||||
...(await original<object>()),
|
||||
activeEditor: () => ({ ctx: { path: mock.active, virtual: false } }),
|
||||
}));
|
||||
vi.mock("@tauri-apps/api/core", () => ({
|
||||
Channel: class {
|
||||
onmessage = () => {};
|
||||
@@ -14,7 +28,8 @@ vi.mock("@/platform/ipc", async (original) => ({
|
||||
isTauri: () => true,
|
||||
call: (value: unknown) => value,
|
||||
commands: {
|
||||
inspectCode: (_id: unknown, _scope: unknown, channel: typeof mock.channel) => {
|
||||
inspectCode: (_id: unknown, scope: unknown, channel: typeof mock.channel) => {
|
||||
mock.scopes.push(scope);
|
||||
mock.channel = channel;
|
||||
return Promise.resolve();
|
||||
},
|
||||
@@ -97,3 +112,17 @@ it("retains initially disabled diagnostics and uses edits made during streaming"
|
||||
dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it("reruns the file the results are for, not the file now active", async () => {
|
||||
mock.scopes = [];
|
||||
mock.active = "/p/a.ts";
|
||||
await runInspection({ kind: "file", directory: "" }, "default");
|
||||
mock.active = "/p/b.ts";
|
||||
rerunInspection();
|
||||
await vi.waitFor(() => expect(mock.scopes).toHaveLength(2));
|
||||
expect(mock.scopes).toEqual([
|
||||
{ kind: "files", paths: ["/p/a.ts"] },
|
||||
{ kind: "files", paths: ["/p/a.ts"] },
|
||||
]);
|
||||
expect(useInspection.getState().scopeLabel).toBe("File /p/a.ts");
|
||||
});
|
||||
@@ -200,7 +200,8 @@ export async function runInspection(choice: ScopeChoice, profileId: ProfileId =
|
||||
summary: null,
|
||||
error: null,
|
||||
scopeLabel: describeScope(choice, scope),
|
||||
last: choice,
|
||||
// Rerun repeats this run's scope: "Current file" stays the file inspected now.
|
||||
last: choice.kind === "file" && scope.kind === "files" ? { ...choice, file: scope.paths[0] } : choice,
|
||||
profile: profileId,
|
||||
excluded: new Set(),
|
||||
});
|
||||
|
||||
@@ -15,6 +15,8 @@ export interface ScopeChoice {
|
||||
directory: string;
|
||||
/** Name of the custom scope for `custom` (`@/platform/search`). */
|
||||
custom?: string;
|
||||
/** The file `file` resolved to, so a rerun inspects it again rather than the file now active. */
|
||||
file?: string;
|
||||
}
|
||||
|
||||
export const SCOPE_LABELS: Record<ScopeKind, string> = {
|
||||
@@ -58,7 +60,7 @@ export async function resolveScope(choice: ScopeChoice): Promise<SearchScope | s
|
||||
case "directory":
|
||||
return choice.directory.trim() ? { kind: "directory", path: choice.directory.trim() } : "Choose a directory";
|
||||
case "file": {
|
||||
const file = currentFile();
|
||||
const file = choice.file ?? currentFile();
|
||||
return file ? { kind: "files", paths: [file] } : "No file is open";
|
||||
}
|
||||
case "changed": {
|
||||
|
||||
@@ -192,6 +192,20 @@ describe("replacing a project in this window", () => {
|
||||
expect(useProject.getState().project?.root).toBe("/local");
|
||||
});
|
||||
|
||||
it("asks about trust before leaving, so Don't Open keeps the current project running", async () => {
|
||||
useProject.setState({
|
||||
...projectState("/a"),
|
||||
settings: { general: { openProjectIn: "same" } },
|
||||
} as never);
|
||||
windowOpenProject.mockResolvedValue(ok({ kind: "current" }));
|
||||
vi.mocked(confirmProjectTrust).mockRejectedValueOnce(new IpcError({ kind: "cancelled", message: "Cancelled" }));
|
||||
await openProjectWithPolicy("/b");
|
||||
expect(confirmProjectTrust).toHaveBeenCalledWith("/b", "local");
|
||||
expect(confirmLeaveProject).not.toHaveBeenCalled();
|
||||
expect(openProject).not.toHaveBeenCalled();
|
||||
expect(notify).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("opens the local project when its path matches the remote root", async () => {
|
||||
useProject.setState({
|
||||
...projectState("/same"),
|
||||
@@ -792,11 +806,14 @@ describe("trust is asked before a new project window opens", () => {
|
||||
expect(windowOpenProject).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("asks only once, from openProject, when the project opens in this window", async () => {
|
||||
it("asks once this window takes the project, before leaving its current one", async () => {
|
||||
windowOpenProject.mockResolvedValue(ok({ kind: "current" }));
|
||||
await openProjectInWindow("/p/b", false);
|
||||
expect(windowOpenProject).toHaveBeenCalledWith("/p/b", false, []);
|
||||
expect(confirmProjectTrust).not.toHaveBeenCalled();
|
||||
expect(confirmProjectTrust).toHaveBeenCalledOnce();
|
||||
expect(vi.mocked(confirmProjectTrust).mock.invocationCallOrder[0]).toBeLessThan(
|
||||
vi.mocked(confirmLeaveProject).mock.invocationCallOrder[0]!,
|
||||
);
|
||||
expect(openProject).toHaveBeenCalledWith("/p/b");
|
||||
});
|
||||
});
|
||||
@@ -25,6 +25,7 @@ import { isDistractionFree, useDistractionFree } from "@/workbench/distractionFr
|
||||
import { orderStatusItems } from "@/workbench/StatusBar";
|
||||
import { statusWidgetRows } from "@/workbench/statusBarWidgets";
|
||||
import { useToolWindowLayouts } from "@/workbench/toolwindows/layouts";
|
||||
import { toolWindowsRestorable, useToolWindowLayout } from "@/workbench/toolwindows/store";
|
||||
import { hostOs, type HostOs } from "./host";
|
||||
|
||||
export const MENU_EVENT = "openidea://menu";
|
||||
@@ -100,7 +101,11 @@ export function menuAccelerator(binding: string): string | undefined {
|
||||
export function buildMenuConfig(os: HostOs): MenuConfig {
|
||||
const labels: Record<string, string> = {};
|
||||
// Per-window state some labels follow (View › Appearance › Enter / Exit Distraction Free Mode).
|
||||
const params = { os, distractionFree: isDistractionFree() ? "on" : "off" };
|
||||
const params = {
|
||||
os,
|
||||
distractionFree: isDistractionFree() ? "on" : "off",
|
||||
toolWindows: toolWindowsRestorable() ? "hidden" : "shown",
|
||||
};
|
||||
for (const key of keysWithPrefix("menu.")) labels[key] = t(key, params);
|
||||
const accelerators: Record<string, string> = {};
|
||||
const seen = new Set<string>();
|
||||
@@ -265,6 +270,10 @@ export function installMenuBridge(): () => void {
|
||||
useDistractionFree.subscribe((s, prev) => {
|
||||
if (s.active !== prev.active) push();
|
||||
}),
|
||||
// Window › Hide All Tool Windows reads "Restore Tool Windows" while it would restore them.
|
||||
useToolWindowLayout.subscribe((s, prev) => {
|
||||
if (toolWindowsRestorable(s) !== toolWindowsRestorable(prev)) push();
|
||||
}),
|
||||
useContributions.subscribe((s, prev) => {
|
||||
if (s.toolWindows !== prev.toolWindows || s.statusItems !== prev.statusItems) push();
|
||||
}),
|
||||
|
||||
@@ -57,6 +57,13 @@ async function openHere(path: string): Promise<boolean> {
|
||||
if (!isRemoteWindow() && useProject.getState().project?.root === path) return true;
|
||||
// A folder of a WSL distro runs there, not as a network folder; the window then drops untitled buffers.
|
||||
const wsl = await commands.wslResolve(path).catch(() => null);
|
||||
try {
|
||||
// Asked before leaving, so Don't Open keeps the current project and its processes running.
|
||||
if (!wsl) await confirmProjectTrust(path, "local");
|
||||
} catch (e) {
|
||||
openFailed(path, e);
|
||||
return false;
|
||||
}
|
||||
if (!(await confirmLeaveProject(!wsl))) return false;
|
||||
try {
|
||||
if (wsl) await connectRemote(wsl.target, wsl.path);
|
||||
|
||||
@@ -410,6 +410,91 @@ describe("build feature", () => {
|
||||
expect(notes).toHaveLength(0);
|
||||
});
|
||||
|
||||
it.each(["cancelled", "failed", "succeeded"])("ignores a previous project's build that %s", async (outcome) => {
|
||||
const previous = startBuild("build", null, false);
|
||||
await act(async () => {});
|
||||
const oldRequest = useBuildRun.getState().request;
|
||||
useProject.setState({ project: { root: "/other", name: "other" } as never });
|
||||
expect(fake.cancelled).toEqual([oldRequest]);
|
||||
|
||||
const nextBackend = new FakeBackend();
|
||||
setBuildBackend(nextBackend);
|
||||
const next = startCompileFile("/other/Main.java", false);
|
||||
await act(async () => {});
|
||||
const current = useBuildRun.getState();
|
||||
expect(current.request).not.toBe(oldRequest);
|
||||
|
||||
fake.emit!({ kind: "output", text: "old output\n", stderr: false });
|
||||
if (outcome === "cancelled") fake.reject(new IpcError({ kind: "cancelled", message: "Cancelled" }));
|
||||
else if (outcome === "failed") fake.reject(new Error("Old build failed"));
|
||||
else fake.resolve(result([], true));
|
||||
const previousResult = await previous;
|
||||
expect(useBuildRun.getState()).toBe(current);
|
||||
expect(previousResult).toBeNull();
|
||||
expect(getContext()["build.lastStatus"]).toBeNull();
|
||||
expect(getContext()["build.running"]).toBe(true);
|
||||
expect(isActionEnabled(getAction("build.stop")!)).toBe(true);
|
||||
expect(useTasks.getState().tasks.find((task) => task.id === BUILD_TASK_ID)).toMatchObject({
|
||||
title: "Compile File",
|
||||
done: false,
|
||||
});
|
||||
expect(notes).toEqual([]);
|
||||
expect(show).not.toHaveBeenCalled();
|
||||
expect(openFile).not.toHaveBeenCalled();
|
||||
|
||||
stopBuild();
|
||||
expect(nextBackend.cancelled).toEqual([current.request]);
|
||||
nextBackend.reject(new IpcError({ kind: "cancelled", message: "Cancelled" }));
|
||||
await next;
|
||||
expect(useBuildRun.getState().status).toBe("cancelled");
|
||||
expect(isActionEnabled(getAction("build.stop")!)).toBe(false);
|
||||
});
|
||||
|
||||
it("drops a previous project's build that was waiting for Save All", async () => {
|
||||
let saved!: () => void;
|
||||
const saving = new Promise<void>((resolve) => (saved = resolve));
|
||||
provideEditorService({
|
||||
openFile,
|
||||
saveAll: vi.fn().mockReturnValueOnce(saving).mockResolvedValue(undefined),
|
||||
activePath: () => null,
|
||||
} as unknown as EditorService);
|
||||
const previous = startBuild("build", null, false);
|
||||
useProject.setState({ project: { root: "/other", name: "other" } as never });
|
||||
const next = startCompileFile("/other/Main.java", false);
|
||||
await act(async () => {});
|
||||
saved();
|
||||
await act(async () => {});
|
||||
|
||||
expect(fake.calls).toEqual([{ kind: "compileFile", file: "/other/Main.java", clear: [] }]);
|
||||
expect(await previous).toBeNull();
|
||||
fake.resolve(result([], true));
|
||||
await next;
|
||||
expect(useBuildRun.getState().status).toBe("success");
|
||||
});
|
||||
|
||||
it("keeps the next build's progress when the finished task's linger expires", async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
const previous = startBuild("build", null, false);
|
||||
await act(async () => {});
|
||||
fake.resolve(result([], true));
|
||||
await previous;
|
||||
useProject.setState({ project: { root: "/other", name: "other" } as never });
|
||||
const next = startBuild("rebuild", null, false);
|
||||
await act(async () => {});
|
||||
|
||||
await vi.advanceTimersByTimeAsync(600);
|
||||
expect(useTasks.getState().tasks.find((task) => task.id === BUILD_TASK_ID)).toMatchObject({
|
||||
title: "Rebuild",
|
||||
done: false,
|
||||
});
|
||||
fake.resolve(result([], true));
|
||||
await next;
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it("compiles one file without its module and reruns it from the tool window", async () => {
|
||||
const run = startCompileFile("/p/core/src/A.java");
|
||||
await act(async () => {});
|
||||
|
||||
+17
-10
@@ -204,17 +204,20 @@ async function executeBuild(
|
||||
invoke: (previous: string[], onEvent: (e: BuildEvent) => void) => Promise<BuildResult>,
|
||||
cancel: () => void,
|
||||
): Promise<BuildResult | null> {
|
||||
const ownsBuild = () => useBuildRun.getState().request === request;
|
||||
await maybeEditorService()
|
||||
?.saveAll()
|
||||
.catch(() => undefined);
|
||||
if (!ownsBuild()) return null;
|
||||
|
||||
let queue: BuildEvent[] = [];
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const flush = () => {
|
||||
clearTimeout(timer);
|
||||
timer = undefined;
|
||||
const events = queue;
|
||||
queue = [];
|
||||
if (useBuildRun.getState().request !== request || !events.length) return;
|
||||
if (!ownsBuild() || !events.length) return;
|
||||
let s = useBuildRun.getState();
|
||||
for (const e of events) s = { ...s, ...applyBuildEvent(s, e) };
|
||||
useBuildRun.setState(s);
|
||||
@@ -222,6 +225,7 @@ async function executeBuild(
|
||||
upsertTask({ id: BUILD_TASK_ID, title: taskTitle, message: s.message, fraction: null, done: false, cancel });
|
||||
};
|
||||
const onEvent = (e: BuildEvent) => {
|
||||
if (!ownsBuild()) return;
|
||||
queue.push(e);
|
||||
timer ??= setTimeout(flush, 16);
|
||||
};
|
||||
@@ -229,7 +233,7 @@ async function executeBuild(
|
||||
let result: BuildResult | null = null;
|
||||
try {
|
||||
result = await invoke(useBuildRun.getState().files, onEvent);
|
||||
clearTimeout(timer);
|
||||
if (!ownsBuild()) return null;
|
||||
flush();
|
||||
const status: BuildStatus = result.success ? "success" : "failed";
|
||||
useBuildRun.setState({
|
||||
@@ -255,7 +259,7 @@ async function executeBuild(
|
||||
});
|
||||
if (!result.success) showFailure();
|
||||
} catch (e) {
|
||||
clearTimeout(timer);
|
||||
if (!ownsBuild()) return null;
|
||||
flush();
|
||||
if (isCancelled(e)) {
|
||||
useBuildRun.setState({ status: "cancelled", files: [], message: null });
|
||||
@@ -278,13 +282,16 @@ async function executeBuild(
|
||||
showFailure();
|
||||
}
|
||||
} finally {
|
||||
if (useBuildRun.getState().request === request) useBuildRun.setState({ request: null });
|
||||
setContext(
|
||||
BUILD_LAST_STATUS,
|
||||
result?.success ? "success" : useBuildRun.getState().status === "cancelled" ? "cancelled" : "failed",
|
||||
);
|
||||
setContext(BUILD_RUNNING, false);
|
||||
upsertTask({ id: BUILD_TASK_ID, title: taskTitle, message: null, fraction: 1, done: true });
|
||||
clearTimeout(timer);
|
||||
if (ownsBuild()) {
|
||||
useBuildRun.setState({ request: null });
|
||||
setContext(
|
||||
BUILD_LAST_STATUS,
|
||||
result?.success ? "success" : useBuildRun.getState().status === "cancelled" ? "cancelled" : "failed",
|
||||
);
|
||||
setContext(BUILD_RUNNING, false);
|
||||
upsertTask({ id: BUILD_TASK_ID, title: taskTitle, message: null, fraction: 1, done: true });
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -24,6 +24,18 @@ describe("Language server status popup", () => {
|
||||
off();
|
||||
});
|
||||
|
||||
it("opens a server's settings from its row", () => {
|
||||
const run = vi.fn();
|
||||
const off = registerAction({ id: "tools.languageServers", title: "Language Servers…", run: ({ arg }) => run(arg) });
|
||||
useServers.setState({ servers: new Map([[1 as never, server("ready", null)]]) });
|
||||
render(<ServerStatus />);
|
||||
fireEvent.click(screen.getByRole("button", { name: /Language servers/ }));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Configure jdtls…" }));
|
||||
expect(run).toHaveBeenCalledWith("jdtls");
|
||||
expect(screen.queryByRole("button", { name: "Configure jdtls…" })).toBeNull();
|
||||
off();
|
||||
});
|
||||
|
||||
it("keeps Restart for other failures", () => {
|
||||
useServers.setState({ servers: new Map([[1 as never, server("crashed", "exit code 1")]]) });
|
||||
render(<ServerStatus />);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/** Status bar widget listing language servers, with a popup to restart them. */
|
||||
/** Status bar widget listing language servers, with a popup to restart or configure them. */
|
||||
import { useMemo, useRef, useState } from "react";
|
||||
import clsx from "clsx";
|
||||
import { getAction, executeAction } from "@/platform/actions";
|
||||
@@ -18,6 +18,7 @@ export function ServerStatus() {
|
||||
const summary = serversSummary(servers);
|
||||
// features/tools owns installing; without it, fall back to the manual hint text.
|
||||
const canInstall = !!getAction("tools.install");
|
||||
const canConfigure = !!getAction("tools.languageServers");
|
||||
if (!summary) return null;
|
||||
return (
|
||||
<>
|
||||
@@ -92,6 +93,17 @@ export function ServerStatus() {
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
{canConfigure && (
|
||||
<IconButton
|
||||
icon="settings"
|
||||
size="small"
|
||||
title={tx`Configure ${serverLabel(s)}…`}
|
||||
onClick={() => {
|
||||
setOpen(false);
|
||||
void executeAction("tools.languageServers", s.name);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
{(s.languages.length > 0 || s.root) && (
|
||||
<div className={styles.meta}>
|
||||
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
type RunExecutorContribution,
|
||||
} from "@/workbench/contributions";
|
||||
import { coverageSupports, formatPercent } from "./model";
|
||||
import { addSuite } from "./store";
|
||||
import { addSuite, captureCoverageProject } from "./store";
|
||||
import { tx } from "@/platform/i18n";
|
||||
|
||||
const errorText = (e: unknown) => (e instanceof Error ? e.message : String(e));
|
||||
@@ -69,7 +69,13 @@ async function prepare(config: RunConfig): Promise<ExecutorLaunch | null> {
|
||||
notifications().notify({ group: "run", level: "warning", title: "Coverage needs the desktop app" });
|
||||
return null;
|
||||
}
|
||||
const plan = await call(commands.coveragePrepare(config));
|
||||
const project = captureCoverageProject();
|
||||
if (!project) return null;
|
||||
const plan = await call(commands.coveragePrepare(config)).catch((e: unknown) => {
|
||||
if (project.isCurrent()) throw e;
|
||||
return null;
|
||||
});
|
||||
if (!plan || !project.isCurrent()) return null;
|
||||
if (plan.status === "unsupported") {
|
||||
notifications().notify({
|
||||
group: "run",
|
||||
@@ -88,10 +94,11 @@ async function prepare(config: RunConfig): Promise<ExecutorLaunch | null> {
|
||||
return {
|
||||
launch: plan.launch,
|
||||
finished: ({ stopped }) => {
|
||||
if (stopped) return;
|
||||
if (stopped || !project.isCurrent()) return;
|
||||
void (async () => {
|
||||
try {
|
||||
const data = await call(commands.coverageCollect(report));
|
||||
if (!project.isCurrent()) return;
|
||||
const suite = addSuite(config.name, data);
|
||||
const totals = data.files.reduce((a, f) => [a[0]! + f.linesCovered, a[1]! + f.linesTotal], [0, 0]);
|
||||
try {
|
||||
@@ -106,6 +113,7 @@ async function prepare(config: RunConfig): Promise<ExecutorLaunch | null> {
|
||||
title: `Coverage of '${suite.name}': ${formatPercent(totals[0]!, totals[1]!)} lines`,
|
||||
});
|
||||
} catch (e) {
|
||||
if (!project.isCurrent()) return;
|
||||
notifications().notify({
|
||||
group: "run",
|
||||
level: "error",
|
||||
|
||||
@@ -10,7 +10,7 @@ import { registerOverlay, registerRunExecutor, registerToolWindow, toolWindowSer
|
||||
import { CoverageHeaderActions, CoverageTabs, CoverageView } from "./CoverageView";
|
||||
import { coverageExecutor } from "./executor";
|
||||
import { coverageGutter } from "./gutter";
|
||||
import { ManageReportsOverlay, importReport, openManageReports } from "./reports";
|
||||
import { ManageReportsOverlay, closeManageReports, importReport, openManageReports } from "./reports";
|
||||
import { resetCoverage, setCoverageVisible, syncCoverageViews, useCoverage } from "./store";
|
||||
|
||||
export function activate(): () => void {
|
||||
@@ -96,11 +96,15 @@ export function activate(): () => void {
|
||||
},
|
||||
]),
|
||||
useProject.subscribe((s, prev) => {
|
||||
if (s.project?.root !== prev.project?.root) resetCoverage();
|
||||
if (s.project?.root !== prev.project?.root) {
|
||||
resetCoverage();
|
||||
closeManageReports();
|
||||
}
|
||||
}),
|
||||
];
|
||||
return () => {
|
||||
disposers.reverse().forEach((d) => d());
|
||||
closeManageReports();
|
||||
if (useCoverage.getState().suites.length) resetCoverage();
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
import { afterEach, beforeEach, expect, it, vi } from "vitest";
|
||||
import type { CoveragePrepared, CoverageSuite, RunConfig } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { coverageExecutor } from "./executor";
|
||||
import { importReport } from "./reports";
|
||||
import { importedReports, resetCoverage, useCoverage } from "./store";
|
||||
|
||||
const backend = vi.hoisted(() => ({
|
||||
coverageImport: vi.fn(),
|
||||
coveragePrepare: vi.fn(),
|
||||
coverageCollect: vi.fn(),
|
||||
open: vi.fn(),
|
||||
show: vi.fn(),
|
||||
notify: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("@/platform/ipc")>();
|
||||
return {
|
||||
...actual,
|
||||
isTauri: () => true,
|
||||
commands: {
|
||||
...actual.commands,
|
||||
coverageImport: backend.coverageImport,
|
||||
coveragePrepare: backend.coveragePrepare,
|
||||
coverageCollect: backend.coverageCollect,
|
||||
},
|
||||
};
|
||||
});
|
||||
vi.mock("@/platform/dialog", () => ({ open: backend.open }));
|
||||
vi.mock("@/workbench/contributions", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@/workbench/contributions")>()),
|
||||
notifications: () => ({ notify: backend.notify }),
|
||||
toolWindowService: () => ({ show: backend.show }),
|
||||
}));
|
||||
|
||||
const origin = "/project-a";
|
||||
const next = "/project-b";
|
||||
const report = `${origin}/lcov.info`;
|
||||
const data: CoverageSuite = {
|
||||
runner: "lcov",
|
||||
hasBranches: false,
|
||||
files: [
|
||||
{ path: `${origin}/src/a.ts`, lines: [], linesCovered: 1, linesTotal: 2, branchesCovered: 0, branchesTotal: 0 },
|
||||
],
|
||||
};
|
||||
const config: RunConfig = {
|
||||
id: "run-a",
|
||||
kind: "shell",
|
||||
name: "Run A",
|
||||
command: "go",
|
||||
args: ["test"],
|
||||
cwd: null,
|
||||
env: {},
|
||||
detected: false,
|
||||
isTest: true,
|
||||
debugAdapter: null,
|
||||
};
|
||||
const plan: CoveragePrepared = {
|
||||
status: "ready",
|
||||
runner: "lcov",
|
||||
launch: config,
|
||||
report: { kind: "lcov", runner: "lcov", path: report, base: origin },
|
||||
};
|
||||
const ok = <T>(value: T) => ({ status: "ok" as const, data: value });
|
||||
const switchTo = (root: string) => useProject.setState({ project: { root } as never });
|
||||
function pending<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
const promise = new Promise<T>((done) => {
|
||||
resolve = done;
|
||||
});
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
localStorage.clear();
|
||||
resetCoverage();
|
||||
switchTo(origin);
|
||||
});
|
||||
afterEach(() => {
|
||||
useProject.setState({ project: null, opening: false, openingPath: null });
|
||||
resetCoverage();
|
||||
});
|
||||
|
||||
it("remembers a late coverage import only in the requesting project", async () => {
|
||||
const response = pending<ReturnType<typeof ok<CoverageSuite>>>();
|
||||
backend.coverageImport.mockReturnValueOnce(response.promise).mockResolvedValueOnce(ok(data));
|
||||
const importing = importReport(report);
|
||||
expect(backend.coverageImport).toHaveBeenCalledWith(report);
|
||||
|
||||
switchTo(next);
|
||||
response.resolve(ok(data));
|
||||
await importing;
|
||||
expect(useCoverage.getState().suites).toEqual([]);
|
||||
expect(importedReports()).toEqual([]);
|
||||
expect(importedReports(origin)).toEqual([{ path: report, name: "lcov.info", importedAt: expect.any(Number) }]);
|
||||
expect(backend.show).not.toHaveBeenCalled();
|
||||
expect(backend.notify).not.toHaveBeenCalled();
|
||||
|
||||
switchTo(origin);
|
||||
const suite = await importReport(importedReports()[0]!.path);
|
||||
expect(useCoverage.getState().suites).toEqual([suite]);
|
||||
expect(suite?.data).toEqual(data);
|
||||
expect(backend.show).toHaveBeenCalledWith("coverage");
|
||||
});
|
||||
|
||||
it.each([
|
||||
["while the next project opens", () => useProject.setState({ opening: true, openingPath: next })],
|
||||
["after the next project opens", () => switchTo(next)],
|
||||
])("abandons a report picked %s", async (_transition, changeProject) => {
|
||||
const picker = pending<string>();
|
||||
backend.open.mockReturnValue(picker.promise);
|
||||
backend.coverageImport.mockResolvedValue(ok(data));
|
||||
const importing = importReport();
|
||||
await vi.waitFor(() => expect(backend.open).toHaveBeenCalledOnce());
|
||||
changeProject();
|
||||
picker.resolve(report);
|
||||
await expect(importing).resolves.toBeNull();
|
||||
expect(backend.coverageImport).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not launch coverage after leaving the project during preparation", async () => {
|
||||
const response = pending<ReturnType<typeof ok<CoveragePrepared>>>();
|
||||
backend.coveragePrepare.mockReturnValue(response.promise);
|
||||
const preparing = coverageExecutor.prepare(config);
|
||||
switchTo(next);
|
||||
response.resolve(ok(plan));
|
||||
await expect(preparing).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it("does not show a collected run after leaving its project", async () => {
|
||||
const response = pending<ReturnType<typeof ok<CoverageSuite>>>();
|
||||
backend.coveragePrepare.mockResolvedValue(ok(plan));
|
||||
backend.coverageCollect.mockReturnValue(response.promise);
|
||||
const run = await coverageExecutor.prepare(config);
|
||||
expect(run).not.toBeNull();
|
||||
run!.finished({ stopped: false, exitCode: 0 });
|
||||
expect(backend.coverageCollect).toHaveBeenCalledWith(plan.report);
|
||||
|
||||
switchTo(next);
|
||||
response.resolve(ok(data));
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
expect(useCoverage.getState().suites).toEqual([]);
|
||||
expect(backend.show).not.toHaveBeenCalled();
|
||||
expect(backend.notify).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -12,6 +12,7 @@ import { notifications, toolWindowService } from "@/workbench/contributions";
|
||||
import { formatPercent } from "./model";
|
||||
import {
|
||||
addSuite,
|
||||
captureCoverageProject,
|
||||
closeSuite,
|
||||
forgetImport,
|
||||
importedReports,
|
||||
@@ -49,12 +50,16 @@ export async function importReport(path?: string): Promise<Suite | null> {
|
||||
notifications().notify({ group: "run", level: "warning", title: "Importing coverage needs the desktop app" });
|
||||
return null;
|
||||
}
|
||||
const project = captureCoverageProject();
|
||||
if (!project) return null;
|
||||
const file = path ?? (await pickReport());
|
||||
if (!file) return null;
|
||||
if (!file || !project.isCurrent()) return null;
|
||||
try {
|
||||
const data = await call(commands.coverageImport(file));
|
||||
const suite = addSuite(basename(file), data, file);
|
||||
rememberImport({ path: file, name: suite.name, importedAt: suite.createdAt });
|
||||
const name = basename(file);
|
||||
const suite = project.isCurrent() ? addSuite(name, data, file) : null;
|
||||
rememberImport(project.root, { path: file, name, importedAt: suite?.createdAt ?? Date.now() });
|
||||
if (!suite) return null;
|
||||
try {
|
||||
toolWindowService().show("coverage");
|
||||
} catch {
|
||||
@@ -70,6 +75,7 @@ export async function importReport(path?: string): Promise<Suite | null> {
|
||||
});
|
||||
return suite;
|
||||
} catch (e) {
|
||||
if (!project.isCurrent()) return null;
|
||||
notifications().notify({
|
||||
group: "run",
|
||||
level: "error",
|
||||
@@ -84,10 +90,11 @@ export async function importReport(path?: string): Promise<Suite | null> {
|
||||
const useManageDialog = create<{ open: boolean }>(() => ({ open: false }));
|
||||
|
||||
export const openManageReports = () => useManageDialog.setState({ open: true });
|
||||
export const closeManageReports = () => useManageDialog.setState({ open: false });
|
||||
|
||||
export function ManageReportsOverlay() {
|
||||
const open = useManageDialog((s) => s.open);
|
||||
return open ? <ManageReportsDialog onClose={() => useManageDialog.setState({ open: false })} /> : null;
|
||||
return open ? <ManageReportsDialog onClose={closeManageReports} /> : null;
|
||||
}
|
||||
|
||||
function ManageReportsDialog({ onClose }: { onClose: () => void }) {
|
||||
|
||||
@@ -33,6 +33,19 @@ interface CoverageState {
|
||||
|
||||
export const useCoverage = create<CoverageState>(() => ({ suites: [], activeId: null, visible: false }));
|
||||
|
||||
export function captureCoverageProject() {
|
||||
const { project, opening } = useProject.getState();
|
||||
if (!project || opening) return null;
|
||||
const root = project.root;
|
||||
return {
|
||||
root,
|
||||
isCurrent: () => {
|
||||
const current = useProject.getState();
|
||||
return !current.opening && current.project?.root === root;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
let seq = 0;
|
||||
|
||||
export function activeSuite(s: CoverageState = useCoverage.getState()): Suite | null {
|
||||
@@ -142,9 +155,8 @@ function saveImported(root: string, reports: ImportedReport[]) {
|
||||
}
|
||||
}
|
||||
|
||||
export function rememberImport(report: ImportedReport) {
|
||||
const root = useProject.getState().project?.root;
|
||||
if (root) saveImported(root, [report, ...importedReports(root).filter((r) => r.path !== report.path)]);
|
||||
export function rememberImport(root: string, report: ImportedReport) {
|
||||
saveImported(root, [report, ...importedReports(root).filter((r) => r.path !== report.path)]);
|
||||
}
|
||||
|
||||
export function forgetImport(path: string) {
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { act, cleanup, fireEvent, render, screen, within } from "@testing-library/react";
|
||||
import { provideEditorService } from "@/workbench/contributions";
|
||||
import { addBreakpoint, useBreakpoints } from "../breakpoints/store";
|
||||
import { DebuggerOverlays } from "../ui/Overlays";
|
||||
import { useOverlays } from "../ui/popoverStore";
|
||||
|
||||
const openFile = vi.fn(async () => undefined);
|
||||
provideEditorService({ openFile } as never);
|
||||
|
||||
const path = "/p/main.py";
|
||||
|
||||
describe("the Breakpoints dialog", () => {
|
||||
beforeEach(() => {
|
||||
openFile.mockClear();
|
||||
useBreakpoints.setState({ byFile: {}, status: {}, muted: false });
|
||||
const first = addBreakpoint(path, 2, { condition: "value == 2" });
|
||||
addBreakpoint(path, 6);
|
||||
useOverlays.setState({ breakpoints: { id: first.id } } as never);
|
||||
});
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
act(() => useOverlays.setState({ breakpoints: null } as never));
|
||||
});
|
||||
|
||||
const dialog = () => screen.getByRole("dialog", { name: "Breakpoints" });
|
||||
const row = (name: string) => within(within(dialog()).getByLabelText("All breakpoints")).getByText(name);
|
||||
const condition = () => within(dialog()).getByLabelText("Condition") as HTMLInputElement;
|
||||
/** A row's mouse click as the list sees it: mousedown selects, click (with its count) activates. */
|
||||
const clickRow = (name: string, detail: number) => {
|
||||
fireEvent.mouseDown(row(name), { button: 0 });
|
||||
fireEvent.click(row(name), { detail });
|
||||
};
|
||||
const breakpointAt = (line: number) => useBreakpoints.getState().byFile[path]!.find((b) => b.line === line)!;
|
||||
|
||||
it("selects a breakpoint on click and goes to its source on double-click", () => {
|
||||
render(<DebuggerOverlays />);
|
||||
clickRow("main.py:7", 1);
|
||||
expect(openFile).not.toHaveBeenCalled();
|
||||
// Its details show beside the list.
|
||||
expect(within(dialog()).getAllByText("main.py:7")).toHaveLength(2);
|
||||
clickRow("main.py:3", 2);
|
||||
expect(openFile).toHaveBeenCalledWith(path, { selection: { line: 2, col: 0 } });
|
||||
});
|
||||
|
||||
it("saves the condition being typed when the dialog closes or another breakpoint is shown", () => {
|
||||
render(<DebuggerOverlays />);
|
||||
fireEvent.change(condition(), { target: { value: "value == 1" } });
|
||||
fireEvent.click(within(dialog()).getByRole("button", { name: "Done" }));
|
||||
expect(breakpointAt(2).condition).toBe("value == 1");
|
||||
|
||||
act(() => useOverlays.setState({ breakpoints: { id: breakpointAt(2).id } } as never));
|
||||
fireEvent.change(condition(), { target: { value: "value == 3" } });
|
||||
clickRow("main.py:7", 1);
|
||||
expect(breakpointAt(2).condition).toBe("value == 3");
|
||||
});
|
||||
});
|
||||
@@ -179,12 +179,19 @@ function BreakpointFields({
|
||||
const commitText = () => {
|
||||
const d = draft.current;
|
||||
const cond = d.condition.trim() || null;
|
||||
if (cond) pushHistory("condition", cond);
|
||||
updateBreakpoint(path, bp.id, {
|
||||
const changes = {
|
||||
condition: cond,
|
||||
hitCondition: d.hitCondition.trim() || null,
|
||||
logMessage: d.logEval ? d.logMessage.trim() || null : null,
|
||||
});
|
||||
};
|
||||
if (
|
||||
changes.condition === (bp.condition ?? null) &&
|
||||
changes.hitCondition === (bp.hitCondition ?? null) &&
|
||||
changes.logMessage === (bp.logMessage ?? null)
|
||||
)
|
||||
return;
|
||||
if (cond) pushHistory("condition", cond);
|
||||
updateBreakpoint(path, bp.id, changes);
|
||||
};
|
||||
useEffect(() => {
|
||||
if (!commitRef) return;
|
||||
@@ -396,9 +403,13 @@ function BreakpointsDialog() {
|
||||
}, [byFile, methods, fields]);
|
||||
const items = rows.filter((r) => r.type !== "section");
|
||||
const [selected, setSelected] = useState<string | null>(null);
|
||||
// The shown breakpoint's typed fields, saved before it is closed or another one is shown:
|
||||
// Enter on Done and a click on a row don't blur them.
|
||||
const commitRef = useRef<(() => void) | null>(null);
|
||||
const open = !!state;
|
||||
const current = items.find((r) => r.key === (selected ?? state?.id)) ?? items[0];
|
||||
const close = () => {
|
||||
commitRef.current?.();
|
||||
setSelected(null);
|
||||
useOverlays.setState({ breakpoints: null });
|
||||
};
|
||||
@@ -448,8 +459,14 @@ function BreakpointsDialog() {
|
||||
isSection={(r) => r.type === "section"}
|
||||
renderSection={(r) => <div className={styles.exceptionAdapter}>{r.type === "section" ? r.label : ""}</div>}
|
||||
activeIndex={current ? rows.indexOf(current) : -1}
|
||||
onActiveChange={(i) => setSelected(rows[i]?.key ?? null)}
|
||||
onActivate={(r) => goTo(r)}
|
||||
onActiveChange={(i) => {
|
||||
commitRef.current?.();
|
||||
setSelected(rows[i]?.key ?? null);
|
||||
}}
|
||||
// A click selects; double-click or Enter goes to the source.
|
||||
onActivate={(r, _i, e) => {
|
||||
if (e.type === "keydown" || e.detail > 1) goTo(r);
|
||||
}}
|
||||
aria-label="All breakpoints"
|
||||
className={styles.bpList}
|
||||
empty={
|
||||
@@ -522,9 +539,9 @@ function BreakpointsDialog() {
|
||||
</div>
|
||||
<div className={styles.bpDetail}>
|
||||
{current?.type === "line" ? (
|
||||
<BreakpointDetail key={current.key} row={current} onGo={() => goTo(current)} />
|
||||
<BreakpointDetail key={current.key} row={current} onGo={() => goTo(current)} commitRef={commitRef} />
|
||||
) : current?.type === "special" ? (
|
||||
<SpecialDetail key={current.key} bp={current.bp} onGo={() => goTo(current)} />
|
||||
<SpecialDetail key={current.key} bp={current.bp} onGo={() => goTo(current)} commitRef={commitRef} />
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
@@ -579,7 +596,15 @@ function ExceptionBreakpoints({ open }: { open: boolean }) {
|
||||
);
|
||||
}
|
||||
|
||||
function BreakpointDetail({ row, onGo }: { row: BpRow; onGo: () => void }) {
|
||||
function BreakpointDetail({
|
||||
row,
|
||||
onGo,
|
||||
commitRef,
|
||||
}: {
|
||||
row: BpRow;
|
||||
onGo: () => void;
|
||||
commitRef: MutableRefObject<(() => void) | null>;
|
||||
}) {
|
||||
const { path, bp } = row;
|
||||
const st = useBreakpoints((s) => s.status[bp.id]);
|
||||
return (
|
||||
@@ -597,7 +622,7 @@ function BreakpointDetail({ row, onGo }: { row: BpRow; onGo: () => void }) {
|
||||
</Button>
|
||||
</div>
|
||||
{st && <div className={styles.statusLine}>{st.verified ? tx("Verified") : (st.message ?? "Not verified")}</div>}
|
||||
<BreakpointFields path={path} bp={bp} />
|
||||
<BreakpointFields path={path} bp={bp} commitRef={commitRef} />
|
||||
<Checkbox
|
||||
checked={!!bp.temporary}
|
||||
onChange={(temporary) => updateBreakpoint(path, bp.id, { temporary })}
|
||||
@@ -607,11 +632,34 @@ function BreakpointDetail({ row, onGo }: { row: BpRow; onGo: () => void }) {
|
||||
);
|
||||
}
|
||||
|
||||
function SpecialDetail({ bp, onGo }: { bp: SpecialBreakpoint; onGo: () => void }) {
|
||||
function SpecialDetail({
|
||||
bp,
|
||||
onGo,
|
||||
commitRef,
|
||||
}: {
|
||||
bp: SpecialBreakpoint;
|
||||
onGo: () => void;
|
||||
commitRef: MutableRefObject<(() => void) | null>;
|
||||
}) {
|
||||
const st = useSpecialBreakpoints((s) => s.status[bp.id]);
|
||||
const [name, setName] = useState(bp.kind === "method" ? bp.name : bp.label);
|
||||
const [condition, setCondition] = useState(bp.condition ?? "");
|
||||
const [hitCondition, setHitCondition] = useState(bp.hitCondition ?? "");
|
||||
const draft = useRef({ name, condition, hitCondition });
|
||||
useEffect(() => {
|
||||
draft.current = { name, condition, hitCondition };
|
||||
commitRef.current = () => {
|
||||
const d = draft.current;
|
||||
updateSpecial(bp.id, {
|
||||
name: d.name.trim(),
|
||||
condition: d.condition.trim() || null,
|
||||
hitCondition: d.hitCondition.trim() || null,
|
||||
});
|
||||
};
|
||||
return () => {
|
||||
commitRef.current = null;
|
||||
};
|
||||
});
|
||||
return (
|
||||
<div className={styles.detail}>
|
||||
<div className={styles.bpTitle}>
|
||||
|
||||
@@ -1,6 +1,16 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { cancelDotnet, discoveredTests, packageList, selectDotnet, resetDotnet, useDotnet } from "./store";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
buildDotnet,
|
||||
cancelDotnet,
|
||||
discoveredTests,
|
||||
packageList,
|
||||
reloadDotnet,
|
||||
resetDotnet,
|
||||
selectDotnet,
|
||||
useDotnet,
|
||||
} from "./store";
|
||||
import * as platform from "@/platform/dotnet";
|
||||
import { useProject } from "@/platform/project";
|
||||
|
||||
afterEach(() => {
|
||||
resetDotnet();
|
||||
@@ -59,6 +69,93 @@ it("ignores an evaluation completed after cancellation", async () => {
|
||||
expect(useDotnet.getState().error).toBe("");
|
||||
});
|
||||
|
||||
describe("reloading a .NET workspace", () => {
|
||||
const path = "/repo/Test.csproj";
|
||||
const project: platform.DotnetProject = {
|
||||
path,
|
||||
name: "Test",
|
||||
frameworks: ["net8.0", "net9.0"],
|
||||
configurations: ["Debug", "Release"],
|
||||
references: [],
|
||||
packages: [],
|
||||
test: true,
|
||||
runner: "vstest",
|
||||
adapter: "mstest",
|
||||
trx: false,
|
||||
};
|
||||
const previousProject = useProject.getState().project;
|
||||
|
||||
beforeEach(() => {
|
||||
useProject.setState({ project: { root: "/repo" } as NonNullable<typeof previousProject> });
|
||||
useDotnet.setState({ selected: path, configuration: "Release", framework: "net9.0" });
|
||||
});
|
||||
|
||||
afterEach(() => useProject.setState({ project: previousProject }));
|
||||
|
||||
it("preserves the project, configuration and framework and evaluates that selection", async () => {
|
||||
const first = { ...project, path: "/repo/A.csproj" };
|
||||
const release = { ...project, frameworks: ["net10.0", "net9.0"] };
|
||||
const selected = { ...release, packages: [{ id: "ReleaseOnly", version: "1.0" }] };
|
||||
vi.spyOn(platform, "dotnetWorkspace").mockResolvedValue({ projects: [first, project], solutions: [] });
|
||||
const evaluate = vi
|
||||
.spyOn(platform, "evaluateProject")
|
||||
.mockImplementation(async (_path, _config, framework) => (framework === "net9.0" ? selected : release));
|
||||
const command = vi.spyOn(platform, "dotnet").mockResolvedValue("");
|
||||
|
||||
await reloadDotnet();
|
||||
|
||||
expect(useDotnet.getState()).toMatchObject({
|
||||
selected: path,
|
||||
configuration: "Release",
|
||||
framework: "net9.0",
|
||||
model: { projects: [first, selected] },
|
||||
});
|
||||
expect(evaluate).toHaveBeenLastCalledWith(path, "Release", "net9.0", expect.any(AbortSignal));
|
||||
await buildDotnet("build");
|
||||
expect(command).toHaveBeenCalledWith(
|
||||
["build", path, "--configuration", "Release", "--framework", "net9.0"],
|
||||
"/repo",
|
||||
expect.any(AbortSignal),
|
||||
);
|
||||
});
|
||||
|
||||
it("uses a supported configuration and framework when the saved choices were removed", async () => {
|
||||
const updated = { ...project, configurations: ["Profile"], frameworks: ["net10.0"] };
|
||||
vi.spyOn(platform, "dotnetWorkspace").mockResolvedValue({ projects: [updated], solutions: [] });
|
||||
const evaluate = vi.spyOn(platform, "evaluateProject").mockResolvedValue(updated);
|
||||
|
||||
await reloadDotnet();
|
||||
|
||||
expect(useDotnet.getState()).toMatchObject({ selected: path, configuration: "Profile", framework: "net10.0" });
|
||||
expect(evaluate).toHaveBeenCalledWith(path, "Profile", "", expect.any(AbortSignal));
|
||||
});
|
||||
|
||||
it("keeps a supported configuration when its previously selected framework is removed", async () => {
|
||||
const release = { ...project, frameworks: ["net10.0"] };
|
||||
vi.spyOn(platform, "dotnetWorkspace").mockResolvedValue({ projects: [project], solutions: [] });
|
||||
vi.spyOn(platform, "evaluateProject").mockResolvedValue(release);
|
||||
|
||||
await reloadDotnet();
|
||||
|
||||
expect(useDotnet.getState()).toMatchObject({ selected: path, configuration: "Release", framework: "net10.0" });
|
||||
});
|
||||
|
||||
it("uses the remaining project's defaults when the selected project is removed", async () => {
|
||||
const remaining = { ...project, path: "/repo/Remaining.csproj" };
|
||||
vi.spyOn(platform, "dotnetWorkspace").mockResolvedValue({ projects: [remaining], solutions: [] });
|
||||
const evaluate = vi.spyOn(platform, "evaluateProject");
|
||||
|
||||
await reloadDotnet();
|
||||
|
||||
expect(useDotnet.getState()).toMatchObject({
|
||||
selected: remaining.path,
|
||||
configuration: "Debug",
|
||||
framework: "net8.0",
|
||||
});
|
||||
expect(evaluate).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("real dotnet discovery output", () => {
|
||||
it.each([
|
||||
"The following Tests are available:\n Passes\n Parameterized (1)\n\nProcess finished with exit code 0",
|
||||
|
||||
@@ -80,15 +80,31 @@ export function cancelDotnet() {
|
||||
export function reloadDotnet() {
|
||||
const root = useProject.getState().project?.root;
|
||||
if (!root) return;
|
||||
const old = useDotnet.getState();
|
||||
return task(async (signal) => {
|
||||
const model = await dotnetWorkspace(root, signal);
|
||||
const old = useDotnet.getState();
|
||||
const project = model.projects.find((p) => p.path === old.selected) ?? model.projects[0];
|
||||
let project = model.projects.find((p) => p.path === old.selected) ?? model.projects[0];
|
||||
const sameProject = project?.path === old.selected;
|
||||
const configurations = project?.configurations ?? [];
|
||||
const defaultConfiguration = configurations.includes(initial.configuration)
|
||||
? initial.configuration
|
||||
: (configurations[0] ?? initial.configuration);
|
||||
const configuration =
|
||||
sameProject && configurations.includes(old.configuration) ? old.configuration : defaultConfiguration;
|
||||
|
||||
// The workspace scan evaluates Debug and the first framework for each project.
|
||||
if (project && configuration !== initial.configuration)
|
||||
project = await evaluateProject(project.path, configuration, "", signal);
|
||||
const framework =
|
||||
sameProject && project?.frameworks.includes(old.framework) ? old.framework : (project?.frameworks[0] ?? "");
|
||||
if (project && framework && framework !== project.frameworks[0])
|
||||
project = await evaluateProject(project.path, configuration, framework, signal);
|
||||
|
||||
return {
|
||||
model,
|
||||
model: { ...model, projects: model.projects.map((item) => (item.path === project?.path ? project : item)) },
|
||||
selected: project?.path ?? "",
|
||||
configuration: "Debug",
|
||||
framework: project?.frameworks[0] ?? "",
|
||||
configuration,
|
||||
framework,
|
||||
packages: [],
|
||||
found: [],
|
||||
tests: [],
|
||||
|
||||
@@ -26,7 +26,7 @@ import {
|
||||
setPullRequestData,
|
||||
updateTimeline,
|
||||
} from "./pullRequest";
|
||||
import { requireConnection } from "./repository";
|
||||
import { requireConnection, useGhRepository, type GHConnection } from "./repository";
|
||||
|
||||
const settle = (ps: Array<Promise<unknown>>) => Promise.allSettled(ps).then(() => undefined);
|
||||
|
||||
@@ -175,18 +175,26 @@ export async function createReview(
|
||||
return review;
|
||||
}
|
||||
|
||||
/** Submits the pending review `reviewId`. */
|
||||
export async function submitReview(number: number, reviewId: string, event: GHPullRequestReviewEvent, body?: string) {
|
||||
await api.submitReview(reviewId, event, body || null);
|
||||
await refreshReview(number);
|
||||
await reloadPullRequestData(number, "mergeability").catch(() => undefined);
|
||||
}
|
||||
|
||||
/** Submit Review popup: submits the pending review, or creates a submitted one. */
|
||||
export async function submitOrCreateReview(number: number, event: GHPullRequestReviewEvent, body: string) {
|
||||
/** Submits or creates a review; returns false if the connection changed before it could send. */
|
||||
export async function submitOrCreateReview(
|
||||
number: number,
|
||||
event: GHPullRequestReviewEvent,
|
||||
body: string,
|
||||
connection: GHConnection,
|
||||
): Promise<boolean> {
|
||||
const isCurrent = () => useGhRepository.getState().connection === connection;
|
||||
const pending = await loadPullRequestData(number, "pendingReview");
|
||||
if (pending) await submitReview(number, pending.id, event, body);
|
||||
else await createReview(number, { event, body: body || undefined });
|
||||
if (!isCurrent()) return false;
|
||||
if (pending) {
|
||||
await api.submitReview(pending.id, event, body || null);
|
||||
} else {
|
||||
const id = await pullRequestId(number);
|
||||
if (!isCurrent()) return false;
|
||||
await api.createReview({ pullRequestId: id, event, body: body || undefined });
|
||||
}
|
||||
if (isCurrent()) await refreshReview(number);
|
||||
if (pending && isCurrent()) await reloadPullRequestData(number, "mergeability").catch(() => undefined);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Discards a pending review with its comments. */
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
* Request Changes (not for the author) and Comment. Shown above the button that opened
|
||||
* it, or centred in the window. 500×200, resizable.
|
||||
*/
|
||||
import { useState, type CSSProperties } from "react";
|
||||
import { useEffect, useState, type CSSProperties } from "react";
|
||||
import { Button, IconButton, Popup, Spinner, T } from "@/ui";
|
||||
import { useTx, tx } from "@/platform/i18n";
|
||||
import { ask } from "@/workbench/messages";
|
||||
@@ -13,40 +13,59 @@ import { errorMessage } from "../api/client";
|
||||
import type { GHPullRequestReviewEvent } from "../api/types";
|
||||
import { deleteReview, submitOrCreateReview } from "../data/operations";
|
||||
import { loadPullRequestData, usePullRequestData } from "../data/pullRequest";
|
||||
import { useGhRepository } from "../data/repository";
|
||||
import { openDialog } from "../ui/dialogs";
|
||||
import { setReviewText, useReviewText } from "./state";
|
||||
import { reviewDraftKey, setReviewText, useReviewText } from "./state";
|
||||
import styles from "./Details.module.css";
|
||||
|
||||
/** Opens the popup for pull request `number`; resolves when it closes. */
|
||||
export function showSubmitReview(number: number, anchor?: Element | null): Promise<unknown> {
|
||||
const draftKey = reviewDraftKey(useGhRepository.getState().connection, number);
|
||||
if (draftKey === null) return Promise.resolve(null);
|
||||
// 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} anchor={at} onClose={() => done(null)} />);
|
||||
return openDialog<true>((done) => (
|
||||
<SubmitReview number={number} draftKey={draftKey} anchor={at} onClose={() => done(null)} />
|
||||
));
|
||||
}
|
||||
|
||||
function SubmitReview(props: { number: number; anchor: Element | { x: number; y: number }; onClose: () => void }) {
|
||||
const { number } = 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[number] ?? "");
|
||||
const text = useReviewText((s) => s.text[draftKey] ?? "");
|
||||
const activeDraftKey = useGhRepository((s) => reviewDraftKey(s.connection, number));
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
useEffect(() => {
|
||||
if (activeDraftKey !== draftKey) onClose();
|
||||
}, [activeDraftKey, draftKey, onClose]);
|
||||
if (activeDraftKey !== draftKey) return null;
|
||||
|
||||
const comments = pending?.commentsCount ?? 0;
|
||||
const hasAnyComment = text.length > 0 || comments > 0;
|
||||
const isAuthor = details?.viewerDidAuthor ?? false;
|
||||
|
||||
const submit = async (event: GHPullRequestReviewEvent) => {
|
||||
const connection = useGhRepository.getState().connection;
|
||||
if (!connection || reviewDraftKey(connection, number) !== draftKey) return;
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
await submitOrCreateReview(number, event, text);
|
||||
setReviewText(number, "");
|
||||
props.onClose();
|
||||
if (await submitOrCreateReview(number, event, text, connection)) {
|
||||
setReviewText(draftKey, "");
|
||||
onClose();
|
||||
}
|
||||
} catch (e) {
|
||||
setError(errorMessage(e));
|
||||
} finally {
|
||||
@@ -54,7 +73,8 @@ function SubmitReview(props: { number: number; anchor: Element | { x: number; y:
|
||||
}
|
||||
};
|
||||
const discard = async () => {
|
||||
if (!pending) return;
|
||||
const connection = useGhRepository.getState().connection;
|
||||
if (!pending || reviewDraftKey(connection, number) !== draftKey) return;
|
||||
const r = await ask({
|
||||
title: tx("Discard Pending Review"),
|
||||
body: tx("Are you sure you want to delete all pending comments?"),
|
||||
@@ -64,7 +84,7 @@ function SubmitReview(props: { number: number; anchor: Element | { x: number; y:
|
||||
],
|
||||
cancel: false,
|
||||
});
|
||||
if (r.button !== "yes") return;
|
||||
if (r.button !== "yes" || useGhRepository.getState().connection !== connection) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
await deleteReview(number, pending.id);
|
||||
@@ -82,7 +102,7 @@ function SubmitReview(props: { number: number; anchor: Element | { x: number; y:
|
||||
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) props.onClose();
|
||||
if (reason !== "outside" || !busy) onClose();
|
||||
}}
|
||||
role="dialog"
|
||||
aria-label={t("Submit Review")}
|
||||
@@ -100,7 +120,7 @@ function SubmitReview(props: { number: number; anchor: Element | { x: number; y:
|
||||
{pending && comments > 0 && (
|
||||
<IconButton icon="trash" size="small" title="Discard pending comments" disabled={busy} onClick={discard} />
|
||||
)}
|
||||
<IconButton icon="close" size="small" title="Close" onClick={props.onClose} />
|
||||
<IconButton icon="close" size="small" title="Close" onClick={onClose} />
|
||||
</div>
|
||||
<textarea
|
||||
data-autofocus
|
||||
@@ -110,7 +130,7 @@ function SubmitReview(props: { number: number; anchor: Element | { x: number; y:
|
||||
value={text}
|
||||
onChange={(e) => {
|
||||
setError(null);
|
||||
setReviewText(number, e.target.value);
|
||||
setReviewText(draftKey, e.target.value);
|
||||
}}
|
||||
/>
|
||||
{error && (
|
||||
|
||||
@@ -1,12 +1,23 @@
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { cleanup, render, screen } from "@testing-library/react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";
|
||||
import { createRef } from "react";
|
||||
import type { GHPRMergeabilityState, GHPullRequest, GHRepository, GHUser } from "../api/types";
|
||||
import * as api from "../api/requests";
|
||||
import type {
|
||||
GHPRMergeabilityState,
|
||||
GHPullRequest,
|
||||
GHPullRequestPendingReview,
|
||||
GHRepository,
|
||||
GHUser,
|
||||
} from "../api/types";
|
||||
import { reviewersStates } from "../data/model";
|
||||
import { submitOrCreateReview } from "../data/operations";
|
||||
import { clearPullRequests, setPullRequestData } from "../data/pullRequest";
|
||||
import { useGhRepository } from "../data/repository";
|
||||
import { GithubDialogHost } from "../ui/dialogs";
|
||||
import { ReviewActions } from "./ReviewActions";
|
||||
import { useReviewText } from "./state";
|
||||
import { StatusSection } from "./StatusSection";
|
||||
import { showSubmitReview } from "./SubmitReviewPopup";
|
||||
|
||||
const me: GHUser = { __typename: "User", id: "U1", login: "me", url: "", avatarUrl: "", name: null };
|
||||
const bob: GHUser = { __typename: "User", id: "U2", login: "bob", url: "", avatarUrl: "", name: "Bob" };
|
||||
@@ -175,3 +186,112 @@ describe("ReviewActions", () => {
|
||||
expect(screen.getByText("Set Myself as Reviewer")).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Submit Review draft", () => {
|
||||
const editor = () => screen.getByRole<HTMLTextAreaElement>("textbox", { name: "Review comment" });
|
||||
const close = () => fireEvent.click(screen.getByRole("button", { name: "Close" }));
|
||||
|
||||
function open(number: number) {
|
||||
act(() => {
|
||||
setPullRequestData(number, "details", () => pr({ number }));
|
||||
setPullRequestData(number, "pendingReview", () => null);
|
||||
void showSubmitReview(number);
|
||||
});
|
||||
}
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
const promise = new Promise<T>((done) => {
|
||||
resolve = done;
|
||||
});
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
useReviewText.setState({ text: {} });
|
||||
});
|
||||
|
||||
it("restores the draft only for the same repository, account and pull request", () => {
|
||||
const connection = useGhRepository.getState().connection!;
|
||||
render(<GithubDialogHost />);
|
||||
|
||||
open(7);
|
||||
fireEvent.change(editor(), { target: { value: "Draft for org/app #7" } });
|
||||
close();
|
||||
|
||||
open(8);
|
||||
expect(editor().value).toBe("");
|
||||
close();
|
||||
|
||||
act(() => {
|
||||
useGhRepository.setState({
|
||||
connection: {
|
||||
...connection,
|
||||
coordinates: { owner: "org", name: "other" },
|
||||
repository: { ...repository, id: "R2", nameWithOwner: "org/other" },
|
||||
},
|
||||
});
|
||||
});
|
||||
open(7);
|
||||
const otherRepositoryDraft = editor().value;
|
||||
close();
|
||||
|
||||
act(() => useGhRepository.setState({ connection: { ...connection, currentUser: bob } }));
|
||||
open(7);
|
||||
const otherAccountDraft = editor().value;
|
||||
close();
|
||||
|
||||
act(() => useGhRepository.setState({ connection }));
|
||||
open(7);
|
||||
const restoredDraft = editor().value;
|
||||
close();
|
||||
|
||||
expect(otherRepositoryDraft).toBe("");
|
||||
expect(otherAccountDraft).toBe("");
|
||||
expect(restoredDraft).toBe("Draft for org/app #7");
|
||||
});
|
||||
|
||||
it("closes an open review popup when its account changes", () => {
|
||||
const connection = useGhRepository.getState().connection!;
|
||||
render(<GithubDialogHost />);
|
||||
open(7);
|
||||
fireEvent.change(editor(), { target: { value: "Draft for me" } });
|
||||
|
||||
act(() => useGhRepository.setState({ connection: { ...connection, currentUser: bob } }));
|
||||
const remainingEditor = screen.queryByRole("textbox", { name: "Review comment" });
|
||||
if (remainingEditor) close();
|
||||
expect(remainingEditor).toBeNull();
|
||||
});
|
||||
|
||||
it("cancels submission if the account changes during the pull request lookup", async () => {
|
||||
const connection = useGhRepository.getState().connection!;
|
||||
const lookup = deferred<string>();
|
||||
const findPullRequestId = vi.spyOn(api, "findPullRequestId").mockReturnValue(lookup.promise);
|
||||
const createReview = vi.spyOn(api, "createReview").mockRejectedValue(new Error("Unexpected review mutation"));
|
||||
|
||||
const submission = submitOrCreateReview(7, "COMMENT", "Draft for me", connection);
|
||||
await vi.waitFor(() => expect(findPullRequestId).toHaveBeenCalledWith(7));
|
||||
useGhRepository.setState({ connection: { ...connection, currentUser: bob } });
|
||||
lookup.resolve("PR1");
|
||||
|
||||
await expect(submission).resolves.toBe(false);
|
||||
expect(createReview).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("cancels submission if the connection closes during the pending review lookup", async () => {
|
||||
const connection = useGhRepository.getState().connection!;
|
||||
setPullRequestData(8, "details", () => pr({ number: 8 }));
|
||||
const lookup = deferred<GHPullRequestPendingReview>();
|
||||
const findPendingReview = vi.spyOn(api, "findPendingReview").mockReturnValue(lookup.promise);
|
||||
const submitReview = vi.spyOn(api, "submitReview").mockRejectedValue(new Error("Unexpected review mutation"));
|
||||
|
||||
const submission = submitOrCreateReview(8, "COMMENT", "Draft for me", connection);
|
||||
await vi.waitFor(() => expect(findPendingReview).toHaveBeenCalledWith("PR1"));
|
||||
useGhRepository.setState({ connection: null });
|
||||
lookup.resolve({ id: "review-1", commentsCount: 0, state: "PENDING" });
|
||||
|
||||
await expect(submission).resolves.toBe(false);
|
||||
expect(submitReview).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -2,8 +2,7 @@
|
||||
* Client state of the details tab: the changes of single commits (REST `commits/{sha}`,
|
||||
* cached per commit), the changes tree's grouping (`GithubPullRequestsProjectUISettings
|
||||
* .changesGrouping`, kept in local storage) and the Submit Review popup's text, kept per
|
||||
* pull request until the review is submitted (IntelliJ keeps it as the pending review's
|
||||
* comment).
|
||||
* pull request, repository and account until the review is submitted.
|
||||
*/
|
||||
import { useEffect } from "react";
|
||||
import { create } from "zustand";
|
||||
@@ -11,7 +10,7 @@ import { errorMessage } from "../api/client";
|
||||
import { commitChangedFiles } from "../api/requests";
|
||||
import type { GHCommitFile } from "../api/types";
|
||||
import type { Loadable } from "../data/pullRequest";
|
||||
import { useGhRepository } from "../data/repository";
|
||||
import { useGhRepository, type GHConnection } from "../data/repository";
|
||||
|
||||
const useCommitFiles = create<{ bySha: Record<string, Loadable<GHCommitFile[]>> }>(() => ({ bySha: {} }));
|
||||
|
||||
@@ -71,9 +70,13 @@ export function setGroupByDirectory(on: boolean) {
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** The Submit Review popup's text per pull request. */
|
||||
export const useReviewText = create<{ text: Record<number, string> }>(() => ({ text: {} }));
|
||||
/** The Submit Review popup's text by GitHub account, repository and pull request. */
|
||||
export const useReviewText = create<{ text: Record<string, string> }>(() => ({ text: {} }));
|
||||
|
||||
export function setReviewText(number: number, text: string) {
|
||||
useReviewText.setState((s) => ({ text: { ...s.text, [number]: text } }));
|
||||
export function reviewDraftKey(connection: GHConnection | null, number: number): string | null {
|
||||
return connection ? JSON.stringify([connection.currentUser.id, connection.repository.id, number]) : null;
|
||||
}
|
||||
|
||||
export function setReviewText(key: string, text: string) {
|
||||
useReviewText.setState((s) => ({ text: { ...s.text, [key]: text } }));
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
import { beforeEach, expect, it, vi } from "vitest";
|
||||
import type { HttpExchange, HttpRequestBlock } from "@/platform/ipc";
|
||||
import { runAll, runRequest, setEnvironment, useHttpClient } from "./store";
|
||||
|
||||
const backend = vi.hoisted(() => ({
|
||||
httpEnvironments: vi.fn(),
|
||||
httpExecute: vi.fn(),
|
||||
httpRequests: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("@/platform/ipc")>();
|
||||
return { ...actual, commands: { ...actual.commands, ...backend } };
|
||||
});
|
||||
vi.mock("@/workbench/contributions", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@/workbench/contributions")>()),
|
||||
showServiceView: vi.fn(),
|
||||
}));
|
||||
|
||||
const path = "/project/batch.http";
|
||||
const text = "### First\nGET {{baseUrl}}/first\n\n### Second\nGET {{baseUrl}}/second\n";
|
||||
const blocks: HttpRequestBlock[] = [
|
||||
{ index: 0, name: "First", method: "GET", url: "{{baseUrl}}/first", line: 1, startLine: 1, endLine: 2 },
|
||||
{ index: 1, name: "Second", method: "GET", url: "{{baseUrl}}/second", line: 4, startLine: 4, endLine: 4 },
|
||||
];
|
||||
const exchange: HttpExchange = {
|
||||
entry: {
|
||||
id: "test",
|
||||
timeMs: null,
|
||||
name: null,
|
||||
method: "GET",
|
||||
url: "http://127.0.0.1/first",
|
||||
status: 200,
|
||||
totalMs: null,
|
||||
file: path,
|
||||
error: null,
|
||||
},
|
||||
request: { name: null, method: "GET", url: "http://127.0.0.1/first", headers: [], body: null },
|
||||
response: null,
|
||||
};
|
||||
const ok = <T>(data: T) => ({ status: "ok" as const, data });
|
||||
const initial = useHttpClient.getState();
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
useHttpClient.setState(initial);
|
||||
vi.resetAllMocks();
|
||||
backend.httpEnvironments.mockResolvedValue(ok(["A", "B"]));
|
||||
backend.httpExecute.mockResolvedValue(ok(exchange));
|
||||
backend.httpRequests.mockResolvedValue(blocks);
|
||||
});
|
||||
|
||||
it.each(["A", null])("keeps the starting environment %s throughout a batch", async (startingEnvironment) => {
|
||||
useHttpClient.setState({ environments: { [path]: ["A", "B"] } });
|
||||
setEnvironment(path, startingEnvironment);
|
||||
let releaseFirst!: () => void;
|
||||
const holdFirst = new Promise<void>((resolve) => {
|
||||
releaseFirst = resolve;
|
||||
});
|
||||
backend.httpExecute.mockImplementationOnce(async () => {
|
||||
await holdFirst;
|
||||
return ok(exchange);
|
||||
});
|
||||
|
||||
const batch = runAll(path, text);
|
||||
await vi.waitFor(() =>
|
||||
expect(backend.httpExecute).toHaveBeenCalledExactlyOnceWith(expect.any(Number), path, text, 0, startingEnvironment),
|
||||
);
|
||||
setEnvironment(path, "B");
|
||||
releaseFirst();
|
||||
await batch;
|
||||
expect(backend.httpExecute).toHaveBeenNthCalledWith(2, expect.any(Number), path, text, 1, startingEnvironment);
|
||||
|
||||
await runAll(path, text);
|
||||
expect(backend.httpExecute).toHaveBeenNthCalledWith(3, expect.any(Number), path, text, 0, "B");
|
||||
expect(backend.httpExecute).toHaveBeenNthCalledWith(4, expect.any(Number), path, text, 1, "B");
|
||||
await runRequest(path, text, 1);
|
||||
expect(backend.httpExecute).toHaveBeenNthCalledWith(5, expect.any(Number), path, text, 1, "B");
|
||||
});
|
||||
|
||||
it.each(["A", "missing"])("validates the starting choice %s once when environments load", async (choice) => {
|
||||
setEnvironment(path, choice);
|
||||
let finishLoading!: (value: ReturnType<typeof ok<string[]>>) => void;
|
||||
backend.httpEnvironments.mockImplementationOnce(
|
||||
() =>
|
||||
new Promise((resolve) => {
|
||||
finishLoading = resolve;
|
||||
}),
|
||||
);
|
||||
const batch = runAll(path, text);
|
||||
await vi.waitFor(() => expect(backend.httpEnvironments).toHaveBeenCalledExactlyOnceWith(path));
|
||||
setEnvironment(path, "B");
|
||||
finishLoading(ok(["A", "B"]));
|
||||
await batch;
|
||||
const environment = choice === "A" ? "A" : null;
|
||||
expect(backend.httpExecute).toHaveBeenNthCalledWith(1, expect.any(Number), path, text, 0, environment);
|
||||
expect(backend.httpExecute).toHaveBeenNthCalledWith(2, expect.any(Number), path, text, 1, environment);
|
||||
});
|
||||
@@ -86,11 +86,11 @@ export async function loadEnvironments(path: string): Promise<string[]> {
|
||||
}
|
||||
}
|
||||
|
||||
/** The environment a run of `path` uses: the chosen one if it still exists. */
|
||||
export function effectiveEnvironment(path: string | null): string | null {
|
||||
/** The environment a run of `path` uses: the selected one if it still exists. */
|
||||
function effectiveEnvironment(path: string | null, selection?: string | null): string | null {
|
||||
if (!path) return null;
|
||||
const s = useHttpClient.getState();
|
||||
const chosen = s.envByFile[path];
|
||||
const chosen = selection === undefined ? s.envByFile[path] : selection;
|
||||
const available = s.environments[path];
|
||||
if (chosen && (!available || available.includes(chosen))) return chosen;
|
||||
return null;
|
||||
@@ -133,7 +133,12 @@ export function parseRequests(text: string): Promise<HttpRequestBlock[]> {
|
||||
* Sends request `index` of `text` (the buffer of `path`). The response opens
|
||||
* in the HTTP Client tool window. Returns false when cancelled or failed early.
|
||||
*/
|
||||
export async function runRequest(path: string | null, text: string, index: number): Promise<boolean> {
|
||||
export async function runRequest(
|
||||
path: string | null,
|
||||
text: string,
|
||||
index: number,
|
||||
batchEnvironment?: string | null,
|
||||
): Promise<boolean> {
|
||||
const busy = useHttpClient.getState().running;
|
||||
if (busy) void commands.cancelRequest(busy.request);
|
||||
const request = nextRequestId();
|
||||
@@ -149,8 +154,10 @@ export async function runRequest(path: string | null, text: string, index: numbe
|
||||
})
|
||||
.catch(() => {});
|
||||
try {
|
||||
if (path && !useHttpClient.getState().environments[path]) await loadEnvironments(path);
|
||||
const ex = await call(commands.httpExecute(request, path, text, index, effectiveEnvironment(path)));
|
||||
if (batchEnvironment === undefined && path && !useHttpClient.getState().environments[path])
|
||||
await loadEnvironments(path);
|
||||
const env = batchEnvironment === undefined ? effectiveEnvironment(path) : batchEnvironment;
|
||||
const ex = await call(commands.httpExecute(request, path, text, index, env));
|
||||
useHttpClient.setState((s) => ({
|
||||
history: [ex.entry, ...s.history.filter((h) => h.id !== ex.entry.id)],
|
||||
exchanges: { ...s.exchanges, [ex.entry.id]: ex },
|
||||
@@ -208,11 +215,15 @@ export async function openEnvironmentFile(path: string, isPrivate: boolean): Pro
|
||||
}
|
||||
}
|
||||
|
||||
/** Runs every request of the file in order; stops when one is cancelled. */
|
||||
/** Runs every request of the file in order with the starting environment. */
|
||||
export async function runAll(path: string | null, text: string): Promise<void> {
|
||||
const selection = path ? (useHttpClient.getState().envByFile[path] ?? null) : null;
|
||||
const blocks = await parseRequests(text);
|
||||
if (!blocks.length) return;
|
||||
if (path && !useHttpClient.getState().environments[path]) await loadEnvironments(path);
|
||||
const environment = effectiveEnvironment(path, selection);
|
||||
for (const b of blocks) {
|
||||
if (!(await runRequest(path, text, b.index))) return;
|
||||
if (!(await runRequest(path, text, b.index, environment))) return;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -149,19 +149,27 @@ export function activate(): () => void {
|
||||
/** The last complete result: what a refresh shows for ecosystems that haven't reported yet. */
|
||||
let settled: LibraryGroup[] = [];
|
||||
let request: RequestId | undefined;
|
||||
/** The project whose libraries are shown (and `settled`). */
|
||||
let shownFor: string | null = null;
|
||||
const clear = () => {
|
||||
disposeRoot();
|
||||
disposeReadOnly();
|
||||
disposeRoot = disposeReadOnly = () => {};
|
||||
shown = "";
|
||||
settled = [];
|
||||
shownFor = null;
|
||||
};
|
||||
const refresh = () => {
|
||||
const id = ++seq;
|
||||
if (request !== undefined) void commands.cancelRequest(request).catch(() => {});
|
||||
request = undefined;
|
||||
if (!useProject.getState().project || useProject.getState().project?.trusted === false || !isTauri())
|
||||
return clear();
|
||||
const project = useProject.getState().project;
|
||||
if (!project || project.trusted === false || !isTauri()) return clear();
|
||||
// Another project's libraries must not show (or fill in) while this one's are discovered.
|
||||
if (shownFor !== project.root) {
|
||||
clear();
|
||||
shownFor = project.root;
|
||||
}
|
||||
let collected: LibraryGroup[] = [];
|
||||
const show = (groups: LibraryGroup[]) => {
|
||||
if (id !== seq) return;
|
||||
|
||||
@@ -4,6 +4,8 @@ import type { LibraryGroup } from "@/bindings";
|
||||
const results: LibraryGroup[][] = [];
|
||||
/** Batches the next request streams before it answers. */
|
||||
const streamed: LibraryGroup[][] = [];
|
||||
/** The next request never answers (discovery still running). */
|
||||
let hang = false;
|
||||
|
||||
vi.mock("@tauri-apps/api/core", () => ({
|
||||
Channel: class {
|
||||
@@ -19,6 +21,7 @@ vi.mock("@/bindings", () => ({
|
||||
vi.mock("@/platform/ipc", () => ({
|
||||
call: (request: [string, { onmessage: (v: unknown) => void }]) => {
|
||||
for (const batch of streamed.splice(0)) request[1].onmessage(batch);
|
||||
if (hang) return new Promise(() => {});
|
||||
return Promise.resolve(results.shift() ?? []);
|
||||
},
|
||||
isCancelled: () => false,
|
||||
@@ -67,4 +70,20 @@ describe("External Libraries refresh", () => {
|
||||
dispose();
|
||||
expect(useProjectViewRoots.getState().roots.has("externalLibraries")).toBe(false);
|
||||
});
|
||||
|
||||
it("drops the previous project's libraries while the next project's are discovered", async () => {
|
||||
const project = (root: string) => ({ root, trusted: true }) as ReturnType<typeof useProject.getState>["project"];
|
||||
useProject.setState({ project: project("/p") });
|
||||
results.push([rust("1.0.19")]);
|
||||
const dispose = activate();
|
||||
await vi.waitFor(() => expect(useProjectViewRoots.getState().roots.has("externalLibraries")).toBe(true));
|
||||
hang = true;
|
||||
try {
|
||||
useProject.setState({ project: project("/q") });
|
||||
expect(useProjectViewRoots.getState().roots.has("externalLibraries")).toBe(false);
|
||||
} finally {
|
||||
hang = false;
|
||||
dispose();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,103 @@
|
||||
import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";
|
||||
import type { Channel } from "@tauri-apps/api/core";
|
||||
import { clearMocks, mockIPC } from "@tauri-apps/api/mocks";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import type { AndroidDevice, IdeError, LogcatLine, RequestId } from "@/platform/ipc";
|
||||
import { LogcatView } from "./LogcatView";
|
||||
import { resetLogcat, useLogcat } from "./store";
|
||||
|
||||
const devices: AndroidDevice[] = ["A", "B"].map((serial) => ({
|
||||
serial,
|
||||
state: "device",
|
||||
model: null,
|
||||
product: null,
|
||||
device: null,
|
||||
transportId: null,
|
||||
}));
|
||||
|
||||
interface Stream {
|
||||
serial: string;
|
||||
request: RequestId;
|
||||
onLines: Channel<LogcatLine[]>;
|
||||
finish: () => void;
|
||||
fail: (error: IdeError) => void;
|
||||
}
|
||||
|
||||
function append(stream: Stream, message: string) {
|
||||
stream.onLines.onmessage([{ time: "11-04 12:52:39.123", pid: 1, tid: 1, level: "info", tag: "test", message }]);
|
||||
}
|
||||
|
||||
const messages = () => useLogcat.getState().lines.map((line) => line.message);
|
||||
|
||||
describe("Logcat streams", () => {
|
||||
let streams: Stream[];
|
||||
let cancelled: RequestId[];
|
||||
|
||||
beforeEach(() => {
|
||||
resetLogcat();
|
||||
streams = [];
|
||||
cancelled = [];
|
||||
mockIPC((cmd, args) => {
|
||||
if (cmd === "android_devices") return devices;
|
||||
if (cmd === "android_logcat") {
|
||||
return new Promise<null>((resolve, reject) => {
|
||||
streams.push({ ...(args as Omit<Stream, "finish" | "fail">), finish: () => resolve(null), fail: reject });
|
||||
});
|
||||
}
|
||||
if (cmd === "cancel_request") cancelled.push((args as { id: RequestId }).id);
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
cleanup();
|
||||
await act(async () => streams.forEach((stream) => stream.finish()));
|
||||
clearMocks();
|
||||
resetLogcat();
|
||||
});
|
||||
|
||||
it("ignores the previous device's batches and cancellation, including while paused", async () => {
|
||||
await act(async () => void render(<LogcatView />));
|
||||
const first = streams[0]!;
|
||||
act(() => append(first, "Device A before switch"));
|
||||
expect(messages()).toEqual(["Device A before switch"]);
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Device" }));
|
||||
fireEvent.click(screen.getByRole("option", { name: "B" }));
|
||||
const second = streams[1]!;
|
||||
expect(second.serial).toBe("B");
|
||||
expect(cancelled).toEqual([first.request]);
|
||||
expect(messages()).toEqual([]);
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Pause" }));
|
||||
act(() => {
|
||||
append(second, "Current device B");
|
||||
append(first, "Late device A");
|
||||
});
|
||||
await act(async () => first.fail({ kind: "cancelled", message: "Cancelled", data: null }));
|
||||
expect(screen.getByText("Streaming")).toBeVisible();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Resume" }));
|
||||
expect(messages()).toEqual(["Current device B"]);
|
||||
});
|
||||
|
||||
it.each(["completion", "error"])("ignores a closed stream's %s after reopening the same device", async (terminal) => {
|
||||
await act(async () => void render(<LogcatView />));
|
||||
const first = streams[0]!;
|
||||
act(() => append(first, "Existing buffer"));
|
||||
cleanup();
|
||||
await act(async () => void render(<LogcatView />));
|
||||
const second = streams[1]!;
|
||||
expect(second.serial).toBe(first.serial);
|
||||
expect(cancelled).toEqual([first.request]);
|
||||
|
||||
await act(async () => {
|
||||
append(first, "Late from closed stream");
|
||||
if (terminal === "completion") first.finish();
|
||||
else first.fail({ kind: "internal", message: "Old connection failed", data: null });
|
||||
append(second, "Reopened stream");
|
||||
});
|
||||
expect(messages()).toEqual(["Existing buffer", "Reopened stream"]);
|
||||
expect(screen.getByText("Streaming")).toBeVisible();
|
||||
await act(async () => second.finish());
|
||||
expect(screen.getByText("Idle")).toBeVisible();
|
||||
});
|
||||
});
|
||||
@@ -99,16 +99,23 @@ export function LogcatView() {
|
||||
written.current = 0;
|
||||
}
|
||||
const request = nextRequestId();
|
||||
const channel = new Channel<LogcatLine[]>();
|
||||
channel.onmessage = (batch) => appendLines(batch);
|
||||
let active = true;
|
||||
const isCurrent = () => active && useLogcat.getState().serial === serial;
|
||||
const channel = new Channel<LogcatLine[]>((batch) => {
|
||||
if (isCurrent()) appendLines(batch);
|
||||
});
|
||||
setStatus("running");
|
||||
call(commands.androidLogcat(request, serial, false, channel))
|
||||
.then(() => setStatus("idle"))
|
||||
.then(() => {
|
||||
if (isCurrent()) setStatus("idle");
|
||||
})
|
||||
.catch((e) => {
|
||||
if (!isCurrent()) return;
|
||||
if (isCancelled(e)) setStatus("idle");
|
||||
else setStatus("error", message(e));
|
||||
});
|
||||
return () => {
|
||||
active = false;
|
||||
void commands.cancelRequest(request);
|
||||
};
|
||||
}, [serial]);
|
||||
|
||||
@@ -7,8 +7,10 @@ import { EditorView } from "@codemirror/view";
|
||||
import { activeEditor, registerEditorContribution } from "@/editor/api";
|
||||
import { executeAction, onActionExecuted, registerActions, type Action } from "@/platform/actions";
|
||||
import { setContext } from "@/platform/context";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { notifications, registerOverlay, registerStatusItem } from "@/workbench/contributions";
|
||||
import { chooseItem, promptInput } from "@/workbench/inputDialogs";
|
||||
import { ask } from "@/workbench/messages";
|
||||
import { EDITOR_KEY_COMMANDS, editorKeyName } from "./editorKeys";
|
||||
import { MacroStatus, MacrosDialogHost, showEditMacros } from "./MacrosDialog";
|
||||
import {
|
||||
@@ -76,13 +78,34 @@ async function stop() {
|
||||
notifications().notify({ level: "info", title: "Nothing was recorded", key: "macro.recording" });
|
||||
return;
|
||||
}
|
||||
const name = await promptInput({
|
||||
title: "Enter Macro Name",
|
||||
label: "Name (leave empty to keep it only as the last macro):",
|
||||
okLabel: "OK",
|
||||
validate: () => null,
|
||||
});
|
||||
if (name) saveMacro(name, steps);
|
||||
let initial = "";
|
||||
for (;;) {
|
||||
const name = await promptInput({
|
||||
title: "Enter Macro Name",
|
||||
label: "Name (leave empty to keep it only as the last macro):",
|
||||
initial,
|
||||
okLabel: "OK",
|
||||
validate: () => null,
|
||||
});
|
||||
if (!name) return;
|
||||
const existing = useMacros.getState().saved.find((macro) => macro.name === name);
|
||||
if (!existing) {
|
||||
saveMacro(name, steps);
|
||||
return;
|
||||
}
|
||||
const { button } = await ask({
|
||||
title: "Replace Macro?",
|
||||
body: tx`A macro named '${name}' already exists. Replace its recorded steps?`,
|
||||
icon: "warning",
|
||||
buttons: [
|
||||
{ id: "rename", label: "Choose Another Name", primary: true },
|
||||
{ id: "replace", label: "Replace" },
|
||||
],
|
||||
});
|
||||
if (button === "cancel") return;
|
||||
if (button === "replace" && saveMacro(name, steps, existing)) return;
|
||||
initial = name;
|
||||
}
|
||||
}
|
||||
|
||||
const playActionId = (name: string) => `macros.play.${name}`;
|
||||
|
||||
@@ -53,6 +53,18 @@ describe("macros", () => {
|
||||
expect(useMacros.getState().saved.map((m) => m.name)).toEqual(["Duplicate"]);
|
||||
});
|
||||
|
||||
it("only replaces the confirmed version of a named macro", () => {
|
||||
saveMacro("Existing", [{ kind: "text", text: "original" }]);
|
||||
const original = useMacros.getState().saved[0];
|
||||
expect(saveMacro("Existing", [])).toBe(false);
|
||||
|
||||
const newerSteps = [{ kind: "text" as const, text: "newer steps" }];
|
||||
expect(saveMacro("Existing", newerSteps, original)).toBe(true);
|
||||
expect(saveMacro("Existing", [], original)).toBe(false);
|
||||
_reloadMacros();
|
||||
expect(useMacros.getState().saved[0]?.steps).toEqual(newerSteps);
|
||||
});
|
||||
|
||||
it("drops malformed stored steps", () => {
|
||||
localStorage.setItem(
|
||||
STORAGE_KEY,
|
||||
|
||||
@@ -116,15 +116,17 @@ export function stopRecording(): MacroStep[] {
|
||||
return rec;
|
||||
}
|
||||
|
||||
/** Saves `steps` as `name`, replacing a macro of that name. */
|
||||
export function saveMacro(name: string, macroSteps: MacroStep[]) {
|
||||
/** Saves a macro, replacing an existing entry only if it is the one confirmed. */
|
||||
export function saveMacro(name: string, macroSteps: MacroStep[], replace?: Macro): boolean {
|
||||
const n = name.trim();
|
||||
if (!n) return;
|
||||
if (!n) return false;
|
||||
const saved = useMacros.getState().saved;
|
||||
const i = saved.findIndex((m) => m.name === n);
|
||||
if (i >= 0 && saved[i] !== replace) return false;
|
||||
const entry = { name: n, steps: macroSteps };
|
||||
useMacros.setState({ saved: i >= 0 ? saved.map((m, j) => (j === i ? entry : m)) : [...saved, entry] });
|
||||
persist();
|
||||
return true;
|
||||
}
|
||||
|
||||
export function renameMacro(from: string, to: string): boolean {
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { act, cleanup, fireEvent, render, screen, within } from "@testing-library/react";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { InputDialogsHost } from "@/workbench/inputDialogs";
|
||||
import { MessagesHost } from "@/workbench/messages";
|
||||
import { activate } from ".";
|
||||
import { _reloadMacros, recordStep, saveMacro, startRecording, useMacros, type MacroStep } from "./model";
|
||||
|
||||
const original: MacroStep[] = [{ kind: "text", text: "original" }];
|
||||
const replacement: MacroStep[] = [{ kind: "text", text: "replacement" }];
|
||||
const saved = () => useMacros.getState().saved;
|
||||
|
||||
describe("saving a macro recording", () => {
|
||||
let dispose: () => void;
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
_reloadMacros();
|
||||
saveMacro("Example", original);
|
||||
dispose = activate();
|
||||
render(
|
||||
<>
|
||||
<InputDialogsHost />
|
||||
<MessagesHost />
|
||||
</>,
|
||||
);
|
||||
act(() => {
|
||||
startRecording();
|
||||
replacement.forEach(recordStep);
|
||||
void executeAction("macro.stopRecording");
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
dispose();
|
||||
});
|
||||
|
||||
function nameDialog() {
|
||||
return within(screen.getByRole("dialog", { name: "Enter Macro Name" }));
|
||||
}
|
||||
|
||||
async function enterName(name: string) {
|
||||
const dialog = nameDialog();
|
||||
fireEvent.change(dialog.getByRole("textbox"), { target: { value: name } });
|
||||
await act(async () => void fireEvent.click(dialog.getByRole("button", { name: "OK" })));
|
||||
}
|
||||
|
||||
it("keeps the original steps until the replacement is confirmed", async () => {
|
||||
await enterName(" Example ");
|
||||
expect(saved()).toEqual([{ name: "Example", steps: original }]);
|
||||
const prompt = within(screen.getByRole("dialog", { name: "Replace Macro?" }));
|
||||
expect(prompt.getByRole("button", { name: "Choose Another Name" })).toHaveFocus();
|
||||
await act(async () => void fireEvent.click(prompt.getByRole("button", { name: "Replace" })));
|
||||
_reloadMacros();
|
||||
expect(saved()).toEqual([{ name: "Example", steps: replacement }]);
|
||||
});
|
||||
|
||||
it("can save under another name after declining to replace the original", async () => {
|
||||
await enterName("Example");
|
||||
await act(async () => void fireEvent.click(screen.getByRole("button", { name: "Choose Another Name" })));
|
||||
expect(nameDialog().getByRole("textbox")).toHaveValue("Example");
|
||||
await enterName("Another");
|
||||
expect(saved()).toEqual([
|
||||
{ name: "Example", steps: original },
|
||||
{ name: "Another", steps: replacement },
|
||||
]);
|
||||
});
|
||||
|
||||
it("cancels the save while keeping the last recording", async () => {
|
||||
await enterName("Example");
|
||||
await act(async () => void fireEvent.click(screen.getByRole("button", { name: "Cancel" })));
|
||||
_reloadMacros();
|
||||
expect(saved()).toEqual([{ name: "Example", steps: original }]);
|
||||
expect(useMacros.getState().last).toEqual(replacement);
|
||||
expect(screen.queryByRole("dialog")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -91,6 +91,13 @@
|
||||
outline: 1px solid var(--fg-muted);
|
||||
outline-offset: -1px;
|
||||
}
|
||||
.flame:focus {
|
||||
outline: none;
|
||||
}
|
||||
.flame:focus .current {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: -2px;
|
||||
}
|
||||
.c1 {
|
||||
background: var(--flame-1);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { render, screen, within } from "@testing-library/react";
|
||||
import { fireEvent, render, screen, within } from "@testing-library/react";
|
||||
import type { Profile, ProfileMode } from "@/platform/ipc";
|
||||
import { useI18n } from "@/platform/i18n";
|
||||
import { ProfilerTabs, ProfilerView } from "./ProfilerView";
|
||||
@@ -48,6 +48,26 @@ describe("ProfilerView", () => {
|
||||
expect(screen.getByText("async-profiler · 610.4 MB allocated")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("moves through the flame graph and zooms with the keyboard", () => {
|
||||
addSnapshot("App", profile("cpu", 100));
|
||||
render(<ProfilerView />);
|
||||
const graph = screen.getByRole("tree", { name: "Flame graph" });
|
||||
expect(graph.tabIndex).toBe(0);
|
||||
const current = () =>
|
||||
document.getElementById(graph.getAttribute("aria-activedescendant")!)?.getAttribute("aria-label");
|
||||
expect(current()).toBe("all (100 ms)");
|
||||
fireEvent.keyDown(graph, { key: "ArrowUp" });
|
||||
expect(current()).toBe("Main.run");
|
||||
fireEvent.keyDown(graph, { key: "Enter" });
|
||||
expect(screen.getByText("Zoomed into Main.run")).toBeInTheDocument();
|
||||
fireEvent.keyDown(graph, { key: "ArrowUp" });
|
||||
expect(current()).toBe("Main.work");
|
||||
fireEvent.keyDown(graph, { key: "ArrowDown" });
|
||||
expect(current()).toBe("Main.run");
|
||||
fireEvent.keyDown(graph, { key: "Escape" });
|
||||
expect(screen.queryByText("Zoomed into Main.run")).toBeNull();
|
||||
});
|
||||
|
||||
it("marks the allocated type in the flame graph and the method list", () => {
|
||||
addSnapshot("App", profile("allocations", 640_000_000));
|
||||
const flame = render(<ProfilerView />);
|
||||
|
||||
@@ -3,12 +3,12 @@
|
||||
* (click to zoom, search highlights), the call tree (top-down) and the method
|
||||
* list (self / total). Double-click opens a frame's source when known.
|
||||
*/
|
||||
import { useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";
|
||||
import clsx from "clsx";
|
||||
import type { Profile } from "@/platform/ipc";
|
||||
import { EmptyState, Icon, IconButton, Input, Tabs, Tree, T } from "@/ui";
|
||||
import { editorService } from "@/workbench/contributions";
|
||||
import { colorSlot, flameLayout, formatWeight, frameLocation, matchingFrames, share } from "./model";
|
||||
import { colorSlot, flameLayout, flameStep, formatWeight, frameLocation, matchingFrames, share } from "./model";
|
||||
import { activeSnapshot, closeSnapshot, useProfiler, type ProfilerTab } from "./store";
|
||||
import styles from "./Profiler.module.css";
|
||||
import { useTx } from "@/platform/i18n";
|
||||
@@ -96,6 +96,28 @@ function FlameGraph({ profile, query }: { profile: Profile; query: string }) {
|
||||
return () => ro.disconnect();
|
||||
}, []);
|
||||
const layout = useMemo(() => flameLayout(profile, focus, width > 0 ? 1 / width : 0.002), [profile, focus, width]);
|
||||
// The frame the keyboard is on: arrows move it, Enter zooms into it, F4 opens its source.
|
||||
const [current, setCurrent] = useState(0);
|
||||
const shown = layout.rects.some((r) => r.node === current) ? current : focus;
|
||||
const onKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {
|
||||
const moves: Record<string, Parameters<typeof flameStep>[2]> = {
|
||||
ArrowUp: "deeper",
|
||||
ArrowDown: "shallower",
|
||||
ArrowLeft: "previous",
|
||||
ArrowRight: "next",
|
||||
};
|
||||
const move = moves[e.key];
|
||||
if (move) setCurrent(flameStep(layout.rects, shown, move));
|
||||
else if (e.key === "Enter") setFocus(shown);
|
||||
else if (e.key === "Escape" && focus !== 0) setFocus(0);
|
||||
else if (e.key === "F4") openFrame(profile, profile.nodes[shown]!.frame);
|
||||
else return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
};
|
||||
useEffect(() => {
|
||||
ref.current?.querySelector(`[data-node="${shown}"]`)?.scrollIntoView?.({ block: "nearest" });
|
||||
}, [shown]);
|
||||
const matches = useMemo(() => matchingFrames(profile, query), [profile, query]);
|
||||
const unit = profile.unit;
|
||||
const total = profile.total ?? 0;
|
||||
@@ -109,7 +131,15 @@ function FlameGraph({ profile, query }: { profile: Profile; query: string }) {
|
||||
</div>
|
||||
)}
|
||||
<div className={styles.flameScroll} ref={ref}>
|
||||
<div className={styles.flame} style={{ height: layout.depth * ROW }} role="tree" aria-label={tx("Flame graph")}>
|
||||
<div
|
||||
className={styles.flame}
|
||||
style={{ height: layout.depth * ROW }}
|
||||
role="tree"
|
||||
aria-label={tx("Flame graph")}
|
||||
tabIndex={0}
|
||||
aria-activedescendant={`flame-frame-${shown}`}
|
||||
onKeyDown={onKeyDown}
|
||||
>
|
||||
{width > 0 &&
|
||||
layout.rects.map((r) => {
|
||||
const node = profile.nodes[r.node]!;
|
||||
@@ -120,17 +150,24 @@ function FlameGraph({ profile, query }: { profile: Profile; query: string }) {
|
||||
return (
|
||||
<div
|
||||
key={r.node}
|
||||
id={`flame-frame-${r.node}`}
|
||||
data-node={r.node}
|
||||
role="treeitem"
|
||||
aria-label={label}
|
||||
aria-selected={r.node === shown}
|
||||
className={clsx(
|
||||
styles.frame,
|
||||
r.node === shown && styles.current,
|
||||
styles[`c${colorSlot(frame.name)}`],
|
||||
frame.kind === "allocatedType" && styles.typeFrame,
|
||||
matches && (matches.has(node.frame) ? styles.match : styles.dim),
|
||||
)}
|
||||
style={{ left: r.x * width, width: Math.max(w - 1, 1), bottom: r.depth * ROW }}
|
||||
title={`${frame.kind === "allocatedType" ? `${tx("Allocated type")}\n` : ""}${frame.name}${location ? ` (${location})` : ""}\nTotal: ${formatWeight(node.total ?? 0, unit)} (${share(node.total ?? 0, total)})\nSelf: ${formatWeight(node.selfWeight ?? 0, unit)}`}
|
||||
onClick={() => setFocus(r.node)}
|
||||
onClick={() => {
|
||||
setCurrent(r.node);
|
||||
setFocus(r.node);
|
||||
}}
|
||||
onDoubleClick={() => openFrame(profile, node.frame)}
|
||||
>
|
||||
{w > 28 && <span className={styles.frameText}>{label}</span>}
|
||||
|
||||
@@ -110,6 +110,34 @@ export function flameLayout(profile: Profile, focus = 0, minWidth = 0.002): { re
|
||||
return { rects, depth: maxDepth + 1 };
|
||||
}
|
||||
|
||||
/**
|
||||
* Keyboard moves in the flame graph from the frame `node`: `deeper` to its widest callee,
|
||||
* `shallower` to its caller, `previous` / `next` to the neighbouring frame on its row.
|
||||
*/
|
||||
export function flameStep(
|
||||
rects: readonly FlameRect[],
|
||||
node: number,
|
||||
move: "deeper" | "shallower" | "previous" | "next",
|
||||
): number {
|
||||
const at = rects.find((r) => r.node === node);
|
||||
if (!at) return rects[0]?.node ?? node;
|
||||
switch (move) {
|
||||
case "deeper": {
|
||||
const inside = rects.filter((r) => r.depth === at.depth + 1 && r.x >= at.x && r.x < at.x + at.width);
|
||||
return inside.reduce<FlameRect | undefined>((a, r) => (!a || r.width > a.width ? r : a), undefined)?.node ?? node;
|
||||
}
|
||||
case "shallower":
|
||||
// A callee starts inside its caller's span.
|
||||
return rects.find((r) => r.depth === at.depth - 1 && r.x <= at.x && at.x < r.x + r.width)?.node ?? node;
|
||||
case "previous":
|
||||
case "next": {
|
||||
const row = rects.filter((r) => r.depth === at.depth).sort((a, b) => a.x - b.x);
|
||||
const i = row.indexOf(at) + (move === "next" ? 1 : -1);
|
||||
return row[i]?.node ?? node;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const parentCache = new WeakMap<Profile, Int32Array>();
|
||||
|
||||
/** Parent node of every node (-1 for the root). */
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
allocationProfilerSupports,
|
||||
colorSlot,
|
||||
flameLayout,
|
||||
flameStep,
|
||||
formatWeight,
|
||||
frameLocation,
|
||||
matchingFrames,
|
||||
@@ -108,3 +109,22 @@ describe("profiler model", () => {
|
||||
expect(colorSlot("main")).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("flameStep", () => {
|
||||
// root (0) → a (1, 60%) and b (2, 40%); a → c (3)
|
||||
const rects = [
|
||||
{ node: 0, depth: 0, x: 0, width: 1 },
|
||||
{ node: 1, depth: 1, x: 0, width: 0.6 },
|
||||
{ node: 2, depth: 1, x: 0.6, width: 0.4 },
|
||||
{ node: 3, depth: 2, x: 0, width: 0.5 },
|
||||
];
|
||||
it("goes to the widest callee, the caller and the neighbours on a row", () => {
|
||||
expect(flameStep(rects, 0, "deeper")).toBe(1);
|
||||
expect(flameStep(rects, 1, "next")).toBe(2);
|
||||
expect(flameStep(rects, 2, "next")).toBe(2);
|
||||
expect(flameStep(rects, 2, "previous")).toBe(1);
|
||||
expect(flameStep(rects, 2, "deeper")).toBe(2);
|
||||
expect(flameStep(rects, 3, "shallower")).toBe(1);
|
||||
expect(flameStep(rects, 2, "shallower")).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -86,6 +86,7 @@ import {
|
||||
VIEW_MODES,
|
||||
autoExpand,
|
||||
clearRevealRequest,
|
||||
explainHiddenPath,
|
||||
loadDir,
|
||||
loadOutline,
|
||||
revealPath,
|
||||
@@ -517,7 +518,7 @@ export function ProjectView() {
|
||||
// Select a revealed path once its row exists.
|
||||
useEffect(() => {
|
||||
if (!revealRequest) return;
|
||||
const { path, focus, seq } = revealRequest;
|
||||
const { path, focus, seq, explain } = revealRequest;
|
||||
const exact = model.keyOfPath.get(path);
|
||||
const loadingAncestors = info.pending.some((p) => p === path || isInside(path, p));
|
||||
if (!exact && loadingAncestors) return;
|
||||
@@ -528,6 +529,8 @@ export function ProjectView() {
|
||||
handle.current?.reveal(key);
|
||||
revealing.current = false;
|
||||
if (focus) handle.current?.focus();
|
||||
const shown = model.byKey.get(key)?.path;
|
||||
if (explain && !exact && shown) explainHiddenPath(path, shown);
|
||||
}, [revealRequest, model, info]);
|
||||
|
||||
// Autoscroll from source: follow the active editor.
|
||||
|
||||
@@ -108,7 +108,7 @@ export function selectInProjectView(path?: string | null, focus = true) {
|
||||
if (!target) return false;
|
||||
if (!modeShows(target)) setViewMode("project");
|
||||
showProjectView(focus);
|
||||
return revealPath(target, focus);
|
||||
return revealPath(target, focus, true);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -7,6 +7,8 @@ import {
|
||||
reloadLoadedDirs,
|
||||
currentModel,
|
||||
expandAll,
|
||||
explainHiddenPath,
|
||||
hidingOption,
|
||||
initProjectTree,
|
||||
loadDir,
|
||||
revealPath,
|
||||
@@ -18,6 +20,7 @@ import {
|
||||
} from "./store";
|
||||
import { beginNew, commitEditing, copySelection, paste, transfer } from "./operations";
|
||||
import { closeFileRefactorDialog, pendingFileRefactorDialog } from "./FileRefactorDialogs";
|
||||
import { provideNotificationService } from "@/workbench/contributions";
|
||||
|
||||
const ROOT = "/p";
|
||||
let fs: MemoryFs;
|
||||
@@ -319,3 +322,28 @@ it("keeps the primary first and sorts attachments by name", () => {
|
||||
initProjectTree("/ws", "Workspace", ["/z", "/c", "/a"]);
|
||||
expect(currentModel().roots.map((n) => n.path)).toEqual(["/a", "/c", "/z"]);
|
||||
});
|
||||
|
||||
describe("a file the view options hide", () => {
|
||||
const entry = (name: string, ignored = false) => ({ name, path: `/p/${name}`, isDir: true, ignored }) as never;
|
||||
|
||||
it("names the option that hides it below the shown ancestor, and offers to turn it on", () => {
|
||||
useProjectTree.setState({ listings: new Map([["/p", [entry("build", true), entry("src")]]]) });
|
||||
setViewOption("showExcluded", false);
|
||||
expect(hidingOption("/p/build/out.txt", "/p")).toBe("showExcluded");
|
||||
expect(hidingOption("/p/.git/config", "/p")).toBe(
|
||||
useProjectTree.getState().options.showHidden ? null : "showHidden",
|
||||
);
|
||||
expect(hidingOption("/p/src/a.ts", "/p")).toBeNull();
|
||||
|
||||
const notify = vi.fn();
|
||||
provideNotificationService({ notify } as never);
|
||||
explainHiddenPath("/p/build/out.txt", "/p");
|
||||
expect(notify).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ title: "out.txt is hidden because Show Excluded Files is off" }),
|
||||
);
|
||||
notify.mock.calls[0]![0].actions[0].run();
|
||||
expect(useProjectTree.getState().options.showExcluded).toBe(true);
|
||||
expect(useProjectTree.getState().revealRequest?.path).toBe("/p/build/out.txt");
|
||||
expect(hidingOption("/p/build/out.txt", "/p")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -10,6 +10,9 @@ import { commands, type FileEntry, type OutlineItem } from "@/bindings";
|
||||
import { withDocument } from "@/editor/lsp/files";
|
||||
import { IpcError } from "@/platform/ipc";
|
||||
import { libraryEntryPaths } from "@/platform/virtualDocs";
|
||||
import { isIgnoredName } from "@/platform/ignoredNames";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
import { ipcPath } from "@/platform/paths";
|
||||
import {
|
||||
DEFAULT_TREE_OPTIONS,
|
||||
@@ -122,7 +125,8 @@ interface ProjectTreeState {
|
||||
editing: Editing | null;
|
||||
clipboard: Clipboard | null;
|
||||
/** A path to select (and scroll to) once its row is visible. */
|
||||
revealRequest: { path: string; focus: boolean; seq: number } | null;
|
||||
/** `explain`: say which view option hides the path when only an ancestor can be selected. */
|
||||
revealRequest: { path: string; focus: boolean; seq: number; explain?: boolean } | null;
|
||||
/** Folder key highlighted as drop target. */
|
||||
dropTarget: string | null;
|
||||
mode: ViewMode;
|
||||
@@ -635,7 +639,7 @@ export function dropOutlines(paths: readonly string[]) {
|
||||
let revealSeq = 0;
|
||||
|
||||
/** Expands the ancestors of `path` and selects it once visible. */
|
||||
export function revealPath(requested: string, focus = false) {
|
||||
export function revealPath(requested: string, focus = false, explain = false) {
|
||||
const { expanded } = get();
|
||||
const project = get().root;
|
||||
if (!project) return false;
|
||||
@@ -668,7 +672,7 @@ export function revealPath(requested: string, focus = false) {
|
||||
changed = true;
|
||||
}
|
||||
if (changed) setExpanded(next);
|
||||
set({ revealRequest: { path, focus, seq: ++revealSeq } });
|
||||
set({ revealRequest: { path, focus, seq: ++revealSeq, ...(explain ? { explain } : {}) } });
|
||||
for (const a of folders) void loadDir(a);
|
||||
return true;
|
||||
}
|
||||
@@ -734,6 +738,45 @@ function groupAncestors(model: TreeModel, key: string): string[] {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The view option that hides `path` below its shown ancestor `shown`: a hidden name
|
||||
* (Show Hidden Files) or an ignored entry (Show Excluded Files). Null when no option does.
|
||||
*/
|
||||
export function hidingOption(path: string, shown: string): "showHidden" | "showExcluded" | null {
|
||||
const { listings, options } = get();
|
||||
if (!isSameOrInside(path, shown) || path === shown) return null;
|
||||
let dir = shown;
|
||||
for (const name of path.slice(shown.length + 1).split("/")) {
|
||||
if (isIgnoredName(name)) return options.showHidden ? null : "showHidden";
|
||||
if (listings.get(dir)?.find((e) => e.name === name)?.ignored) return options.showExcluded ? null : "showExcluded";
|
||||
dir = `${dir}/${name}`;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const OPTION_TITLES = { showHidden: "Show Hidden Files", showExcluded: "Show Excluded Files" } as const;
|
||||
|
||||
/** Select Opened File reached only `shown`: say which option hides `path`, offering to turn it on. */
|
||||
export function explainHiddenPath(path: string, shown: string) {
|
||||
const option = hidingOption(path, shown);
|
||||
if (!option) return;
|
||||
const title = OPTION_TITLES[option];
|
||||
notifications().notify({
|
||||
level: "info",
|
||||
key: "project.hiddenPath",
|
||||
title: tx`${nameOf(path)} is hidden because ${title} is off`,
|
||||
actions: [
|
||||
{
|
||||
label: tx(title),
|
||||
run: () => {
|
||||
setViewOption(option, true);
|
||||
revealPath(path, true);
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
export function clearRevealRequest(seq: number) {
|
||||
if (get().revealRequest?.seq === seq) set({ revealRequest: null });
|
||||
}
|
||||
|
||||
@@ -140,6 +140,14 @@ function TrustSettings() {
|
||||
setError(String(e));
|
||||
}
|
||||
};
|
||||
const trust = async (path: string) => {
|
||||
try {
|
||||
await call(commands.projectTrustSet(path, true, false));
|
||||
await refresh();
|
||||
} catch (e) {
|
||||
setError(String(e));
|
||||
}
|
||||
};
|
||||
const addLocation = async () => {
|
||||
try {
|
||||
const { open } = await import("@/platform/dialog");
|
||||
@@ -169,6 +177,24 @@ function TrustSettings() {
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
{decisions?.restricted.length ? (
|
||||
<>
|
||||
<h3>
|
||||
<T>Restricted projects</T>
|
||||
</h3>
|
||||
<p className={styles.hint}>
|
||||
<T>These projects open in Restricted Mode, even inside a trusted location.</T>
|
||||
</p>
|
||||
{decisions.restricted.map((path) => (
|
||||
<div className={styles.row} key={path}>
|
||||
<span className={styles.path}>{path}</span>
|
||||
<Button onClick={() => void trust(path)}>
|
||||
<T>Trust</T>
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</>
|
||||
) : null}
|
||||
<div className={styles.sectionHead}>
|
||||
<h3>
|
||||
<T>Trusted locations</T>
|
||||
@@ -178,7 +204,7 @@ function TrustSettings() {
|
||||
</Button>
|
||||
</div>
|
||||
<p className={styles.hint}>
|
||||
<T>Every project inside a trusted location is trusted without asking.</T>
|
||||
<T>Every project inside a trusted location is trusted without asking, unless it is a restricted project.</T>
|
||||
</p>
|
||||
{decisions?.locations.map((path) => (
|
||||
<div className={styles.row} key={path}>
|
||||
|
||||
@@ -58,9 +58,13 @@
|
||||
justify-content: space-between;
|
||||
gap: var(--space-3);
|
||||
}
|
||||
.sectionHead h3 {
|
||||
.content h3 {
|
||||
margin: 0;
|
||||
}
|
||||
.content > h3,
|
||||
.sectionHead {
|
||||
margin-top: var(--space-3);
|
||||
}
|
||||
.hint {
|
||||
color: var(--fg-secondary);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { afterEach, beforeEach, expect, it, vi } from "vitest";
|
||||
import { act, fireEvent, render, screen } from "@testing-library/react";
|
||||
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { confirmProjectTrust } from "@/platform/projectTrust";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { emitLocalIdeEvent } from "@/platform/ipc";
|
||||
@@ -165,6 +165,24 @@ it("adds a picked folder as a trusted location from settings", async () => {
|
||||
expect(addLocation).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("lists restricted projects, which a trusted location doesn't cover, and trusts one from settings", async () => {
|
||||
const Page = useSettingsPages.getState().pages.get("projectTrust")!.component!;
|
||||
listDecisions.mockResolvedValue({
|
||||
status: "ok",
|
||||
data: { projects: [], locations: ["/projects"], restricted: ["/projects/app"] },
|
||||
});
|
||||
render(<Page />);
|
||||
expect(await screen.findByRole("heading", { name: "Restricted projects" })).toBeTruthy();
|
||||
listDecisions.mockResolvedValue({
|
||||
status: "ok",
|
||||
data: { projects: ["/projects/app"], locations: ["/projects"], restricted: [] },
|
||||
});
|
||||
fireEvent.click(screen.getByRole("button", { name: "Trust" }));
|
||||
await waitFor(() => expect(screen.queryByRole("heading", { name: "Restricted projects" })).toBeNull());
|
||||
expect(decide).toHaveBeenCalledWith("/projects/app", true, false);
|
||||
expect(screen.getByText("/projects/app")).toBeTruthy();
|
||||
});
|
||||
|
||||
it.each(["Trust Project", "Preview in Restricted Mode"])(
|
||||
"keeps a local opening's trust decision on the client: %s",
|
||||
async (button) => {
|
||||
|
||||
@@ -36,6 +36,7 @@ import {
|
||||
import { selectedTarget } from "./sessionTargets";
|
||||
import styles from "./Run.module.css";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { confirm } from "@/workbench/messages";
|
||||
|
||||
type Row =
|
||||
/** A labelled group, or a thin separator when `label` is empty. */
|
||||
@@ -111,6 +112,16 @@ function anchorElement(): Element | { x: number; y: number } {
|
||||
}
|
||||
|
||||
/** Run/Debug configuration chooser popup (⌃⌥R), anchored to the title bar widget. */
|
||||
/** Deletes a configuration from the chooser once the user confirms, as IDEA's popup asks first. */
|
||||
async function askDeleteConfig(config: RunConfig) {
|
||||
const ok = await confirm({
|
||||
title: "Confirmation",
|
||||
message: tx`Are you sure you want to delete ${config.name}?`,
|
||||
ok: "Delete",
|
||||
});
|
||||
if (ok) await deleteConfig(config.id);
|
||||
}
|
||||
|
||||
export function ConfigChooserOverlay() {
|
||||
const open = useRun((s) => s.chooserOpen);
|
||||
if (!open) return null;
|
||||
@@ -250,10 +261,11 @@ function ConfigChooser() {
|
||||
e.key === "Delete" &&
|
||||
row?.type === "config" &&
|
||||
canDeleteConfig(row.config.id) &&
|
||||
input().selectionStart === query.length
|
||||
input().selectionStart === query.length &&
|
||||
input().selectionEnd === query.length
|
||||
) {
|
||||
e.preventDefault();
|
||||
void deleteConfig(row.config.id);
|
||||
void askDeleteConfig(row.config);
|
||||
return;
|
||||
}
|
||||
if (numbers.size && !e.altKey && !e.ctrlKey && !e.metaKey && /^Digit[1-9]$|^Numpad[1-9]$/.test(e.code)) {
|
||||
@@ -286,7 +298,7 @@ function ConfigChooser() {
|
||||
{ kind: "header", label: "Configuration" },
|
||||
{ label: "Edit…", icon: "edit", run: () => activate(row, "edit") },
|
||||
{ label: pinned.includes(c.id) ? "Unpin" : "Pin", icon: "pin", run: () => togglePinned(c.id) },
|
||||
...(canDeleteConfig(c.id) ? [{ label: "Delete", danger: true, run: () => void deleteConfig(c.id) }] : []),
|
||||
...(canDeleteConfig(c.id) ? [{ label: "Delete", danger: true, run: () => void askDeleteConfig(c) }] : []),
|
||||
];
|
||||
};
|
||||
const openMenu = (c: RunConfig, at: Element) => setMenu({ name: c.name, anchor: at, items: menuItems(c) });
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { afterEach, beforeEach, expect, it, vi } from "vitest";
|
||||
import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
|
||||
|
||||
const ipc = vi.hoisted(() => ({
|
||||
runSaveConfigs: vi.fn(),
|
||||
@@ -17,6 +17,7 @@ vi.mock("@/platform/ipc", async (importOriginal) => ({
|
||||
|
||||
import type { RunConfig } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { MessagesHost } from "@/workbench/messages";
|
||||
import { EditConfigsOverlay } from "./EditConfigsDialog";
|
||||
import { ConfigChooserOverlay } from "./ConfigChooser";
|
||||
import {
|
||||
@@ -141,14 +142,39 @@ it("keeps other temporary and non-temporary configurations on removal", async ()
|
||||
expect(useRun.getState().configs.map((c) => c.id)).toEqual(expect.arrayContaining(["npm:app", other.id]));
|
||||
});
|
||||
|
||||
it("chooser popup Delete removes the selected detection", async () => {
|
||||
it("chooser popup Delete removes the selected detection once confirmed", async () => {
|
||||
useRun.setState({ chooserOpen: true, editorOpen: false });
|
||||
render(<ConfigChooserOverlay />);
|
||||
render(
|
||||
<>
|
||||
<ConfigChooserOverlay />
|
||||
<MessagesHost />
|
||||
</>,
|
||||
);
|
||||
fireEvent.keyDown(document.querySelector("input[data-autofocus]")!, { key: "Delete" });
|
||||
const ask = await screen.findByRole("dialog", { name: "Confirmation" });
|
||||
expect(ipc.runSaveConfigs).not.toHaveBeenCalled();
|
||||
fireEvent.click(within(ask).getByRole("button", { name: "Delete" }));
|
||||
await waitFor(() => expect(ipc.runSaveConfigs).toHaveBeenCalledWith([], ["npm:app"]));
|
||||
await waitFor(() => expect(useRun.getState().configs).toEqual([]));
|
||||
});
|
||||
|
||||
it("chooser popup Delete edits the search text when the caret is not at its end", async () => {
|
||||
useRun.setState({ chooserOpen: true, editorOpen: false });
|
||||
render(
|
||||
<>
|
||||
<ConfigChooserOverlay />
|
||||
<MessagesHost />
|
||||
</>,
|
||||
);
|
||||
const input = document.querySelector<HTMLInputElement>("input[data-autofocus]")!;
|
||||
fireEvent.change(input, { target: { value: "app" } });
|
||||
input.setSelectionRange(1, 1);
|
||||
fireEvent.keyDown(input, { key: "Delete" });
|
||||
await act(async () => {});
|
||||
expect(screen.queryByRole("dialog", { name: "Confirmation" })).toBeNull();
|
||||
expect(ipc.runSaveConfigs).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("Cancel discards a pending detected removal", () => {
|
||||
render(<EditConfigsOverlay />);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Remove Configuration" }));
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { act, fireEvent, render, screen, within } from "@testing-library/react";
|
||||
import type { FileMatches, SearchSummary } from "@/platform/ipc";
|
||||
import type { FileMatches, SearchQuery, SearchSummary } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import type { ReplaceRequest } from "../find/replaceFlow";
|
||||
|
||||
const replaced: ReplaceRequest[] = [];
|
||||
const confirms: unknown[] = [];
|
||||
const queries: SearchQuery[] = [];
|
||||
let validation: Promise<void> | null = null;
|
||||
let search: ((onFile: (file: FileMatches) => void) => Promise<SearchSummary | null>) | null = null;
|
||||
let confirmation: Promise<boolean> | null = null;
|
||||
@@ -15,7 +17,8 @@ vi.mock("../find/windowStore", async (orig) => ({
|
||||
validate: async () => {
|
||||
await validation;
|
||||
},
|
||||
start: async (_id: number, _q: unknown, onFile: (f: FileMatches) => void) => {
|
||||
start: async (_id: number, query: SearchQuery, onFile: (f: FileMatches) => void) => {
|
||||
queries.push(query);
|
||||
if (search) return search(onFile);
|
||||
onFile({
|
||||
path: "/p/a.kt",
|
||||
@@ -87,6 +90,7 @@ const field = () => screen.getByLabelText("Text to find");
|
||||
beforeEach(() => {
|
||||
replaced.length = 0;
|
||||
confirms.length = 0;
|
||||
queries.length = 0;
|
||||
localStorage.clear();
|
||||
validation = null;
|
||||
search = null;
|
||||
@@ -108,7 +112,10 @@ beforeEach(() => {
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
act(() => hideFindPopup());
|
||||
act(() => {
|
||||
hideFindPopup();
|
||||
useProject.setState({ project: null });
|
||||
});
|
||||
});
|
||||
|
||||
describe("Find in Files popup", () => {
|
||||
@@ -260,6 +267,53 @@ describe("Find in Files popup", () => {
|
||||
expect(useFindPopup.getState().directory).toBe("/p/src/main");
|
||||
});
|
||||
|
||||
it.each([false, true])("waits for a directory instead of searching the project (replace=%s)", async (replace) => {
|
||||
useProject.setState({ project: { root: "/p", name: "p", trusted: true, isGit: false, settings: {} } });
|
||||
render(<FindInFilesOverlay />);
|
||||
act(() => showFindPopup(replace, { query: "order", directory: "/p" }));
|
||||
await settle();
|
||||
expect(queries.map((q) => q.scope)).toEqual([{ kind: "directory", path: "/p" }]);
|
||||
expect(screen.getByRole("listbox", { name: "Matches" })).toHaveTextContent("a.kt");
|
||||
|
||||
const directory = screen.getByRole("textbox", { name: "Directory" });
|
||||
expect(directory).toHaveValue(".");
|
||||
fireEvent.change(directory, { target: { value: "" } });
|
||||
expect(screen.queryByText("a.kt")).not.toBeInTheDocument();
|
||||
await settle();
|
||||
expect(queries).toHaveLength(1);
|
||||
expect(screen.getByRole("tab", { name: "Directory" })).toHaveAttribute("aria-selected", "true");
|
||||
expect(screen.getByText("Enter a directory to search")).toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: "Open in Find Window" })).toBeDisabled();
|
||||
fireEvent.keyDown(field(), { key: "Enter", ctrlKey: true });
|
||||
expect(useFindPopup.getState().open).toBe(true);
|
||||
if (replace) {
|
||||
expect(screen.getByRole("button", { name: "Replace All" })).toBeDisabled();
|
||||
expect(screen.getByRole("button", { name: /^Replace$/ })).toBeDisabled();
|
||||
fireEvent.keyDown(field(), { key: "Enter" });
|
||||
fireEvent.keyDown(field(), { key: "Enter", altKey: true, shiftKey: true });
|
||||
expect(replaced).toHaveLength(0);
|
||||
expect(confirms).toHaveLength(0);
|
||||
}
|
||||
|
||||
fireEvent.change(directory, { target: { value: " " } });
|
||||
await settle();
|
||||
expect(queries).toHaveLength(1);
|
||||
fireEvent.change(directory, { target: { value: "" } });
|
||||
act(() => hideFindPopup());
|
||||
act(() => showFindPopup(replace));
|
||||
await settle();
|
||||
expect(screen.getByRole("tab", { name: "Directory" })).toHaveAttribute("aria-selected", "true");
|
||||
expect(queries).toHaveLength(1);
|
||||
|
||||
fireEvent.change(screen.getByRole("textbox", { name: "Directory" }), { target: { value: "src" } });
|
||||
await settle();
|
||||
expect(queries.at(-1)?.scope).toEqual({ kind: "directory", path: "/p/src" });
|
||||
fireEvent.click(screen.getByRole("tab", { name: "In Project" }));
|
||||
await settle();
|
||||
expect(queries.at(-1)?.scope).toEqual({ kind: "project" });
|
||||
expect(screen.getByRole("button", { name: "Open in Find Window" })).toBeEnabled();
|
||||
});
|
||||
|
||||
it("closing remembers the search text", async () => {
|
||||
render(<FindInFilesOverlay />);
|
||||
act(() => showFindPopup(false, { query: "order" }));
|
||||
|
||||
@@ -31,6 +31,13 @@ describe("Find in Files module and custom scopes", () => {
|
||||
const inputs = { root: "/p", openPaths: () => ["/p/a.ts"], recentPaths: null };
|
||||
const base = useFindPopup.getState();
|
||||
|
||||
it.each(["/", "C:/"])("preserves the absolute root directory %s", (directory) => {
|
||||
expect(resolveFindScope({ ...base, scopeTab: "directory", directory }, inputs)).toEqual({
|
||||
kind: "directory",
|
||||
path: directory,
|
||||
});
|
||||
});
|
||||
|
||||
it("a module searches its folder, the root module the project", () => {
|
||||
expect(resolveFindScope({ ...base, scopeTab: "module", module: "/member" }, inputs)).toEqual({
|
||||
kind: "directory",
|
||||
@@ -56,7 +63,7 @@ describe("Find in Files module and custom scopes", () => {
|
||||
expect(scope("openFiles")).toEqual({ kind: "files", paths: ["/p/a.ts"] });
|
||||
expect(scope(customScopeValue("No tests"))).toEqual({ kind: "pattern", pattern: "!file:*test*" });
|
||||
expect(scope(customScopeValue("gone"))).toEqual({ kind: "project" });
|
||||
const q = buildQuery({ ...base, pattern: "x" }, scope(customScopeValue("No tests")), 0);
|
||||
const q = buildQuery({ ...base, pattern: "x" }, scope(customScopeValue("No tests"))!, 0);
|
||||
expect(describeQuery(q, "/p")).toBe("'x' in Scope 'No tests'");
|
||||
useCustomScopes.setState({ root: null, scopes: [] });
|
||||
});
|
||||
|
||||
@@ -1,11 +1,20 @@
|
||||
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent, type MouseEvent } from "react";
|
||||
import {
|
||||
useEffect,
|
||||
useId,
|
||||
useLayoutEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type KeyboardEvent,
|
||||
type MouseEvent,
|
||||
} from "react";
|
||||
import clsx from "clsx";
|
||||
import { openEditorPaths, useEditorRegistry } from "@/editor/api";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { setContext } from "@/platform/context";
|
||||
import { t, useTxTemplate, tx } from "@/platform/i18n";
|
||||
import { formatBinding, hostBinding, shortcutLabel } from "@/platform/keymap";
|
||||
import { call, commands, isTauri, onIdeEvent, type SearchScope } from "@/platform/ipc";
|
||||
import { call, commands, isTauri, onIdeEvent } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { useProjectModules } from "@/platform/projectRoots";
|
||||
import { EDIT_SCOPES_ACTION, useCustomScopeList } from "@/platform/search";
|
||||
@@ -128,8 +137,10 @@ const NAMED_SCOPES: Array<{ value: BuiltinScope; label: string }> = [
|
||||
];
|
||||
|
||||
function displayDirectory(dir: string, root: string | null): string {
|
||||
if (root && dir === root) return "";
|
||||
return root && dir.startsWith(root + "/") ? dir.slice(root.length + 1) : dir;
|
||||
if (!root) return dir;
|
||||
const prefix = root.endsWith("/") ? root : root + "/";
|
||||
if (dir === root) return ".";
|
||||
return dir.startsWith(prefix) ? dir.slice(prefix.length) || "." : dir;
|
||||
}
|
||||
|
||||
function FindInFilesDialog() {
|
||||
@@ -169,6 +180,7 @@ function FindInFilesDialog() {
|
||||
const maskRef = useRef<HTMLDivElement>(null);
|
||||
const maskInputRef = useRef<HTMLInputElement>(null);
|
||||
const contextRef = useRef<HTMLButtonElement>(null);
|
||||
const directoryPromptId = useId();
|
||||
const set = (patch: Partial<FindOptions>) => useFindPopup.setState(patch);
|
||||
|
||||
useEffect(() => () => session.dispose(), [session]);
|
||||
@@ -200,7 +212,7 @@ function FindInFilesDialog() {
|
||||
);
|
||||
}, [s.scopeTab, s.namedScope, recentPaths]);
|
||||
|
||||
const scope: SearchScope = useMemo(
|
||||
const scope = useMemo(
|
||||
() =>
|
||||
resolveFindScope(s, {
|
||||
root,
|
||||
@@ -229,13 +241,13 @@ function FindInFilesDialog() {
|
||||
context: s.context,
|
||||
};
|
||||
const query = useMemo(
|
||||
() => buildQuery(options, scope, POPUP_MAX_MATCHES),
|
||||
() => (scope ? buildQuery(options, scope, POPUP_MAX_MATCHES) : null),
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[s.pattern, s.caseSensitive, s.wholeWord, s.isRegex, s.maskEnabled, s.mask, s.context, scope],
|
||||
);
|
||||
const queryKey = JSON.stringify(query);
|
||||
|
||||
const stale = state.stale || (state.query ? JSON.stringify(state.query) !== queryKey : !!s.pattern);
|
||||
const stale = !!query && (state.stale || (state.query ? JSON.stringify(state.query) !== queryKey : !!s.pattern));
|
||||
const currentQuery = useRef(queryKey);
|
||||
const [rerun, setRerun] = useState(0);
|
||||
useEffect(
|
||||
@@ -247,6 +259,10 @@ function FindInFilesDialog() {
|
||||
);
|
||||
useLayoutEffect(() => {
|
||||
currentQuery.current = queryKey;
|
||||
if (!query) {
|
||||
void session.search(null);
|
||||
return;
|
||||
}
|
||||
session.invalidate();
|
||||
const t = setTimeout(() => {
|
||||
void session.search(query);
|
||||
@@ -289,9 +305,9 @@ function FindInFilesDialog() {
|
||||
setTimeout(() => void openLocation(row.path, pos, { side }), 0);
|
||||
};
|
||||
const pin = () => {
|
||||
if (!s.pattern) return;
|
||||
if (!query?.pattern) return;
|
||||
if (s.maskEnabled) rememberMask(s.mask);
|
||||
const pinned = buildQuery(options, scope, 0);
|
||||
const pinned = { ...query, maxMatches: 0 };
|
||||
close();
|
||||
openInFindWindow(pinned, describeQuery(pinned, root), {
|
||||
replacement: s.replace ? s.replacement : null,
|
||||
@@ -302,7 +318,11 @@ function FindInFilesDialog() {
|
||||
|
||||
// Check again after a confirmation: its captured rows may have been superseded.
|
||||
const canReplace = () =>
|
||||
!stale && !session.current.stale && currentQuery.current === queryKey && session.current.files === state.files;
|
||||
!!query &&
|
||||
!stale &&
|
||||
!session.current.stale &&
|
||||
currentQuery.current === queryKey &&
|
||||
session.current.files === state.files;
|
||||
|
||||
/**
|
||||
* IDEA asks before Replace All only when the results span more than one file, or when the
|
||||
@@ -340,7 +360,7 @@ function FindInFilesDialog() {
|
||||
|
||||
/** Replaces `usages` in the backend, then marks them done (IDEA's Replace / Replace All). */
|
||||
const replaceUsages = async (usages: Usage[], allInScope = false): Promise<ReplaceMarks | null> => {
|
||||
if (!canReplace() || !usages.length || running) return null;
|
||||
if (!query || !canReplace() || !usages.length || running) return null;
|
||||
const run = startReplace(
|
||||
{
|
||||
query,
|
||||
@@ -415,7 +435,7 @@ function FindInFilesDialog() {
|
||||
previewVersion,
|
||||
]);
|
||||
useEffect(() => {
|
||||
if (stale || !previewMode || !s.replace || !selected) return;
|
||||
if (!query || stale || !previewMode || !s.replace || !selected) return;
|
||||
let alive = true;
|
||||
const key = diffPreviewKey;
|
||||
const usages = pendingUsages([selected], marks);
|
||||
@@ -461,7 +481,7 @@ function FindInFilesDialog() {
|
||||
|
||||
const selectScope = (id: ScopeTab) => {
|
||||
// IDEA starts the Directory scope at the current file's folder.
|
||||
if (id === "directory" && !s.directory.trim()) {
|
||||
if (id === "directory" && s.scopeTab !== "directory" && !s.directory.trim()) {
|
||||
const active = maybeEditorService()?.activePath();
|
||||
const folders = project?.workspace?.projects ?? (root ? [root] : []);
|
||||
const dir = active && folders.some((r) => active.startsWith(r + "/")) ? dirname(active) : root;
|
||||
@@ -580,7 +600,18 @@ function FindInFilesDialog() {
|
||||
rowHeight={ROW}
|
||||
aria-label="Matches"
|
||||
empty={
|
||||
<EmptyResults state={state} options={options} onClear={clearOptions} onRegex={() => set({ isRegex: true })} />
|
||||
query ? (
|
||||
<EmptyResults
|
||||
state={state}
|
||||
options={options}
|
||||
onClear={clearOptions}
|
||||
onRegex={() => set({ isRegex: true })}
|
||||
/>
|
||||
) : (
|
||||
<div id={directoryPromptId} className={styles.empty} role="status">
|
||||
<T>Enter a directory to search</T>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
renderItem={(r, st) => {
|
||||
const state = s.replace ? groupState(r, marks) : "pending";
|
||||
@@ -769,8 +800,9 @@ function FindInFilesDialog() {
|
||||
value={displayDirectory(s.directory, root)}
|
||||
placeholder={tx("Directory (relative to project root)")}
|
||||
aria-label={tx("Directory")}
|
||||
aria-invalid={!query || undefined}
|
||||
aria-describedby={!query ? directoryPromptId : undefined}
|
||||
spellCheck={false}
|
||||
// Keep the raw text (resolved only when searching), or a typed "/" would be stripped.
|
||||
onChange={(e) => set({ directory: e.target.value })}
|
||||
/>
|
||||
)}
|
||||
@@ -894,7 +926,7 @@ function FindInFilesDialog() {
|
||||
</Button>
|
||||
)}
|
||||
<span className={styles.okHint}>{formatBinding(hostBinding("Meta+Enter"))}</span>
|
||||
<Button disabled={!s.pattern} onClick={pin}>
|
||||
<Button disabled={!query?.pattern} onClick={pin}>
|
||||
<T>Open in Find Window</T>
|
||||
</Button>
|
||||
{s.replace && (
|
||||
|
||||
@@ -78,12 +78,12 @@ export class FindSession {
|
||||
this.update({ ...this.state, stale: true, matchCount: 0, summary: null, error: null }, true);
|
||||
}
|
||||
|
||||
/** Starts (or restarts) a search; an empty pattern resets to idle. */
|
||||
async search(query: SearchQuery): Promise<void> {
|
||||
/** Starts (or restarts) a search; missing query or pattern resets to idle. */
|
||||
async search(query: SearchQuery | null): Promise<void> {
|
||||
const seq = ++this.seq;
|
||||
this.disposed = false;
|
||||
this.cancelRunning();
|
||||
if (!query.pattern) {
|
||||
if (!query?.pattern) {
|
||||
this.update({ ...IDLE }, true);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -167,8 +167,6 @@ export function showFindPopup(replace: boolean, arg: FindArg & { selection?: str
|
||||
if (arg.directory) {
|
||||
patch.scopeTab = "directory";
|
||||
patch.directory = arg.directory;
|
||||
} else if (!s.open && s.scopeTab === "directory" && !s.directory) {
|
||||
patch.scopeTab = "project";
|
||||
}
|
||||
useFindPopup.setState(patch);
|
||||
}
|
||||
@@ -244,16 +242,18 @@ export interface ScopeInputs {
|
||||
}
|
||||
|
||||
export function resolveDirectory(dir: string, root: string | null): string {
|
||||
const d = dir.trim().replace(/\/+$/, "");
|
||||
const d = dir.trim();
|
||||
if (!d || d.startsWith("/") || /^[a-zA-Z]:[\\/]/.test(d)) return d;
|
||||
return root ? `${root}/${d}` : d;
|
||||
return root ? `${root.replace(/\/$/, "")}/${d}` : d;
|
||||
}
|
||||
|
||||
/** The backend scope of the popup's scope tabs. */
|
||||
export function resolveFindScope(o: FindOptions, inputs: ScopeInputs): SearchScope {
|
||||
export function resolveFindScope(o: FindOptions, inputs: ScopeInputs): SearchScope | null {
|
||||
const { root } = inputs;
|
||||
if (o.scopeTab === "directory" && o.directory.trim())
|
||||
return { kind: "directory", path: resolveDirectory(o.directory, root) };
|
||||
if (o.scopeTab === "directory") {
|
||||
const path = resolveDirectory(o.directory, root);
|
||||
return path ? { kind: "directory", path } : null;
|
||||
}
|
||||
if (o.scopeTab === "module")
|
||||
return o.module && root ? { kind: "directory", path: resolveDirectory(o.module, root) } : { kind: "project" };
|
||||
if (o.scopeTab !== "scope") return { kind: "project" };
|
||||
|
||||
@@ -26,7 +26,7 @@ import { sampleFileName } from "@/platform/fileTypes";
|
||||
import type { LanguageChoice } from "./backend";
|
||||
import { onIdeEvent } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { useSettingsForm } from "@/workbench/contributions";
|
||||
import { useSettingsForm, useSettingsPageFocus } from "@/workbench/contributions";
|
||||
import {
|
||||
languageNames,
|
||||
NewServerDialog,
|
||||
@@ -644,6 +644,7 @@ export function LanguageServersPage() {
|
||||
const [selectedLanguage, setSelectedLanguage] = useState<string | null>(null);
|
||||
const [selectedTool, setSelectedTool] = useState<string | null>(null);
|
||||
const [adding, setAdding] = useState(false);
|
||||
const list = useRef<HTMLUListElement>(null);
|
||||
const known = useLanguageChoices();
|
||||
const staged = form.useValue("languageServers") as Record<string, ServerEntry> | undefined;
|
||||
const servers = useMemo(() => staged ?? {}, [staged]);
|
||||
@@ -690,6 +691,29 @@ export function LanguageServersPage() {
|
||||
setSelectedTool(null);
|
||||
};
|
||||
|
||||
// Opened as `languages.servers#<tool>` (the status bar's Language Servers popup): that tool's
|
||||
// language and details.
|
||||
const { focus, consume } = useSettingsPageFocus();
|
||||
useEffect(() => {
|
||||
if (!focus) return;
|
||||
const frame = requestAnimationFrame(() => {
|
||||
setNeedsSetup(false);
|
||||
setQuery("");
|
||||
setSelectedLanguage(null);
|
||||
setSelectedTool(focus);
|
||||
consume();
|
||||
});
|
||||
return () => cancelAnimationFrame(frame);
|
||||
}, [focus, consume]);
|
||||
|
||||
const selectedName = selected?.name;
|
||||
useEffect(() => {
|
||||
if (!selectedName) return;
|
||||
list.current?.querySelector<HTMLElement>(`[data-language="${CSS.escape(selectedName)}"]`)?.scrollIntoView?.({
|
||||
block: "nearest",
|
||||
});
|
||||
}, [selectedName]);
|
||||
|
||||
const onListKey = (e: KeyboardEvent<HTMLUListElement>) => {
|
||||
if (e.key !== "ArrowDown" && e.key !== "ArrowUp") return;
|
||||
e.preventDefault();
|
||||
@@ -752,7 +776,7 @@ export function LanguageServersPage() {
|
||||
placeholder="Language or tool"
|
||||
aria-label="Filter languages"
|
||||
/>
|
||||
<ul className={styles.list} aria-label={tx("Languages")} onKeyDown={onListKey}>
|
||||
<ul ref={list} className={styles.list} aria-label={tx("Languages")} onKeyDown={onListKey}>
|
||||
{shown.map((l) => (
|
||||
<li key={l.name} className={clsx(styles.row, l === selected && styles.rowSelected)}>
|
||||
<button
|
||||
|
||||
@@ -2,7 +2,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { act, render, screen, waitFor, within } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { emitLocalIdeEvent } from "@/platform/ipc";
|
||||
import { provideNotificationService, type NotificationService } from "@/workbench/contributions";
|
||||
import {
|
||||
provideNotificationService,
|
||||
SettingsPageFocusContext,
|
||||
type NotificationService,
|
||||
} from "@/workbench/contributions";
|
||||
import { useTasks } from "@/workbench/tasks";
|
||||
import { MemoryToolsBackend, sampleTools, setToolsBackend } from "../backend";
|
||||
import { cancelInstall, installTool, refreshTools, uninstallTool, useTools } from "../store";
|
||||
@@ -450,6 +454,21 @@ describe("LanguageServersPage", () => {
|
||||
expect(within(screen.getByLabelText("ty (Python) details")).queryByRole("radio")).toBeNull();
|
||||
});
|
||||
|
||||
it("opens on the tool it was asked to show (languages.servers#<tool>)", async () => {
|
||||
const consume = vi.fn();
|
||||
render(
|
||||
<SettingsPageFocusContext.Provider value={{ focus: "pyrefly", consume }}>
|
||||
<TestSettingsForm>
|
||||
<LanguageServersPage />
|
||||
</TestSettingsForm>
|
||||
</SettingsPageFocusContext.Provider>,
|
||||
);
|
||||
await waitFor(() => expect(toolItem("pyrefly")).toHaveAttribute("aria-current", "true"));
|
||||
expect(language("Python")).toHaveAttribute("aria-current", "true");
|
||||
expect(screen.getByLabelText("Python tools")).toContainElement(toolItem("pyrefly"));
|
||||
expect(consume).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("jumps to a missing tool from the language's banner", async () => {
|
||||
const user = userEvent.setup();
|
||||
renderPage();
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
* Tools installer: Settings › Languages & Frameworks › Language Servers, plus
|
||||
* install prompts for missing language servers.
|
||||
*
|
||||
* Actions: `tools.languageServers` (open the page), `tools.install` (arg: tool name),
|
||||
* Actions: `tools.languageServers` (open the page; arg: a tool name to show), `tools.install` (arg: tool name),
|
||||
* `java.downloadJdk` (arg: `DownloadJdkArgs`).
|
||||
*/
|
||||
import { executeAction, registerActions } from "@/platform/actions";
|
||||
@@ -42,7 +42,11 @@ export function activate(): () => void {
|
||||
category: "Tools",
|
||||
icon: "package",
|
||||
keywords: ["lsp", "install", "debugger", "adapter"],
|
||||
run: () => void executeAction("file.settings", SETTINGS_PAGE_ID),
|
||||
run: ({ arg }) =>
|
||||
void executeAction(
|
||||
"file.settings",
|
||||
typeof arg === "string" ? `${SETTINGS_PAGE_ID}#${arg}` : SETTINGS_PAGE_ID,
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "tools.install",
|
||||
|
||||
@@ -67,7 +67,7 @@ import {
|
||||
import { applyStash, commitChanges, deleteFiles, dropStash, showUnstashDialog, stashChanges } from "./changeOps";
|
||||
import { CommitOptionsPopup } from "./CommitOptions";
|
||||
import { DEFAULT_LIST_NAME, useChangelists, withListDefaults } from "./changelists";
|
||||
import { inclusionChecks, isCommitAll, useStagingArea } from "./staging";
|
||||
import { inclusionChecks, isCommitAll, stagingAreaOn, useStagingArea } from "./staging";
|
||||
import { addToChangelist, commitFiles } from "./changelistsUi";
|
||||
import { acceptSide } from "./conflictsUi";
|
||||
import { copyChangesAsPatch } from "./patches";
|
||||
@@ -345,15 +345,20 @@ export function nodeMenu(
|
||||
{ kind: "separator" as const },
|
||||
]
|
||||
: []),
|
||||
{
|
||||
label: "Commit File…",
|
||||
icon: "commit",
|
||||
disabled: !files.some((f) => groupOf(f) === "changes"),
|
||||
run: () => commitFiles(paths),
|
||||
},
|
||||
{ kind: "separator" },
|
||||
// Under the modal interface the node itself, like double-click, in the front window.
|
||||
vcsDiffInFront() && opts?.roots && first
|
||||
// With the staging area a commit takes the whole index: there is no committing one file.
|
||||
...(stagingAreaOn()
|
||||
? []
|
||||
: [
|
||||
{
|
||||
label: "Commit File…",
|
||||
icon: "commit" as const,
|
||||
disabled: !files.some((f) => groupOf(f) === "changes"),
|
||||
run: () => commitFiles(paths),
|
||||
},
|
||||
{ kind: "separator" as const },
|
||||
]),
|
||||
// The node itself, like double-click: under Staged or Unstaged its side of the index.
|
||||
opts?.roots && first
|
||||
? {
|
||||
label: "Show Diff",
|
||||
icon: "diff",
|
||||
|
||||
Loaded 100 of 138 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user