дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-21 09:00:49 +02:00
Порівняти коміти
1
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
7540ef29b7 |
No files matched your search
@@ -359,9 +359,6 @@ 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).
|
||||
@@ -385,8 +382,6 @@ 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,
|
||||
@@ -758,7 +753,6 @@ impl AgentManager {
|
||||
before: BTreeMap::new(),
|
||||
saved: None,
|
||||
touched: Some(BTreeSet::new()),
|
||||
turn: None,
|
||||
subagents: Vec::new(),
|
||||
pending_rollback: 0,
|
||||
title_renamed: true,
|
||||
@@ -872,7 +866,6 @@ impl AgentManager {
|
||||
before,
|
||||
saved,
|
||||
touched: (req.isolation == Isolation::Local).then(BTreeSet::new),
|
||||
turn: None,
|
||||
subagents: Vec::new(),
|
||||
pending_rollback: 0,
|
||||
title_renamed: false,
|
||||
@@ -1196,8 +1189,6 @@ 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,
|
||||
@@ -1537,7 +1528,6 @@ 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))
|
||||
@@ -1580,47 +1570,18 @@ impl AgentManager {
|
||||
.await
|
||||
}
|
||||
|
||||
/// 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),
|
||||
}
|
||||
/// 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),
|
||||
})
|
||||
.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, as they are in `HEAD`, or as they
|
||||
/// were when its last turn started.
|
||||
/// `view` compares them: as they were when it started, or as they are in `HEAD`.
|
||||
pub async fn rollback_changes(
|
||||
&self,
|
||||
id: &str,
|
||||
@@ -1631,18 +1592,15 @@ 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, restored) = blocking(move || {
|
||||
let restamped = blocking(move || {
|
||||
let (changes, rev) = match view {
|
||||
AgentChangesView::Group => (at.grouped_changes(&before)?.uncommitted, worktree::head_commit(at.cwd())?),
|
||||
AgentChangesView::SinceStart | AgentChangesView::LastTurn => (at.changes(&before)?, at.rev()?),
|
||||
AgentChangesView::SinceStart => (at.changes(&before)?, at.rev()?),
|
||||
};
|
||||
let changes = worktree::made_by_task(changes, touched.as_deref());
|
||||
let sources = match rev.as_deref() {
|
||||
@@ -1650,7 +1608,6 @@ 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.
|
||||
@@ -1660,58 +1617,6 @@ 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)
|
||||
@@ -1847,7 +1752,6 @@ 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,
|
||||
@@ -1881,48 +1785,31 @@ impl Task {
|
||||
(s.before.clone(), s.touched.clone())
|
||||
}
|
||||
|
||||
/// 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))
|
||||
}
|
||||
|
||||
/// 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
|
||||
}
|
||||
/// 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()
|
||||
};
|
||||
self.state.lock().turn = turn;
|
||||
self.persist();
|
||||
blocking(move || worktree::snapshot(&cwd)).await.ok()
|
||||
}
|
||||
|
||||
/// 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 };
|
||||
/// 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;
|
||||
}
|
||||
{
|
||||
let mut s = self.state.lock();
|
||||
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() }));
|
||||
let Some(touched) = &s.touched else { return };
|
||||
let mut touched = (**touched).clone();
|
||||
touched.extend(changed);
|
||||
s.touched = Some(Arc::new(touched));
|
||||
}
|
||||
self.persist();
|
||||
}
|
||||
@@ -2039,7 +1926,6 @@ 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,
|
||||
@@ -2091,11 +1977,11 @@ impl Task {
|
||||
/// the user stops one. The caller set `busy`.
|
||||
async fn run(self: Arc<Self>, mut prompt: AgentPrompt) {
|
||||
loop {
|
||||
self.checkout_before_turn().await;
|
||||
let start = 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().await;
|
||||
self.record_turn_changes(start).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,8 +672,6 @@ 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,10 +2852,7 @@ 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(), AgentChangesView::SinceStart).await.unwrap().as_deref(),
|
||||
Some("original\n")
|
||||
);
|
||||
assert_eq!(mgr.base_text(&task.id, changes[0].path.0.clone()).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();
|
||||
@@ -3639,178 +3636,6 @@ 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 {
|
||||
@@ -3827,7 +3652,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"), AgentChangesView::SinceStart).await.unwrap();
|
||||
let base = mgr.base_text(&task.id, repo.dir.join("a.txt")).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:?}");
|
||||
@@ -3967,11 +3792,7 @@ 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"), AgentChangesView::SinceStart).await.unwrap(),
|
||||
None,
|
||||
"{eol:?}"
|
||||
);
|
||||
assert_eq!(mgr.base_text(&task.id, repo.dir.join("new.txt")).await.unwrap(), None, "{eol:?}");
|
||||
|
||||
mgr.rollback_changes(&task.id, None, AgentChangesView::SinceStart).await.unwrap();
|
||||
assert!(!repo.dir.join("new.txt").exists(), "{eol:?}");
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
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};
|
||||
@@ -611,6 +610,7 @@ 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,16 +626,11 @@ 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(&change.path.0, Some(rev))?
|
||||
repo.file_bytes_at(path, 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() {
|
||||
@@ -651,187 +646,6 @@ fn put(path: &Path, content: Option<Vec<u8>>) -> IdeResult<()> {
|
||||
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) {
|
||||
@@ -1001,67 +815,6 @@ 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,9 +536,7 @@ impl PathMap {
|
||||
let abs = if p.is_absolute() {
|
||||
p.to_path_buf()
|
||||
} else {
|
||||
// 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()));
|
||||
let in_base = base.map(|b| Path::new(b).join(p)).filter(|c| c.exists());
|
||||
in_base.unwrap_or_else(|| cwd.join(p))
|
||||
};
|
||||
let abs = normalize(&abs);
|
||||
@@ -1305,22 +1303,6 @@ 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,14 +1875,6 @@ 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
|
||||
|
||||
@@ -19,16 +19,10 @@ struct State {
|
||||
settings: Vec<(String, String)>,
|
||||
read_only: bool,
|
||||
session_id: String,
|
||||
session: Mutex<Session>,
|
||||
session: Mutex<bool>,
|
||||
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";
|
||||
@@ -115,23 +109,12 @@ impl ClickhousePool {
|
||||
settings: setup.params,
|
||||
read_only: source.read_only,
|
||||
session_id: uuid::Uuid::new_v4().to_string(),
|
||||
session: Mutex::new(Session::default()),
|
||||
session: Mutex::new(false),
|
||||
closed: CancellationToken::new(),
|
||||
}));
|
||||
let cancel = CancellationToken::new();
|
||||
let initialize = async {
|
||||
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);
|
||||
}
|
||||
}
|
||||
pool.execute("SELECT 1", 1, &cancel).await?;
|
||||
for sql in setup.statements {
|
||||
pool.execute(&sql, 0, &cancel).await?;
|
||||
}
|
||||
@@ -168,7 +151,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, session: &Session) -> RequestBuilder {
|
||||
fn request(&self, client: &Client, query_id: &str, max_rows: usize, initialized: bool) -> RequestBuilder {
|
||||
let mut request = client
|
||||
.post(self.0.endpoint.clone())
|
||||
.basic_auth(&self.0.user, Some(&self.0.password))
|
||||
@@ -179,20 +162,16 @@ 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 session.initialized {
|
||||
if initialized {
|
||||
request = request.query(&[("session_check", "1")]);
|
||||
} else {
|
||||
request = request.query(&[("database", &self.0.database)]);
|
||||
}
|
||||
if self.0.read_only && !session.strict_read_only {
|
||||
if self.0.read_only {
|
||||
request = request.query(&[("readonly", "1")]);
|
||||
}
|
||||
request
|
||||
@@ -221,7 +200,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)?;
|
||||
@@ -275,7 +254,7 @@ impl ClickhousePool {
|
||||
match result {
|
||||
Some(result) => {
|
||||
if result.is_ok() {
|
||||
session.initialized = true;
|
||||
*session = true;
|
||||
}
|
||||
result
|
||||
}
|
||||
@@ -344,9 +323,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 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.
|
||||
/// 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.
|
||||
struct RowReader {
|
||||
skip: usize,
|
||||
max_rows: usize,
|
||||
@@ -500,20 +479,6 @@ 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_")
|
||||
@@ -761,77 +726,6 @@ 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![(
|
||||
|
||||
@@ -369,21 +369,10 @@ 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,
|
||||
view: Option<AgentChangesView>,
|
||||
) -> IdeResult<Vec<AgentChange>> {
|
||||
pub async fn agent_changes(host: &Host, window: &str, task: String) -> IdeResult<Vec<AgentChange>> {
|
||||
host.require_trust(window)?;
|
||||
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,
|
||||
}
|
||||
host.project(window)?.agents.changes(&task).await
|
||||
}
|
||||
|
||||
/// The task's uncommitted changes and the commits made since it started.
|
||||
@@ -393,17 +382,11 @@ pub async fn agent_grouped_changes(host: &Host, window: &str, task: String) -> I
|
||||
host.project(window)?.agents.grouped_changes(&task).await
|
||||
}
|
||||
|
||||
/// Content of `path` as `view` compares it (without: when the task started), the left side of its diff.
|
||||
/// Content of `path` when the task started (left side of its diff).
|
||||
#[command(trust = trusted)]
|
||||
pub async fn agent_base_text(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
task: String,
|
||||
path: IpcPath,
|
||||
view: Option<AgentChangesView>,
|
||||
) -> IdeResult<Option<String>> {
|
||||
pub async fn agent_base_text(host: &Host, window: &str, task: String, path: IpcPath) -> IdeResult<Option<String>> {
|
||||
host.require_trust(window)?;
|
||||
host.project(window)?.agents.base_text(&task, path.into_path_buf(), view.unwrap_or_default()).await
|
||||
host.project(window)?.agents.base_text(&task, path.into_path_buf()).await
|
||||
}
|
||||
|
||||
/// Rollback: the task's changed files among `paths` (all without) back as `view` compares them.
|
||||
|
||||
@@ -359,22 +359,10 @@ pub async fn lsp_goto(host: &Host, window: &str, doc: DocId, pos: Pos, kind: Got
|
||||
if kind != GotoKind::Definition {
|
||||
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 Some((plugins, d)) = plugin_providers(host, window, doc, ProviderKind::Definition) else { return result };
|
||||
let found = plugin_call(move || plugins.provide_definition(&d, pos)).await.unwrap_or_default();
|
||||
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 found: Vec<Location> =
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -1,154 +0,0 @@
|
||||
//! ⌘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,7 +21,6 @@ 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,9 +15,6 @@ 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 {
|
||||
@@ -30,7 +27,7 @@ impl ReplaceHost for DocumentsHost<'_> {
|
||||
continue;
|
||||
}
|
||||
docs.apply_edits(doc, &edits)?;
|
||||
if save {
|
||||
if transient {
|
||||
docs.save(doc)?;
|
||||
}
|
||||
return Ok(edits.len() as u32);
|
||||
@@ -49,8 +46,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; other open documents
|
||||
/// are saved, and files that were not open are opened transiently, saved and closed.
|
||||
/// editor buffers are replaced in place and left unsaved; 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,
|
||||
|
||||
@@ -146,52 +146,3 @@ 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,28 +65,6 @@ 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 }
|
||||
@@ -315,20 +293,11 @@ 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)
|
||||
{
|
||||
@@ -732,28 +701,6 @@ 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,7 +25,6 @@ mod kotlin_lsp;
|
||||
mod launch;
|
||||
mod library_source;
|
||||
mod loading;
|
||||
mod maven_placeholder;
|
||||
mod message_requests;
|
||||
mod notebook;
|
||||
mod phoxite;
|
||||
|
||||
@@ -1,113 +0,0 @@
|
||||
//! `@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()));
|
||||
}
|
||||
}
|
||||
@@ -121,14 +121,7 @@ fn read_snapshot_text(path: &Path) -> Option<String> {
|
||||
if bytes.iter().take(8192).any(|b| *b == 0) {
|
||||
return None;
|
||||
}
|
||||
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))
|
||||
String::from_utf8(bytes).ok()
|
||||
}
|
||||
|
||||
impl LocalHistory {
|
||||
@@ -345,10 +338,7 @@ impl LocalHistory {
|
||||
return Err(IdeError::invalid(format!("invalid history id {id:?}")));
|
||||
}
|
||||
match fs::read(self.blob_path(id)) {
|
||||
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())
|
||||
}
|
||||
Ok(bytes) => Ok(String::from_utf8(bytes).unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into())),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
|
||||
Err(IdeError::not_found(format!("history snapshot {id} not found")))
|
||||
}
|
||||
@@ -542,25 +532,6 @@ 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();
|
||||
|
||||
@@ -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. 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.
|
||||
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.
|
||||
|
||||
Drag the pane's left edge to resize it. The width applies to every task and is remembered across restarts.
|
||||
|
||||
|
||||
@@ -45,16 +45,14 @@ 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 or stops responding on Linux
|
||||
## The window stays blank on Linux
|
||||
|
||||
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:
|
||||
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:
|
||||
|
||||
```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,16 +45,14 @@ Java 语言服务器(jdtls)会分析它导入的每个模块,所以大型
|
||||
|
||||
Windows 安装包目前还没有代码签名,Microsoft Defender SmartScreen 可能提示“未知发布者”。点击 **更多信息**,再点击 **仍要运行**。参见[安装](/zh/guide/install)。
|
||||
|
||||
## Linux 上窗口空白或无响应
|
||||
## Linux 上窗口一片空白
|
||||
|
||||
在部分 Wayland 环境中,WebKitGTK 的 DMA-BUF 渲染器会出错。在使用 NVIDIA 驱动的 Wayland 会话中,OpenIDEA 会为自身关闭驱动的显式同步(`__NV_DISABLE_EXPLICIT_SYNC=1`),这样既能避开问题,又能保留该渲染器。如果在其他环境下窗口一片空白、显示异常,或启动几秒后键盘和鼠标都没有反应,先退出 OpenIDEA,再在终端中关闭 DMA-BUF 渲染器启动,例如:
|
||||
在使用 NVIDIA 驱动的 Wayland 会话中,WebKitGTK 的 DMA-BUF 渲染器会出错。OpenIDEA 检测到这种组合时会自动设置 `WEBKIT_DISABLE_DMABUF_RENDERER=1`。如果在其他环境下也出现空白或显示异常的窗口,先退出 OpenIDEA,再在终端中带上这个变量启动,例如:
|
||||
|
||||
```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)。
|
||||
|
||||
+7
-24
@@ -15,24 +15,11 @@ 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` 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 })),
|
||||
/** 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 })),
|
||||
/** 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 })),
|
||||
/** 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 })),
|
||||
agentChanges: (task: string) => typedError<AgentChange[], IdeError>(__TAURI_INVOKE("agent_changes", { task })),
|
||||
/**
|
||||
* 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).
|
||||
@@ -116,9 +103,7 @@ export const commands = {
|
||||
/** 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<null, IdeError>(__TAURI_INVOKE("agent_rollback_changes", { task, paths, view })),
|
||||
"group" | 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 })),
|
||||
/**
|
||||
@@ -1310,8 +1295,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; other open documents
|
||||
* are saved, and files that were not open are opened transiently, saved and closed.
|
||||
* editor buffers are replaced in place and left unsaved; 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,
|
||||
@@ -2086,9 +2071,7 @@ export type AgentChangesView =
|
||||
/** 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";
|
||||
"group";
|
||||
|
||||
export type AgentCommand = {
|
||||
/** Without the leading `/`. */
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { registerEditorKind, setFileDecorations, type EditorKindContribution } from "@/workbench/contributions";
|
||||
import { registerEditorKind, type EditorKindContribution } from "@/workbench/contributions";
|
||||
import { t } from "@/platform/i18n";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { confirm } from "@/workbench/messages";
|
||||
@@ -166,18 +166,3 @@ 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,14 +272,6 @@ 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>();
|
||||
@@ -395,11 +387,10 @@ 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 root || s.lightEdit ? Object.values(cs.panes) : []) {
|
||||
for (const pane of Object.values(cs.panes)) {
|
||||
for (const tab of pane.tabs) {
|
||||
if (isUntitledUri(tab.input.path ?? "")) {
|
||||
carriedUntitled.push(tab);
|
||||
@@ -1449,7 +1440,8 @@ export class EditorController implements SlotHost {
|
||||
paneId,
|
||||
prefs.tabLimit,
|
||||
prefs.closingPolicy,
|
||||
tabModified,
|
||||
(tab) =>
|
||||
inputDirty(tab.input, kinds) ?? !!(tab.input.path && useDocMeta.getState()[tab.input.path]?.dirty),
|
||||
keep ?? current.panes[paneId]?.active ?? undefined,
|
||||
protect,
|
||||
)
|
||||
@@ -1733,10 +1725,13 @@ export class EditorController implements SlotHost {
|
||||
protect: (tab) => tab.pinned,
|
||||
});
|
||||
}
|
||||
/** Keeps tabs with unsaved changes or a VCS status (tabs shown as modified). */
|
||||
/** Keeps tabs with unsaved changes or a VCS status (IDEA: tabs shown as modified). */
|
||||
closeUnmodified(paneId: string): Promise<boolean> {
|
||||
return this.removeGuarded((s) => (s.panes[paneId] ? closeUnmodified(s, paneId, tabModified) : s), {
|
||||
protect: (tab) => tab.pinned || tabModified(tab),
|
||||
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),
|
||||
});
|
||||
}
|
||||
closeReadOnly(paneId: string): Promise<boolean> {
|
||||
|
||||
@@ -15,7 +15,6 @@ 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;
|
||||
@@ -159,19 +158,6 @@ 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,20 +36,6 @@ 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,19 +36,6 @@ 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);
|
||||
@@ -101,7 +88,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 = await subjectFileName(path, deps);
|
||||
const name = basename(path);
|
||||
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, topLevelTypeAt, type SuperDeps } from "./structureNav";
|
||||
import { baseName, memberAt, methodStop, superMethods, type SuperDeps } from "./structureNav";
|
||||
import { tx } from "@/platform/i18n";
|
||||
|
||||
const EDITOR_WHEN = "textEditorActive && (editorFocus || !toolWindowFocus)";
|
||||
@@ -150,10 +150,6 @@ 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, topLevelTypeAt } from "./structureNav";
|
||||
import { memberAt, methodStop, methodStops, superMethods } 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,12 +100,3 @@ 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,17 +36,6 @@ 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. */
|
||||
export function SegmentedControl({
|
||||
function SegmentedControl({
|
||||
ariaLabel,
|
||||
options,
|
||||
value,
|
||||
|
||||
@@ -1280,10 +1280,6 @@
|
||||
flex: none;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.changesScope {
|
||||
flex: none;
|
||||
padding: 6px 10px 2px;
|
||||
}
|
||||
.changesSummary {
|
||||
flex: none;
|
||||
overflow: hidden;
|
||||
|
||||
@@ -46,8 +46,6 @@ 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,
|
||||
@@ -191,10 +189,9 @@ function TaskSession({ id, docked }: { id: string; docked: boolean }) {
|
||||
{changesOpen && (
|
||||
<ChangesPane
|
||||
task={task}
|
||||
changes={scope === "turn" ? (lastTurn ?? null) : (changes ?? null)}
|
||||
commits={scope === "turn" ? [] : commits}
|
||||
grouped={grouped && scope === "task"}
|
||||
scope={scope}
|
||||
changes={changes ?? null}
|
||||
commits={commits}
|
||||
grouped={grouped}
|
||||
head={head}
|
||||
docked={docked}
|
||||
onHide={() => setChangesOpen(false)}
|
||||
|
||||
@@ -1,19 +1,15 @@
|
||||
/** 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, scope: "task", width: null };
|
||||
export const DEFAULT_CHANGES_OPTIONS: ChangesOptions = { groupByCommit: true, width: null };
|
||||
|
||||
const MIN_CHANGES_WIDTH = 200;
|
||||
const MAX_CHANGES_WIDTH = 1600;
|
||||
@@ -30,7 +26,6 @@ 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,8 +10,7 @@ import { confirm } from "@/workbench/messages";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { ChangesResizer } from "../ChangesResizer";
|
||||
import styles from "../Session.module.css";
|
||||
import { setChangesOptions, type ChangesScope } from "../changesOptions";
|
||||
import { SegmentedControl } from "../ConfigPickers";
|
||||
import { setChangesOptions } from "../changesOptions";
|
||||
import { formatSentAt } from "../conversation";
|
||||
import { branchLabel } from "../model";
|
||||
import { acceptChanges, refreshChanges, rollbackChanges, useAgents } from "../store";
|
||||
@@ -173,7 +172,6 @@ export function ChangesPane({
|
||||
changes,
|
||||
commits,
|
||||
grouped,
|
||||
scope,
|
||||
head,
|
||||
docked,
|
||||
onHide,
|
||||
@@ -182,22 +180,20 @@ export function ChangesPane({
|
||||
changes: AgentChange[] | null;
|
||||
commits: readonly AgentCommit[];
|
||||
grouped: boolean;
|
||||
scope: ChangesScope;
|
||||
head: string | null;
|
||||
docked: boolean;
|
||||
onHide: () => void;
|
||||
}) {
|
||||
// The views key their rows differently, and list different changes: a selection doesn't carry over.
|
||||
const view = scope === "turn" ? "turn" : grouped ? "grouped" : "flat";
|
||||
// The two views key their rows differently: a selection doesn't carry over.
|
||||
const [selection, setSelection] = useState<{
|
||||
view: string;
|
||||
grouped: boolean;
|
||||
keys: ReadonlySet<string>;
|
||||
}>(() => ({
|
||||
view,
|
||||
grouped,
|
||||
keys: NO_SELECTION,
|
||||
}));
|
||||
const selected = selection.view === view ? selection.keys : NO_SELECTION;
|
||||
const setSelected = (keys: ReadonlySet<string>) => setSelection({ view, keys });
|
||||
const selected = selection.grouped === grouped ? selection.keys : NO_SELECTION;
|
||||
const setSelected = (keys: ReadonlySet<string>) => setSelection({ grouped, 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(() => {
|
||||
@@ -230,17 +226,13 @@ export function ChangesPane({
|
||||
: tx`Roll back the changes to ${count} files?`}
|
||||
</p>
|
||||
<p>
|
||||
{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.",
|
||||
)}
|
||||
{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>
|
||||
</>
|
||||
),
|
||||
@@ -252,7 +244,7 @@ export function ChangesPane({
|
||||
await rollbackChanges(
|
||||
task.id,
|
||||
picked.length ? picked.map((c) => c.relPath) : null,
|
||||
scope === "turn" ? "lastTurn" : grouped ? "group" : "sinceStart",
|
||||
grouped ? "group" : "sinceStart",
|
||||
);
|
||||
setSelected(new Set());
|
||||
} catch (e) {
|
||||
@@ -264,11 +256,10 @@ export function ChangesPane({
|
||||
}
|
||||
};
|
||||
const accept = async () => {
|
||||
// Accepting brings over the task's whole work, committed or not: grouping and the last turn
|
||||
// only change the listing.
|
||||
// Accepting brings over the task's whole work, committed or not: grouping only changes the listing.
|
||||
const all =
|
||||
(grouped || scope === "turn") && !picked.length
|
||||
? await call(commands.agentChanges(task.id, null)).catch(() => changes ?? [])
|
||||
grouped && !picked.length
|
||||
? await call(commands.agentChanges(task.id)).catch(() => changes ?? [])
|
||||
: (changes ?? []);
|
||||
const targets = picked.length ? picked : all;
|
||||
const count = targets.length;
|
||||
@@ -343,7 +334,7 @@ export function ChangesPane({
|
||||
onClick={() => void rollback()}
|
||||
/>
|
||||
<IconButton icon="refresh" title="Refresh" onClick={() => void refreshChanges(task.id)} />
|
||||
{task.isolation === "worktree" && scope === "task" && (
|
||||
{task.isolation === "worktree" && (
|
||||
<IconButton
|
||||
icon="eye"
|
||||
title="View Options"
|
||||
@@ -366,29 +357,9 @@ export function ChangesPane({
|
||||
)}
|
||||
{!docked && <IconButton icon="chevron-right" title={tx("Hide changes")} size="small" onClick={onHide} />}
|
||||
</div>
|
||||
<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) && (
|
||||
{(grouped || head || task.base) && (
|
||||
<div className={styles.changesSummary}>
|
||||
{scope === "turn" ? (
|
||||
<T>Since the last turn started</T>
|
||||
) : (
|
||||
<>
|
||||
<T>vs</T> {grouped ? "HEAD" : (head ?? task.base)}
|
||||
</>
|
||||
)}
|
||||
<T>vs</T> {grouped ? "HEAD" : (head ?? task.base)}
|
||||
{changes && changes.length > 0 && (
|
||||
<>
|
||||
{" "}
|
||||
@@ -402,7 +373,7 @@ export function ChangesPane({
|
||||
<Spinner />
|
||||
) : (
|
||||
<Tree<ChangeRow>
|
||||
key={view}
|
||||
key={grouped ? "grouped" : "flat"}
|
||||
aria-label="Changed files"
|
||||
roots={rows}
|
||||
getKey={(n) => n.key}
|
||||
@@ -421,7 +392,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, scope);
|
||||
else void openChangeDiff(task, n.change.path);
|
||||
} else if (n.type === "commit") {
|
||||
void openCommitDiff(task, n.commit, n.commit.files[0]?.path ?? "");
|
||||
}
|
||||
@@ -478,7 +449,7 @@ export function ChangesPane({
|
||||
}}
|
||||
empty={
|
||||
<div className={styles.changesEmpty}>
|
||||
{scope === "turn" ? <T>The last turn changed no files</T> : <T>No changes yet</T>}
|
||||
<T>No changes yet</T>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
@@ -488,18 +459,15 @@ export function ChangesPane({
|
||||
);
|
||||
}
|
||||
|
||||
/** 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);
|
||||
/** 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);
|
||||
const paths = changed.includes(path) ? changed : [path];
|
||||
const baseLabel = scope === "turn" ? tx("Before Last Turn") : (task.base ?? "Base");
|
||||
const baseLabel = 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, scope === "turn" ? "lastTurn" : null)).catch(
|
||||
() => null,
|
||||
);
|
||||
const base = await call(commands.agentBaseText(task.id, file)).catch(() => null);
|
||||
return {
|
||||
path: file,
|
||||
left: { type: "text", text: base ?? "", label: baseLabel },
|
||||
|
||||
@@ -33,7 +33,6 @@ 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]>,
|
||||
@@ -85,8 +84,7 @@ vi.mock("@/platform/ipc", async (original) => ({
|
||||
};
|
||||
return { status: "ok", data: backend.entries.get(key) ?? [] };
|
||||
},
|
||||
agentChanges: async (_task: string, view: string | null) => {
|
||||
if (view === "lastTurn") return { status: "ok", data: backend.turnChanges };
|
||||
agentChanges: async () => {
|
||||
backend.changesCalls += 1;
|
||||
return { status: "ok", data: backend.changes };
|
||||
},
|
||||
@@ -232,13 +230,12 @@ 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, scope: "task" });
|
||||
useChangesOptions.setState({ groupByCommit: false });
|
||||
backend.imported = [];
|
||||
backend.importError = null;
|
||||
backend.importErrors = new Map();
|
||||
@@ -2973,43 +2970,6 @@ 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,8 +98,6 @@ 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[];
|
||||
@@ -188,7 +186,6 @@ export const useAgents = create<AgentsState>(() => ({
|
||||
entryLoads: new Map(),
|
||||
changes: new Map(),
|
||||
groupedChanges: new Map(),
|
||||
turnChanges: new Map(),
|
||||
providers: [],
|
||||
limits: new Map(),
|
||||
modelCatalogs: new Map(),
|
||||
@@ -499,7 +496,6 @@ 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),
|
||||
@@ -603,18 +599,12 @@ function withoutTaskCache(s: AgentsState, taskId: string): Partial<AgentsState>
|
||||
groupedChanges = new Map(s.groupedChanges);
|
||||
groupedChanges.delete(taskId);
|
||||
}
|
||||
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;
|
||||
if (!entries && !entryLoads && !changes && !groupedChanges) return null;
|
||||
return {
|
||||
...(entries ? { entries } : {}),
|
||||
...(entryLoads ? { entryLoads } : {}),
|
||||
...(changes ? { changes } : {}),
|
||||
...(groupedChanges ? { groupedChanges } : {}),
|
||||
...(turnChanges ? { turnChanges } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -635,7 +625,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) || s.turnChanges.has(taskId) || isTaskOpenInUi(taskId);
|
||||
return s.changes.has(taskId) || s.groupedChanges.has(taskId) || isTaskOpenInUi(taskId);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -677,7 +667,6 @@ export function disconnect() {
|
||||
entryLoads: new Map(),
|
||||
changes: new Map(),
|
||||
groupedChanges: new Map(),
|
||||
turnChanges: new Map(),
|
||||
modelCatalogs: new Map(),
|
||||
modelRequests: new Set(),
|
||||
modelRequestTargets: new Map(),
|
||||
@@ -857,25 +846,11 @@ 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";
|
||||
@@ -896,7 +871,7 @@ async function refreshTaskChanges(task: string, stillWanted: () => boolean): Pro
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const changes = await call(commands.agentChanges(task, null));
|
||||
const changes = await call(commands.agentChanges(task));
|
||||
if (!stillWanted()) return;
|
||||
useAgents.setState((s) => ({
|
||||
changes: new Map(s.changes).set(task, changes),
|
||||
|
||||
@@ -56,10 +56,7 @@ 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, view: string | null) => ({
|
||||
status: "ok",
|
||||
data: view === "lastTurn" ? `before the last turn: ${path}` : `base of ${path}`,
|
||||
}),
|
||||
agentBaseText: async (_task: string, path: string) => ({ status: "ok", data: `base of ${path}` }),
|
||||
agentEntries: async () => ({ status: "ok", data: await backend.entries }),
|
||||
},
|
||||
}));
|
||||
@@ -525,21 +522,6 @@ 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,23 +1,9 @@
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import type { Diagnostic, InspectEvent } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import {
|
||||
installInspectionProfileSync,
|
||||
rerunInspection,
|
||||
resetInspection,
|
||||
runInspection,
|
||||
useInspection,
|
||||
} from "./inspect";
|
||||
import { installInspectionProfileSync, resetInspection, runInspection, useInspection } from "./inspect";
|
||||
|
||||
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 } }),
|
||||
}));
|
||||
const mock = vi.hoisted(() => ({ channel: null as null | { onmessage: (event: InspectEvent) => void } }));
|
||||
vi.mock("@tauri-apps/api/core", () => ({
|
||||
Channel: class {
|
||||
onmessage = () => {};
|
||||
@@ -28,8 +14,7 @@ vi.mock("@/platform/ipc", async (original) => ({
|
||||
isTauri: () => true,
|
||||
call: (value: unknown) => value,
|
||||
commands: {
|
||||
inspectCode: (_id: unknown, scope: unknown, channel: typeof mock.channel) => {
|
||||
mock.scopes.push(scope);
|
||||
inspectCode: (_id: unknown, _scope: unknown, channel: typeof mock.channel) => {
|
||||
mock.channel = channel;
|
||||
return Promise.resolve();
|
||||
},
|
||||
@@ -112,17 +97,3 @@ 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,8 +200,7 @@ export async function runInspection(choice: ScopeChoice, profileId: ProfileId =
|
||||
summary: null,
|
||||
error: null,
|
||||
scopeLabel: describeScope(choice, scope),
|
||||
// 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,
|
||||
last: choice,
|
||||
profile: profileId,
|
||||
excluded: new Set(),
|
||||
});
|
||||
|
||||
@@ -15,8 +15,6 @@ 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> = {
|
||||
@@ -60,7 +58,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 = choice.file ?? currentFile();
|
||||
const file = currentFile();
|
||||
return file ? { kind: "files", paths: [file] } : "No file is open";
|
||||
}
|
||||
case "changed": {
|
||||
|
||||
@@ -192,20 +192,6 @@ 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"),
|
||||
@@ -806,14 +792,11 @@ describe("trust is asked before a new project window opens", () => {
|
||||
expect(windowOpenProject).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("asks once this window takes the project, before leaving its current one", async () => {
|
||||
it("asks only once, from openProject, when the project opens in this window", async () => {
|
||||
windowOpenProject.mockResolvedValue(ok({ kind: "current" }));
|
||||
await openProjectInWindow("/p/b", false);
|
||||
expect(windowOpenProject).toHaveBeenCalledWith("/p/b", false, []);
|
||||
expect(confirmProjectTrust).toHaveBeenCalledOnce();
|
||||
expect(vi.mocked(confirmProjectTrust).mock.invocationCallOrder[0]).toBeLessThan(
|
||||
vi.mocked(confirmLeaveProject).mock.invocationCallOrder[0]!,
|
||||
);
|
||||
expect(confirmProjectTrust).not.toHaveBeenCalled();
|
||||
expect(openProject).toHaveBeenCalledWith("/p/b");
|
||||
});
|
||||
});
|
||||
@@ -25,7 +25,6 @@ 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";
|
||||
@@ -101,11 +100,7 @@ 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",
|
||||
toolWindows: toolWindowsRestorable() ? "hidden" : "shown",
|
||||
};
|
||||
const params = { os, distractionFree: isDistractionFree() ? "on" : "off" };
|
||||
for (const key of keysWithPrefix("menu.")) labels[key] = t(key, params);
|
||||
const accelerators: Record<string, string> = {};
|
||||
const seen = new Set<string>();
|
||||
@@ -270,10 +265,6 @@ 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,13 +57,6 @@ 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);
|
||||
|
||||
@@ -24,18 +24,6 @@ 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 or configure them. */
|
||||
/** Status bar widget listing language servers, with a popup to restart them. */
|
||||
import { useMemo, useRef, useState } from "react";
|
||||
import clsx from "clsx";
|
||||
import { getAction, executeAction } from "@/platform/actions";
|
||||
@@ -18,7 +18,6 @@ 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 (
|
||||
<>
|
||||
@@ -93,17 +92,6 @@ 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}>
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
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,19 +179,12 @@ function BreakpointFields({
|
||||
const commitText = () => {
|
||||
const d = draft.current;
|
||||
const cond = d.condition.trim() || null;
|
||||
const changes = {
|
||||
if (cond) pushHistory("condition", cond);
|
||||
updateBreakpoint(path, bp.id, {
|
||||
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;
|
||||
@@ -403,13 +396,9 @@ 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 });
|
||||
};
|
||||
@@ -459,14 +448,8 @@ 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) => {
|
||||
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);
|
||||
}}
|
||||
onActiveChange={(i) => setSelected(rows[i]?.key ?? null)}
|
||||
onActivate={(r) => goTo(r)}
|
||||
aria-label="All breakpoints"
|
||||
className={styles.bpList}
|
||||
empty={
|
||||
@@ -539,9 +522,9 @@ function BreakpointsDialog() {
|
||||
</div>
|
||||
<div className={styles.bpDetail}>
|
||||
{current?.type === "line" ? (
|
||||
<BreakpointDetail key={current.key} row={current} onGo={() => goTo(current)} commitRef={commitRef} />
|
||||
<BreakpointDetail key={current.key} row={current} onGo={() => goTo(current)} />
|
||||
) : current?.type === "special" ? (
|
||||
<SpecialDetail key={current.key} bp={current.bp} onGo={() => goTo(current)} commitRef={commitRef} />
|
||||
<SpecialDetail key={current.key} bp={current.bp} onGo={() => goTo(current)} />
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
@@ -596,15 +579,7 @@ function ExceptionBreakpoints({ open }: { open: boolean }) {
|
||||
);
|
||||
}
|
||||
|
||||
function BreakpointDetail({
|
||||
row,
|
||||
onGo,
|
||||
commitRef,
|
||||
}: {
|
||||
row: BpRow;
|
||||
onGo: () => void;
|
||||
commitRef: MutableRefObject<(() => void) | null>;
|
||||
}) {
|
||||
function BreakpointDetail({ row, onGo }: { row: BpRow; onGo: () => void }) {
|
||||
const { path, bp } = row;
|
||||
const st = useBreakpoints((s) => s.status[bp.id]);
|
||||
return (
|
||||
@@ -622,7 +597,7 @@ function BreakpointDetail({
|
||||
</Button>
|
||||
</div>
|
||||
{st && <div className={styles.statusLine}>{st.verified ? tx("Verified") : (st.message ?? "Not verified")}</div>}
|
||||
<BreakpointFields path={path} bp={bp} commitRef={commitRef} />
|
||||
<BreakpointFields path={path} bp={bp} />
|
||||
<Checkbox
|
||||
checked={!!bp.temporary}
|
||||
onChange={(temporary) => updateBreakpoint(path, bp.id, { temporary })}
|
||||
@@ -632,34 +607,11 @@ function BreakpointDetail({
|
||||
);
|
||||
}
|
||||
|
||||
function SpecialDetail({
|
||||
bp,
|
||||
onGo,
|
||||
commitRef,
|
||||
}: {
|
||||
bp: SpecialBreakpoint;
|
||||
onGo: () => void;
|
||||
commitRef: MutableRefObject<(() => void) | null>;
|
||||
}) {
|
||||
function SpecialDetail({ bp, onGo }: { bp: SpecialBreakpoint; onGo: () => void }) {
|
||||
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}>
|
||||
|
||||
@@ -149,27 +149,19 @@ 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;
|
||||
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;
|
||||
}
|
||||
if (!useProject.getState().project || useProject.getState().project?.trusted === false || !isTauri())
|
||||
return clear();
|
||||
let collected: LibraryGroup[] = [];
|
||||
const show = (groups: LibraryGroup[]) => {
|
||||
if (id !== seq) return;
|
||||
|
||||
@@ -4,8 +4,6 @@ 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 {
|
||||
@@ -21,7 +19,6 @@ 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,
|
||||
@@ -70,20 +67,4 @@ 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();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -91,13 +91,6 @@
|
||||
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 { fireEvent, render, screen, within } from "@testing-library/react";
|
||||
import { 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,26 +48,6 @@ 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 { useEffect, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";
|
||||
import { useLayoutEffect, useMemo, useRef, useState } 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, flameStep, formatWeight, frameLocation, matchingFrames, share } from "./model";
|
||||
import { colorSlot, flameLayout, 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,28 +96,6 @@ 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;
|
||||
@@ -131,15 +109,7 @@ 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")}
|
||||
tabIndex={0}
|
||||
aria-activedescendant={`flame-frame-${shown}`}
|
||||
onKeyDown={onKeyDown}
|
||||
>
|
||||
<div className={styles.flame} style={{ height: layout.depth * ROW }} role="tree" aria-label={tx("Flame graph")}>
|
||||
{width > 0 &&
|
||||
layout.rects.map((r) => {
|
||||
const node = profile.nodes[r.node]!;
|
||||
@@ -150,24 +120,17 @@ 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={() => {
|
||||
setCurrent(r.node);
|
||||
setFocus(r.node);
|
||||
}}
|
||||
onClick={() => setFocus(r.node)}
|
||||
onDoubleClick={() => openFrame(profile, node.frame)}
|
||||
>
|
||||
{w > 28 && <span className={styles.frameText}>{label}</span>}
|
||||
|
||||
@@ -110,34 +110,6 @@ 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,7 +4,6 @@ import {
|
||||
allocationProfilerSupports,
|
||||
colorSlot,
|
||||
flameLayout,
|
||||
flameStep,
|
||||
formatWeight,
|
||||
frameLocation,
|
||||
matchingFrames,
|
||||
@@ -109,22 +108,3 @@ 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,7 +86,6 @@ import {
|
||||
VIEW_MODES,
|
||||
autoExpand,
|
||||
clearRevealRequest,
|
||||
explainHiddenPath,
|
||||
loadDir,
|
||||
loadOutline,
|
||||
revealPath,
|
||||
@@ -518,7 +517,7 @@ export function ProjectView() {
|
||||
// Select a revealed path once its row exists.
|
||||
useEffect(() => {
|
||||
if (!revealRequest) return;
|
||||
const { path, focus, seq, explain } = revealRequest;
|
||||
const { path, focus, seq } = revealRequest;
|
||||
const exact = model.keyOfPath.get(path);
|
||||
const loadingAncestors = info.pending.some((p) => p === path || isInside(path, p));
|
||||
if (!exact && loadingAncestors) return;
|
||||
@@ -529,8 +528,6 @@ 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, true);
|
||||
return revealPath(target, focus);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -7,8 +7,6 @@ import {
|
||||
reloadLoadedDirs,
|
||||
currentModel,
|
||||
expandAll,
|
||||
explainHiddenPath,
|
||||
hidingOption,
|
||||
initProjectTree,
|
||||
loadDir,
|
||||
revealPath,
|
||||
@@ -20,7 +18,6 @@ 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;
|
||||
@@ -322,28 +319,3 @@ 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,9 +10,6 @@ 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,
|
||||
@@ -125,8 +122,7 @@ interface ProjectTreeState {
|
||||
editing: Editing | null;
|
||||
clipboard: Clipboard | null;
|
||||
/** A path to select (and scroll to) once its row is visible. */
|
||||
/** `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;
|
||||
revealRequest: { path: string; focus: boolean; seq: number } | null;
|
||||
/** Folder key highlighted as drop target. */
|
||||
dropTarget: string | null;
|
||||
mode: ViewMode;
|
||||
@@ -639,7 +635,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, explain = false) {
|
||||
export function revealPath(requested: string, focus = false) {
|
||||
const { expanded } = get();
|
||||
const project = get().root;
|
||||
if (!project) return false;
|
||||
@@ -672,7 +668,7 @@ export function revealPath(requested: string, focus = false, explain = false) {
|
||||
changed = true;
|
||||
}
|
||||
if (changed) setExpanded(next);
|
||||
set({ revealRequest: { path, focus, seq: ++revealSeq, ...(explain ? { explain } : {}) } });
|
||||
set({ revealRequest: { path, focus, seq: ++revealSeq } });
|
||||
for (const a of folders) void loadDir(a);
|
||||
return true;
|
||||
}
|
||||
@@ -738,45 +734,6 @@ 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,14 +140,6 @@ 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");
|
||||
@@ -177,24 +169,6 @@ 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>
|
||||
@@ -204,7 +178,7 @@ function TrustSettings() {
|
||||
</Button>
|
||||
</div>
|
||||
<p className={styles.hint}>
|
||||
<T>Every project inside a trusted location is trusted without asking, unless it is a restricted project.</T>
|
||||
<T>Every project inside a trusted location is trusted without asking.</T>
|
||||
</p>
|
||||
{decisions?.locations.map((path) => (
|
||||
<div className={styles.row} key={path}>
|
||||
|
||||
@@ -58,13 +58,9 @@
|
||||
justify-content: space-between;
|
||||
gap: var(--space-3);
|
||||
}
|
||||
.content h3 {
|
||||
.sectionHead 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, waitFor } from "@testing-library/react";
|
||||
import { act, fireEvent, render, screen } from "@testing-library/react";
|
||||
import { confirmProjectTrust } from "@/platform/projectTrust";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { emitLocalIdeEvent } from "@/platform/ipc";
|
||||
@@ -165,24 +165,6 @@ 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,7 +36,6 @@ 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. */
|
||||
@@ -112,16 +111,6 @@ 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;
|
||||
@@ -261,11 +250,10 @@ function ConfigChooser() {
|
||||
e.key === "Delete" &&
|
||||
row?.type === "config" &&
|
||||
canDeleteConfig(row.config.id) &&
|
||||
input().selectionStart === query.length &&
|
||||
input().selectionEnd === query.length
|
||||
input().selectionStart === query.length
|
||||
) {
|
||||
e.preventDefault();
|
||||
void askDeleteConfig(row.config);
|
||||
void deleteConfig(row.config.id);
|
||||
return;
|
||||
}
|
||||
if (numbers.size && !e.altKey && !e.ctrlKey && !e.metaKey && /^Digit[1-9]$|^Numpad[1-9]$/.test(e.code)) {
|
||||
@@ -298,7 +286,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 askDeleteConfig(c) }] : []),
|
||||
...(canDeleteConfig(c.id) ? [{ label: "Delete", danger: true, run: () => void deleteConfig(c.id) }] : []),
|
||||
];
|
||||
};
|
||||
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, within } from "@testing-library/react";
|
||||
import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
|
||||
const ipc = vi.hoisted(() => ({
|
||||
runSaveConfigs: vi.fn(),
|
||||
@@ -17,7 +17,6 @@ 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 {
|
||||
@@ -142,39 +141,14 @@ 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 once confirmed", async () => {
|
||||
it("chooser popup Delete removes the selected detection", async () => {
|
||||
useRun.setState({ chooserOpen: true, editorOpen: false });
|
||||
render(
|
||||
<>
|
||||
<ConfigChooserOverlay />
|
||||
<MessagesHost />
|
||||
</>,
|
||||
);
|
||||
render(<ConfigChooserOverlay />);
|
||||
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" }));
|
||||
|
||||
@@ -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, useSettingsPageFocus } from "@/workbench/contributions";
|
||||
import { useSettingsForm } from "@/workbench/contributions";
|
||||
import {
|
||||
languageNames,
|
||||
NewServerDialog,
|
||||
@@ -644,7 +644,6 @@ 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]);
|
||||
@@ -691,29 +690,6 @@ 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();
|
||||
@@ -776,7 +752,7 @@ export function LanguageServersPage() {
|
||||
placeholder="Language or tool"
|
||||
aria-label="Filter languages"
|
||||
/>
|
||||
<ul ref={list} className={styles.list} aria-label={tx("Languages")} onKeyDown={onListKey}>
|
||||
<ul 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,11 +2,7 @@ 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,
|
||||
SettingsPageFocusContext,
|
||||
type NotificationService,
|
||||
} from "@/workbench/contributions";
|
||||
import { provideNotificationService, type NotificationService } from "@/workbench/contributions";
|
||||
import { useTasks } from "@/workbench/tasks";
|
||||
import { MemoryToolsBackend, sampleTools, setToolsBackend } from "../backend";
|
||||
import { cancelInstall, installTool, refreshTools, uninstallTool, useTools } from "../store";
|
||||
@@ -454,21 +450,6 @@ 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; arg: a tool name to show), `tools.install` (arg: tool name),
|
||||
* Actions: `tools.languageServers` (open the page), `tools.install` (arg: tool name),
|
||||
* `java.downloadJdk` (arg: `DownloadJdkArgs`).
|
||||
*/
|
||||
import { executeAction, registerActions } from "@/platform/actions";
|
||||
@@ -42,11 +42,7 @@ export function activate(): () => void {
|
||||
category: "Tools",
|
||||
icon: "package",
|
||||
keywords: ["lsp", "install", "debugger", "adapter"],
|
||||
run: ({ arg }) =>
|
||||
void executeAction(
|
||||
"file.settings",
|
||||
typeof arg === "string" ? `${SETTINGS_PAGE_ID}#${arg}` : SETTINGS_PAGE_ID,
|
||||
),
|
||||
run: () => void executeAction("file.settings", SETTINGS_PAGE_ID),
|
||||
},
|
||||
{
|
||||
id: "tools.install",
|
||||
|
||||
@@ -357,8 +357,8 @@ export function nodeMenu(
|
||||
},
|
||||
{ kind: "separator" as const },
|
||||
]),
|
||||
// The node itself, like double-click: under Staged or Unstaged its side of the index.
|
||||
opts?.roots && first
|
||||
// Under the modal interface the node itself, like double-click, in the front window.
|
||||
vcsDiffInFront() && opts?.roots && first
|
||||
? {
|
||||
label: "Show Diff",
|
||||
icon: "diff",
|
||||
|
||||
@@ -23,9 +23,6 @@ const isLabel = (e: HistoryEntry) => e.kind === "label";
|
||||
const time = (e: HistoryEntry) => e.timestampMs ?? 0;
|
||||
|
||||
/** Per file, the newest snapshot recorded before `at` (the state at a label). */
|
||||
/** The backend's label of the snapshot taken when a file is deleted (`ide-workspace::history::DELETED`). */
|
||||
const DELETED = "Deleted";
|
||||
|
||||
export function snapshotsBefore(entries: readonly HistoryEntry[], at: number): Map<string, HistoryEntry> {
|
||||
const out = new Map<string, HistoryEntry>();
|
||||
for (const e of entries) {
|
||||
@@ -116,17 +113,7 @@ export function LocalHistoryEditor({ input }: { input: EditorInput }) {
|
||||
);
|
||||
return;
|
||||
}
|
||||
// A file whose last revision before the label is its deletion was absent then: nothing to restore.
|
||||
const recorded = view.folder ? [...(atLabel?.values() ?? [])] : fileAtLabel ? [fileAtLabel] : [];
|
||||
const targets = recorded.filter((e) => e.label !== DELETED);
|
||||
if (!view.folder && fileAtLabel?.label === DELETED) {
|
||||
notifications().notify({
|
||||
level: "info",
|
||||
title: tx`${baseName(path)} did not exist at label '${current.label}'`,
|
||||
key: "localHistory.revert",
|
||||
});
|
||||
return;
|
||||
}
|
||||
const targets = view.folder ? [...(atLabel?.values() ?? [])] : fileAtLabel ? [fileAtLabel] : [];
|
||||
if (!targets.length) {
|
||||
notifications().notify({
|
||||
level: "info",
|
||||
|
||||
@@ -294,14 +294,10 @@ describe("Changes tree diffs follow the commit interface setting (#1863)", () =>
|
||||
expect(openFile).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
// The row's own diff (under Staged or Unstaged, its side of the index), in an editor tab.
|
||||
it("opens the node's diff in an editor tab with the non-modal interface", async () => {
|
||||
it("keeps the Show Diff action item with the non-modal interface", () => {
|
||||
modal(false);
|
||||
const menu = nodeMenu([node], ["/p"], { roots: [node] });
|
||||
const show = menu.find((m) => m.kind !== "separator" && "label" in m && m.label === "Show Diff");
|
||||
(show as { run: () => void }).run();
|
||||
await vi.waitFor(() => expect(openInput).toHaveBeenCalledTimes(1));
|
||||
expect(openDiffDialog).not.toHaveBeenCalled();
|
||||
expect(menu).toContainEqual({ kind: "action", action: "vcs.showDiff", arg: "/p/src/a.ts" });
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -95,14 +95,15 @@ describe("Local History", () => {
|
||||
expect(list).toHaveTextContent("src/gone.ts");
|
||||
expect(screen.getByText(/Label 'Before Git checkout' · 2 files recorded before it/)).toBeInTheDocument();
|
||||
|
||||
// Revert at the label restores every file's last revision before it; a file
|
||||
// deleted before the label was absent then and stays absent.
|
||||
// Revert at the label restores every file's last revision before it.
|
||||
fireEvent.click(screen.getByRole("button", { name: "Revert" }));
|
||||
const confirm = await screen.findByRole("dialog", { name: "Revert" });
|
||||
expect(confirm).toHaveTextContent("Revert 1 files under src to label 'Before Git checkout'?");
|
||||
fireEvent.click(within(confirm).getByRole("button", { name: "Revert" }));
|
||||
await waitFor(() => expect(historyRestore).toHaveBeenCalledTimes(1));
|
||||
expect(historyRestore).toHaveBeenCalledWith("/p/src/a.ts", id("e"));
|
||||
await waitFor(() => expect(historyRestore).toHaveBeenCalledTimes(2));
|
||||
expect(historyRestore.mock.calls.map((c) => c.join(" ")).sort()).toEqual([
|
||||
`/p/src/a.ts ${id("e")}`,
|
||||
`/p/src/gone.ts ${id("d")}`,
|
||||
]);
|
||||
|
||||
// A deleted file's row offers Restore.
|
||||
fireEvent.click(within(list).getAllByRole("option")[1]!);
|
||||
|
||||
@@ -1,32 +0,0 @@
|
||||
import { afterEach, beforeEach, expect, it, vi } from "vitest";
|
||||
import type { BranchInfo } from "@/bindings";
|
||||
import { installOperationNoticeExpiry } from "../operations";
|
||||
import { useVcs } from "../store";
|
||||
|
||||
const { expire } = vi.hoisted(() => ({ expire: vi.fn() }));
|
||||
vi.mock("@/workbench/contributions", async (original) => ({
|
||||
...(await original<typeof import("@/workbench/contributions")>()),
|
||||
notifications: () => ({ notify: vi.fn(), expire }),
|
||||
}));
|
||||
|
||||
const branch = (operation: string | null) => ({ head: "main", operation }) as unknown as BranchInfo;
|
||||
let dispose: () => void;
|
||||
|
||||
beforeEach(() => {
|
||||
expire.mockClear();
|
||||
useVcs.setState({ branch: branch("merge") });
|
||||
dispose = installOperationNoticeExpiry();
|
||||
});
|
||||
afterEach(() => dispose());
|
||||
|
||||
it("expires the conflict notice once the merge it offers to commit or abort is over", () => {
|
||||
useVcs.setState({ branch: branch("merge") });
|
||||
expect(expire).not.toHaveBeenCalled();
|
||||
useVcs.setState({ branch: branch(null) });
|
||||
expect(expire).toHaveBeenCalledWith("vcs.conflicts");
|
||||
});
|
||||
|
||||
it("keeps it while an operation is still in progress", () => {
|
||||
useVcs.setState({ branch: branch("rebase") });
|
||||
expect(expire).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -18,7 +18,6 @@ import { useChangelists } from "../changelists";
|
||||
import { useCommit } from "../commitStore";
|
||||
import { inclusionChecks, isCommitAll, stagingChecks } from "../staging";
|
||||
import { useVcs } from "../store";
|
||||
import { provideEditorService } from "@/workbench/contributions";
|
||||
|
||||
const file = (rel: string, staged: FileStatus["staged"], unstaged: FileStatus["unstaged"]): FileStatus => ({
|
||||
path: `/p/${rel}`,
|
||||
@@ -131,29 +130,6 @@ describe("staging operations of the tree's nodes", () => {
|
||||
]).toEqual([true, false]);
|
||||
});
|
||||
|
||||
it("shows a row's side of the index from Show Diff: HEAD ↔ Index under Staged, Index ↔ working copy under Unstaged", async () => {
|
||||
useSettings(true);
|
||||
const openInput = vi.fn(async () => undefined);
|
||||
provideEditorService({ openInput } as never);
|
||||
const show = (node: (typeof roots)[number]) => {
|
||||
const menu = nodeMenu([node], [], { roots });
|
||||
(menu.find((m) => "label" in m && m.label === "Show Diff") as { run: () => void }).run();
|
||||
};
|
||||
const sides = () => {
|
||||
const data = (openInput.mock.calls.at(-1) as unknown as [{ data: { left: unknown; right: unknown } }])[0].data;
|
||||
return [data.left, data.right];
|
||||
};
|
||||
show(group("staged").children!.find((n) => n.label === "Partial.kt")!);
|
||||
await vi.waitFor(() => expect(openInput).toHaveBeenCalledTimes(1));
|
||||
expect(sides()).toEqual([
|
||||
{ type: "rev", rev: "HEAD" },
|
||||
{ type: "rev", rev: ":0", label: "Index" },
|
||||
]);
|
||||
show(group("unstaged").children!.find((n) => n.label === "Partial.kt")!);
|
||||
await vi.waitFor(() => expect(openInput).toHaveBeenCalledTimes(2));
|
||||
expect(sides()).toEqual([{ type: "rev", rev: ":0", label: "Index" }, { type: "worktree" }]);
|
||||
});
|
||||
|
||||
it("has no Commit File…: a commit takes the whole index", () => {
|
||||
useSettings(true);
|
||||
const labels = (items: MenuItem[]) => items.map((i) => ("label" in i ? i.label : null));
|
||||
|
||||
@@ -60,7 +60,6 @@ import {
|
||||
showWorktrees,
|
||||
} from "./gitMenuDialogs";
|
||||
import { currentRepo, refreshNow, repoName, repoOf, statusOf, useVcs } from "./store";
|
||||
import { stagingAreaOn } from "./staging";
|
||||
import { showSyncCommitsForCurrent } from "./SyncCommitsPopup";
|
||||
import { tx } from "@/platform/i18n";
|
||||
|
||||
@@ -434,24 +433,21 @@ export function registerVcsActions(): () => void {
|
||||
}
|
||||
if (await showDirectoryWorkingDiff(paths)) return;
|
||||
const state = useVcs.getState();
|
||||
// The tree the Commit tool window shows: with the staging area, Staged / Unstaged and no lists.
|
||||
const staging = stagingAreaOn();
|
||||
const tree = buildChangeTree(
|
||||
state.status,
|
||||
state.root ?? "",
|
||||
useCommit.getState().groupByDir,
|
||||
staging ? undefined : useChangelists.getState().state,
|
||||
useChangelists.getState().state,
|
||||
state.roots,
|
||||
useCommit.getState().groupByStaging || staging,
|
||||
useCommit.getState().groupByStaging,
|
||||
undefined,
|
||||
useCommit.getState().groupByRepo,
|
||||
useCommit.getState().showUnversionedSeparately,
|
||||
);
|
||||
// The selected rows while the tree has focus: a file under Staged or Unstaged diffs that side.
|
||||
const targets = showDiffTargets(tree, paths, !argPaths(arg)?.length && commitWindowFocused());
|
||||
// The modal interface has one front diff window (#1863): a file with its group
|
||||
// as the F7 chain, or several selected files as the chain.
|
||||
if (isModalCommit()) {
|
||||
const targets = showDiffTargets(tree, paths, !argPaths(arg)?.length && commitWindowFocused());
|
||||
const [first] = targets;
|
||||
const data =
|
||||
targets.length > 1
|
||||
@@ -465,9 +461,8 @@ export function registerVcsActions(): () => void {
|
||||
await openVcsDiff({ ...data, line });
|
||||
return;
|
||||
}
|
||||
for (const target of targets.slice(0, 5)) {
|
||||
const data = typeof target === "string" ? groupDiffData(tree, target) : changeNodeDiffData(tree, target);
|
||||
await openDiff({ ...data, line }, { preview: targets.length === 1 });
|
||||
for (const path of paths.slice(0, 5)) {
|
||||
await openDiff({ ...groupDiffData(tree, path), line }, { preview: paths.length === 1 });
|
||||
}
|
||||
},
|
||||
},
|
||||
|
||||
@@ -20,7 +20,7 @@ import { registerVcsActions } from "./actions";
|
||||
import { installChangelists } from "./changelists";
|
||||
import { registerHistoryActions, trackOperationContext } from "./historyActions";
|
||||
import { registerLogPaneActions } from "./logPaneActions";
|
||||
import { controlLabel, controlOperation, inProgress, installOperationNoticeExpiry } from "./operations";
|
||||
import { controlLabel, controlOperation, inProgress } from "./operations";
|
||||
import { annotationsShown, blameSlot } from "./blame";
|
||||
import { activateRevisionAnnotations } from "./annotateRevisionProvider";
|
||||
import { inlineBlame } from "./inlineBlame";
|
||||
@@ -195,7 +195,6 @@ export function activate(): () => void {
|
||||
useCommit.setState({ signOff: workflowSettings().vcs.git.signOff });
|
||||
const disposers = [
|
||||
installVcsStore(),
|
||||
installOperationNoticeExpiry(),
|
||||
installRootSync(),
|
||||
installGitLog(),
|
||||
installDiagnosticsTracking(),
|
||||
|
||||
@@ -56,17 +56,6 @@ export function inProgress(op: string | null | undefined = useVcs.getState().bra
|
||||
return op === "rebase" || op === "merge" || op === "cherry-pick" || op === "revert" || op === "am" ? op : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Expires the conflict notices (key `vcs.conflicts`: Merge conflicts, All conflicts resolved) once
|
||||
* the merge / rebase / cherry-pick they offer to continue or abort is over, however it ended.
|
||||
*/
|
||||
export function installOperationNoticeExpiry(): () => void {
|
||||
return useVcs.subscribe((s, prev) => {
|
||||
if (inProgress(prev.branch?.operation) && !inProgress(s.branch?.operation))
|
||||
notifications().expire?.("vcs.conflicts");
|
||||
});
|
||||
}
|
||||
|
||||
/** "Rebasing main", "Merging", "Cherry-picking"… for the branch widget and banner. */
|
||||
export function operationTitle(op: InProgress, head: string | null): string {
|
||||
if (!head)
|
||||
|
||||
@@ -7,7 +7,7 @@ import { _addEditor, _removeEditor, editorContributions, type EditorDocContext }
|
||||
import { findExtension, findNext, findPrevious, makeQuery, setFindOpen, type FindOptions } from "@/editor/core/cm/find";
|
||||
import { fontZoom } from "@/editor/core/cm/prefs";
|
||||
import { seedFind, useFindOptions, useFindSessions, type FindTarget } from "@/editor/core/view/FindBar";
|
||||
import { FIND_CURRENT_HIGHLIGHT, FIND_HIGHLIGHT, SELECTION_MATCH_HIGHLIGHT, previewSelectionOf } from "./highlight";
|
||||
import { FIND_CURRENT_HIGHLIGHT, FIND_HIGHLIGHT, SELECTION_MATCH_HIGHLIGHT } from "./highlight";
|
||||
import { registerMarkdownLiveSource, useLiveMarkdown } from "./live";
|
||||
import { MarkdownEditor } from "./MarkdownEditor";
|
||||
import { useMarkdownModes } from "./modes";
|
||||
@@ -306,25 +306,3 @@ describe("Markdown preview search & selection highlights", () => {
|
||||
expect(view.state.sliceDoc(view.state.selection.main.from, view.state.selection.main.to)).toBe("second");
|
||||
});
|
||||
});
|
||||
|
||||
describe("a word selected in the preview", () => {
|
||||
it("drops the space a Windows double-click adds after the word", () => {
|
||||
const root = document.createElement("div");
|
||||
root.innerHTML = "<p>Manage <strong>Order</strong> items</p>";
|
||||
document.body.append(root);
|
||||
try {
|
||||
const strong = root.querySelector("strong")!.firstChild!;
|
||||
const after = root.querySelector("strong")!.nextSibling!;
|
||||
const range = document.createRange();
|
||||
range.setStart(strong, 0);
|
||||
range.setEnd(after, 1);
|
||||
const sel = window.getSelection()!;
|
||||
sel.removeAllRanges();
|
||||
sel.addRange(range);
|
||||
expect(previewSelectionOf(root)?.text).toBe("Order");
|
||||
expect(sel.toString()).toBe("Order");
|
||||
} finally {
|
||||
root.remove();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -276,24 +276,9 @@ export function previewSelectionOf(root: HTMLElement): { text: string; range: Ra
|
||||
if (typeof window === "undefined") return null;
|
||||
const sel = window.getSelection();
|
||||
if (!sel || sel.isCollapsed || sel.rangeCount !== 1) return null;
|
||||
let range = sel.getRangeAt(0);
|
||||
const range = sel.getRangeAt(0);
|
||||
if (!root.contains(range.commonAncestorContainer)) return null;
|
||||
let text = sel.toString();
|
||||
// Double-clicking a word on Windows selects the space after it too; the word is what was meant.
|
||||
const trailing = /^\S+(\s+)$/.exec(text)?.[1];
|
||||
if (trailing) {
|
||||
text = text.slice(0, -trailing.length);
|
||||
const end = range.endContainer;
|
||||
if (end.nodeType === Node.TEXT_NODE && range.endOffset >= trailing.length) {
|
||||
const trimmed = range.cloneRange();
|
||||
trimmed.setEnd(end, range.endOffset - trailing.length);
|
||||
if (trimmed.toString() === text) {
|
||||
sel.removeAllRanges();
|
||||
sel.addRange(trimmed);
|
||||
range = trimmed;
|
||||
}
|
||||
}
|
||||
}
|
||||
const text = sel.toString();
|
||||
if (text.length < MIN_SELECTION_LENGTH || text.length > MAX_SELECTION_LENGTH || text.includes("\n") || !text.trim())
|
||||
return null;
|
||||
return { text, range: range.cloneRange() };
|
||||
|
||||
@@ -5,11 +5,10 @@
|
||||
*/
|
||||
import { useEffect, useRef, useState, type ReactNode } from "react";
|
||||
import clsx from "clsx";
|
||||
import { useEditorRegistry } from "@/editor/api";
|
||||
import { onIdeEvent } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { FloatingToolbar, IconButton } from "@/ui";
|
||||
import { browserIcon, isWebResource, openInBrowser, useBrowsers, useWebPreview, webUrl } from "./browsers";
|
||||
import { browserIcon, openInBrowser, useBrowsers, useWebPreview, webUrl } from "./browsers";
|
||||
import styles from "./Web.module.css";
|
||||
import { tx } from "@/platform/i18n";
|
||||
|
||||
@@ -69,23 +68,19 @@ function WebPreview({ path }: { path: string }) {
|
||||
};
|
||||
}, [path]);
|
||||
|
||||
// Saved edits to the page or the project's web resources (scripts, styles, images) reload it;
|
||||
// other files (notes, sources the page doesn't load) leave its state alone.
|
||||
// Saved edits anywhere in the project (scripts, styles) reload the page.
|
||||
useEffect(() => {
|
||||
const scope = root ?? path.slice(0, path.lastIndexOf("/"));
|
||||
const affects = (p: string) => p === path || ((p.startsWith(scope + "/") || p === scope) && isWebResource(p));
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const reload = () => {
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(() => setSeq((n) => n + 1), RELOAD_DELAY);
|
||||
};
|
||||
const offFs = onIdeEvent("fsChanged", (e) => {
|
||||
if ([...e.created, ...e.modified, ...e.removed].some(affects)) reload();
|
||||
if ([...e.created, ...e.modified, ...e.removed].some((p) => p === scope || p.startsWith(scope + "/"))) reload();
|
||||
});
|
||||
const offDirty = onIdeEvent("docDirty", (e) => {
|
||||
if (e.dirty) return;
|
||||
const saved = [...useEditorRegistry.getState().editors].find((ed) => ed.ctx.doc === e.doc)?.ctx.path;
|
||||
if (!saved || affects(saved)) reload();
|
||||
if (!e.dirty) reload();
|
||||
});
|
||||
return () => {
|
||||
clearTimeout(timer);
|
||||
|
||||
@@ -2,7 +2,7 @@ import { afterEach, describe, expect, it } from "vitest";
|
||||
import type { ProjectInfo, Settings } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { textEditorWrapperFor, useTextEditorWrappers } from "@/workbench/contributions";
|
||||
import { isHtmlPath, isWebPath, isWebResource } from "./browsers";
|
||||
import { isHtmlPath, isWebPath } from "./browsers";
|
||||
import { activate } from "./index";
|
||||
|
||||
const types = (patterns: string[], removedPatterns: string[] = []) => ({ patterns, removedPatterns, hashbangs: [] });
|
||||
@@ -69,12 +69,3 @@ describe("HTML files follow File Types", () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("web resources", () => {
|
||||
it("are what a page loads, so the built-in preview reloads for them only", () => {
|
||||
for (const path of ["/p/index.html", "/p/app.css", "/p/main.js", "/p/data.json", "/p/logo.svg", "/p/a.woff2"])
|
||||
expect(isWebResource(path), path).toBe(true);
|
||||
for (const path of ["/p/notes.txt", "/p/README.md", "/p/src/Main.java"])
|
||||
expect(isWebResource(path), path).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -59,12 +59,3 @@ export async function openInBrowser(path: string, browser: string | null = null)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/** Files a page can load besides markup: styles, scripts, data, images, fonts, media. */
|
||||
const WEB_RESOURCE =
|
||||
/\.(css|m?js|cjs|jsx|tsx?|json|map|svg|png|jpe?g|gif|webp|avif|ico|bmp|woff2?|ttf|otf|eot|wasm|mp3|mp4|webm|ogg|wav)$/i;
|
||||
|
||||
/** A change to it can change what the built-in preview shows (it reloads for these only). */
|
||||
export function isWebResource(path: string): boolean {
|
||||
return isHtmlPath(path) || WEB_RESOURCE.test(path);
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { act, cleanup, render } from "@testing-library/react";
|
||||
|
||||
type Handler = (e: unknown) => void;
|
||||
const handlers = new Map<string, Handler[]>();
|
||||
vi.mock("@/platform/ipc", async (original) => ({
|
||||
...(await original<typeof import("@/platform/ipc")>()),
|
||||
onIdeEvent: (kind: string, h: Handler) => {
|
||||
handlers.set(kind, [...(handlers.get(kind) ?? []), h]);
|
||||
return () =>
|
||||
handlers.set(
|
||||
kind,
|
||||
(handlers.get(kind) ?? []).filter((x) => x !== h),
|
||||
);
|
||||
},
|
||||
}));
|
||||
vi.mock("./browsers", async (original) => ({
|
||||
...(await original<typeof import("./browsers")>()),
|
||||
webUrl: async () => "http://127.0.0.1/p/page.html",
|
||||
}));
|
||||
|
||||
const { WebEditor } = await import("./WebEditor");
|
||||
const { useWebPreview } = await import("./browsers");
|
||||
const { useProject } = await import("@/platform/project");
|
||||
|
||||
const emit = (kind: string, e: unknown) => act(() => handlers.get(kind)?.forEach((h) => h(e)));
|
||||
const fsChanged = (modified: string[]) => emit("fsChanged", { created: [], modified, removed: [] });
|
||||
|
||||
describe("the built-in HTML preview", () => {
|
||||
afterEach(cleanup);
|
||||
|
||||
it("reloads for the page and its web resources, not for unrelated files", async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
useProject.setState({ project: { root: "/p" } as never });
|
||||
useWebPreview.setState({ "/p/page.html": true });
|
||||
const { container } = render(
|
||||
<WebEditor path="/p/page.html" tabId="t">
|
||||
<div />
|
||||
</WebEditor>,
|
||||
);
|
||||
await act(async () => {});
|
||||
const frame = () => container.querySelector("iframe");
|
||||
const first = frame();
|
||||
expect(first).toBeTruthy();
|
||||
fsChanged(["/p/notes.txt", "/p/README.md"]);
|
||||
act(() => vi.advanceTimersByTime(1000));
|
||||
expect(frame()).toBe(first);
|
||||
fsChanged(["/p/style.css"]);
|
||||
act(() => vi.advanceTimersByTime(1000));
|
||||
expect(frame()).not.toBe(first);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -274,11 +274,7 @@ export function RecentList({ exclude, compact, autoFocus, onOpened, className, t
|
||||
open(items[current]);
|
||||
return;
|
||||
}
|
||||
// Delete removes the selected project only when it has no text to delete: the caret is at the end
|
||||
// of the query (⌘⌫: the query is empty). Otherwise it edits the query.
|
||||
const field = e.currentTarget;
|
||||
const atEnd = field.selectionStart === field.value.length && field.selectionEnd === field.value.length;
|
||||
if (((e.key === "Delete" && atEnd) || (e.key === "Backspace" && e.metaKey && !field.value)) && items[current]) {
|
||||
if ((e.key === "Delete" || (e.key === "Backspace" && e.metaKey)) && items[current]) {
|
||||
e.preventDefault();
|
||||
void askRemoveRecent(items[current]!.project);
|
||||
return;
|
||||
|
||||
@@ -137,18 +137,6 @@ describe("Welcome › Projects", () => {
|
||||
expect(selectedName()).toBe("py-demo");
|
||||
});
|
||||
|
||||
it("leaves Delete to the search text while the caret has text after it", async () => {
|
||||
await renderWelcome();
|
||||
const search = screen.getByLabelText("Search projects") as HTMLInputElement;
|
||||
fireEvent.change(search, { target: { value: "acme" } });
|
||||
search.setSelectionRange(1, 1);
|
||||
fireEvent.keyDown(search, { key: "Delete" });
|
||||
expect(screen.queryByRole("dialog", { name: "Remove Recent Project" })).toBeNull();
|
||||
search.setSelectionRange(4, 4);
|
||||
fireEvent.keyDown(search, { key: "Delete" });
|
||||
expect(screen.getByRole("dialog", { name: "Remove Recent Project" })).toBeTruthy();
|
||||
});
|
||||
|
||||
it("offers Open in New Window in the row menu when the action exists", async () => {
|
||||
const dispose = registerActions([{ id: "file.openInNewWindow", title: "Open in New Window", run: () => {} }]);
|
||||
await renderWelcome();
|
||||
|
||||
@@ -93,20 +93,14 @@ function translated(key: string): string | undefined {
|
||||
}
|
||||
|
||||
/** Catalog key, else the source-text catalog; `undefined` when untranslated. */
|
||||
function localized(key: string | null, text: string | undefined): string | undefined {
|
||||
function localized(key: string, text: string | undefined): string | undefined {
|
||||
if (!text) return undefined;
|
||||
const v = (key === null ? undefined : translated(key)) ?? tx(text);
|
||||
const v = translated(key) ?? tx(text);
|
||||
return v === text ? undefined : v;
|
||||
}
|
||||
|
||||
/** Titles that follow state ({@link retitleAction}), as written (English). */
|
||||
const titleOverrides = new Map<string, string>();
|
||||
|
||||
function localize(source: Action): Action {
|
||||
const override = titleOverrides.get(source.id);
|
||||
const action = override ? { ...source, title: override } : source;
|
||||
// An override is text, not the id's catalog entry (which names the registered title).
|
||||
const title = action.verbatim ? undefined : localized(override ? null : `action.${action.id}`, action.title);
|
||||
function localize(action: Action): Action {
|
||||
const title = action.verbatim ? undefined : localized(`action.${action.id}`, action.title);
|
||||
const description = localized(`action.${action.id}.description`, action.description);
|
||||
const category = localized(`action.category.${action.category}`, action.category);
|
||||
if (!title && !description && !category) return action;
|
||||
@@ -124,19 +118,6 @@ useI18n.subscribe((s, prev) => {
|
||||
useActions.setState({ actions: new Map([...sources].map(([id, a]) => [id, localize(a)])) });
|
||||
});
|
||||
|
||||
/**
|
||||
* Shows action `id` as `title` (English, translated through the text catalog) while its
|
||||
* state calls for it, e.g. Hide All Tool Windows as "Restore Tool Windows"; `undefined`
|
||||
* returns to the registered title.
|
||||
*/
|
||||
export function retitleAction(id: string, title: string | undefined) {
|
||||
if (titleOverrides.get(id) === title) return;
|
||||
if (title) titleOverrides.set(id, title);
|
||||
else titleOverrides.delete(id);
|
||||
const source = sources.get(id);
|
||||
if (source) useActions.setState((s) => ({ actions: new Map(s.actions).set(id, localize(source)) }));
|
||||
}
|
||||
|
||||
/** Adds `action` to the written sources; returns a disposer that removes it. */
|
||||
function addSource(action: Action): () => void {
|
||||
sources.set(action.id, action);
|
||||
|
||||
@@ -331,7 +331,7 @@
|
||||
"menu.toolwindow.debug": "Debug",
|
||||
"menu.toolwindow.find": "Find",
|
||||
"menu.toolwindow.git": "Git",
|
||||
"menu.toolwindow.hideAll": "{toolWindows, select, hidden {Restore Tool Windows} other {Hide All Tool Windows}}",
|
||||
"menu.toolwindow.hideAll": "Hide All Tool Windows",
|
||||
"menu.toolwindow.problems": "Problems",
|
||||
"menu.toolwindow.project": "Project",
|
||||
"menu.toolwindow.run": "Run",
|
||||
|
||||
@@ -269,7 +269,7 @@
|
||||
"menu.toolwindow.debug": "Depuración",
|
||||
"menu.toolwindow.find": "Buscar",
|
||||
"menu.toolwindow.git": "Git",
|
||||
"menu.toolwindow.hideAll": "{toolWindows, select, hidden {Restaurar ventanas de herramientas} other {Ocultar todas las ventanas de herramientas}}",
|
||||
"menu.toolwindow.hideAll": "Ocultar todas las ventanas de herramientas",
|
||||
"menu.toolwindow.problems": "Problemas",
|
||||
"menu.toolwindow.project": "Proyecto",
|
||||
"menu.toolwindow.run": "Ejecución",
|
||||
|
||||
@@ -268,7 +268,7 @@
|
||||
"menu.toolwindow.debug": "Débogage",
|
||||
"menu.toolwindow.find": "Recherche",
|
||||
"menu.toolwindow.git": "Git",
|
||||
"menu.toolwindow.hideAll": "{toolWindows, select, hidden {Restaurer les fenêtres d'outils} other {Masquer toutes les fenêtres d'outils}}",
|
||||
"menu.toolwindow.hideAll": "Masquer toutes les fenêtres d'outils",
|
||||
"menu.toolwindow.problems": "Problèmes",
|
||||
"menu.toolwindow.project": "Projet",
|
||||
"menu.toolwindow.run": "Exécution",
|
||||
|
||||
@@ -275,7 +275,7 @@
|
||||
"menu.toolwindow.debug": "디버그",
|
||||
"menu.toolwindow.find": "찾기",
|
||||
"menu.toolwindow.git": "Git",
|
||||
"menu.toolwindow.hideAll": "{toolWindows, select, hidden {도구 창 복원} other {모든 도구 창 숨기기}}",
|
||||
"menu.toolwindow.hideAll": "모든 도구 창 숨기기",
|
||||
"menu.toolwindow.problems": "문제",
|
||||
"menu.toolwindow.project": "프로젝트",
|
||||
"menu.toolwindow.run": "실행",
|
||||
|
||||
@@ -269,7 +269,7 @@
|
||||
"menu.toolwindow.debug": "Debug",
|
||||
"menu.toolwindow.find": "Znajdź",
|
||||
"menu.toolwindow.git": "Git",
|
||||
"menu.toolwindow.hideAll": "{toolWindows, select, hidden {Przywróć okna narzędziowe} other {Ukryj wszystkie okna narzędziowe}}",
|
||||
"menu.toolwindow.hideAll": "Ukryj wszystkie okna narzędziowe",
|
||||
"menu.toolwindow.problems": "Problemy",
|
||||
"menu.toolwindow.project": "Projekt",
|
||||
"menu.toolwindow.run": "Uruchom",
|
||||
|
||||
@@ -267,7 +267,7 @@
|
||||
"menu.toolwindow.debug": "Depurar",
|
||||
"menu.toolwindow.find": "Localizar",
|
||||
"menu.toolwindow.git": "Git",
|
||||
"menu.toolwindow.hideAll": "{toolWindows, select, hidden {Restaurar janelas de ferramentas} other {Ocultar todas as janelas de ferramentas}}",
|
||||
"menu.toolwindow.hideAll": "Ocultar todas as janelas de ferramentas",
|
||||
"menu.toolwindow.problems": "Problemas",
|
||||
"menu.toolwindow.project": "Projeto",
|
||||
"menu.toolwindow.run": "Executar",
|
||||
|
||||
@@ -289,13 +289,6 @@
|
||||
"They go back to how they were when the task started, in the task's worktree.": "They go back to how they were when the task started, in the task's worktree.",
|
||||
"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.": "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.",
|
||||
"They go back to the last commit; changes made after it are lost.": "They go back to the last commit; changes made after it are lost.",
|
||||
"They go back to how they were when the last turn started. Edits of yours made to them since then are lost too.": "They go back to how they were when the last turn started. Edits of yours made to them since then are lost too.",
|
||||
"Changes to show": "Changes to show",
|
||||
"Whole Task": "Whole Task",
|
||||
"Last Turn": "Last Turn",
|
||||
"Since the last turn started": "Since the last turn started",
|
||||
"The last turn changed no files": "The last turn changed no files",
|
||||
"Before Last Turn": "Before Last Turn",
|
||||
"Cannot roll back the changes": "Cannot roll back the changes",
|
||||
"Cannot connect": "Cannot connect",
|
||||
"Rollback Selected Changes…": "Rollback Selected Changes…",
|
||||
@@ -2485,14 +2478,5 @@
|
||||
"Alignment": "Alignment",
|
||||
"Align key-value pairs": "Align key-value pairs",
|
||||
"Align consecutive assignments": "Align consecutive assignments",
|
||||
"Lines up => in multi-line arrays and = in consecutive assignments after the language server or PHP-CS-Fixer formats the file; for a selection, only its lines.": "Lines up => in multi-line arrays and = in consecutive assignments after the language server or PHP-CS-Fixer formats the file; for a selection, only its lines.",
|
||||
"Are you sure you want to delete {name}?": "Are you sure you want to delete {name}?",
|
||||
"Every project inside a trusted location is trusted without asking, unless it is a restricted project.": "Every project inside a trusted location is trusted without asking, unless it is a restricted project.",
|
||||
"Restricted projects": "Restricted projects",
|
||||
"These projects open in Restricted Mode, even inside a trusted location.": "These projects open in Restricted Mode, even inside a trusted location.",
|
||||
"Trust": "Trust",
|
||||
"{name} is hidden because {title} is off": "{name} is hidden because {title} is off",
|
||||
"{name} did not exist at label '{label}'": "{name} did not exist at label '{label}'",
|
||||
"Restore Tool Windows": "Restore Tool Windows",
|
||||
"Configure {name}…": "Configure {name}…"
|
||||
"Lines up => in multi-line arrays and = in consecutive assignments after the language server or PHP-CS-Fixer formats the file; for a selection, only its lines.": "Lines up => in multi-line arrays and = in consecutive assignments after the language server or PHP-CS-Fixer formats the file; for a selection, only its lines."
|
||||
}
|
||||
@@ -261,13 +261,6 @@
|
||||
"They go back to how they were when the task started, in the task's worktree.": "它们会在任务的工作树中恢复为任务开始时的内容。",
|
||||
"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.": "它们会恢复为任务开始时的内容。任务开始后你对它们做的修改也会丢失;任务开始前的修改会保留。",
|
||||
"They go back to the last commit; changes made after it are lost.": "它们会回到最后一次提交的状态;之后的改动会丢失。",
|
||||
"They go back to how they were when the last turn started. Edits of yours made to them since then are lost too.": "它们会恢复为最近一轮开始时的内容。之后你对它们做的修改也会丢失。",
|
||||
"Changes to show": "显示的更改",
|
||||
"Whole Task": "整个任务",
|
||||
"Last Turn": "最近一轮",
|
||||
"Since the last turn started": "最近一轮开始以来",
|
||||
"The last turn changed no files": "最近一轮没有改动文件",
|
||||
"Before Last Turn": "最近一轮之前",
|
||||
"Cannot roll back the changes": "无法回滚更改",
|
||||
"Copy the changes to {name} into the local checkout?": "是否将对 {name} 的更改复制到本地检出?",
|
||||
"Copy the changes to {count} files into the local checkout?": "是否将对 {count} 个文件的更改复制到本地检出?",
|
||||
@@ -3800,6 +3793,7 @@
|
||||
"(empty line)": "(空行)",
|
||||
"Name cannot be empty": "名称不能为空",
|
||||
"Every scope needs a name": "每个范围都需要名称",
|
||||
"Every project inside a trusted location is trusted without asking.": "受信任的位置内的每个项目都会被信任,不再询问。",
|
||||
"Scopes": "范围",
|
||||
"Add Scope": "添加范围",
|
||||
"Remove Scope": "移除范围",
|
||||
@@ -8859,14 +8853,5 @@
|
||||
"Alignment": "对齐",
|
||||
"Align key-value pairs": "对齐键值对",
|
||||
"Align consecutive assignments": "对齐连续赋值",
|
||||
"Lines up => in multi-line arrays and = in consecutive assignments after the language server or PHP-CS-Fixer formats the file; for a selection, only its lines.": "在语言服务器或 PHP-CS-Fixer 格式化文件后,对齐多行数组中的 => 和连续赋值语句中的 =;格式化选区时只对齐选中的行。",
|
||||
"Are you sure you want to delete {name}?": "确定要删除 {name} 吗?",
|
||||
"Every project inside a trusted location is trusted without asking, unless it is a restricted project.": "受信任的位置内的每个项目都会被信任,不再询问;受限项目除外。",
|
||||
"Restricted projects": "受限项目",
|
||||
"These projects open in Restricted Mode, even inside a trusted location.": "这些项目即使位于受信任的位置内,也以受限模式打开。",
|
||||
"Trust": "信任",
|
||||
"{name} is hidden because {title} is off": "{name} 已隐藏,因为“{title}”已关闭",
|
||||
"{name} did not exist at label '{label}'": "标签“{label}”时 {name} 尚不存在",
|
||||
"Restore Tool Windows": "恢复工具窗口",
|
||||
"Configure {name}…": "配置 {name}…"
|
||||
"Lines up => in multi-line arrays and = in consecutive assignments after the language server or PHP-CS-Fixer formats the file; for a selection, only its lines.": "在语言服务器或 PHP-CS-Fixer 格式化文件后,对齐多行数组中的 => 和连续赋值语句中的 =;格式化选区时只对齐选中的行。"
|
||||
}
|
||||
@@ -331,7 +331,7 @@
|
||||
"menu.toolwindow.debug": "调试",
|
||||
"menu.toolwindow.find": "查找",
|
||||
"menu.toolwindow.git": "Git",
|
||||
"menu.toolwindow.hideAll": "{toolWindows, select, hidden {恢复工具窗口} other {隐藏所有工具窗口}}",
|
||||
"menu.toolwindow.hideAll": "隐藏所有工具窗口",
|
||||
"menu.toolwindow.problems": "问题",
|
||||
"menu.toolwindow.project": "项目",
|
||||
"menu.toolwindow.run": "运行",
|
||||
|
||||
@@ -8,17 +8,12 @@ import { usePlatform } from "@/platform/platformInfo";
|
||||
import { Icon, MenuList, Popup, type MenuItem } from "@/ui";
|
||||
import menuStyles from "@/ui/Menu.module.css";
|
||||
import { isDistractionFree } from "./distractionFree";
|
||||
import { toolWindowsRestorable } from "./toolwindows/store";
|
||||
import styles from "./TitleBar.module.css";
|
||||
|
||||
function label(id: string, fallback: string): string {
|
||||
const key = `menu.${id}`;
|
||||
if (lookup(key) === undefined) return fallback;
|
||||
return t(key, {
|
||||
os: usePlatform.getState().os,
|
||||
distractionFree: isDistractionFree() ? "on" : "off",
|
||||
toolWindows: toolWindowsRestorable() ? "hidden" : "shown",
|
||||
});
|
||||
return t(key, { os: usePlatform.getState().os, distractionFree: isDistractionFree() ? "on" : "off" });
|
||||
}
|
||||
|
||||
type Submenu = Extract<MenuNode, { kind: "submenu" }>;
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { showBackgroundTasks } from "./StatusBar";
|
||||
import { executeAction, getAction, registerActions } from "@/platform/actions";
|
||||
import { isCancelled, isTauri } from "@/platform/ipc";
|
||||
import { confirmProjectTrust } from "@/platform/projectTrust";
|
||||
import { isTauri } from "@/platform/ipc";
|
||||
import { closeProject, confirmLeaveProject, openProject, useProject } from "@/platform/project";
|
||||
import { runSearchFieldCommand, showContextMenu } from "@/ui";
|
||||
import { showCustomizeToolbar } from "./MainToolbarDialog";
|
||||
@@ -33,12 +32,10 @@ export async function openProjectDialog() {
|
||||
await executeAction("file.openProjectPath", path);
|
||||
return;
|
||||
}
|
||||
if (!(await confirmLeaveProject())) return;
|
||||
try {
|
||||
await confirmProjectTrust(path, "local");
|
||||
if (!(await confirmLeaveProject())) return;
|
||||
await openProject(path);
|
||||
} catch (e) {
|
||||
if (isCancelled(e)) return;
|
||||
notify({ level: "error", title: "Could not open project", body: e instanceof Error ? e.message : String(e) });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { registerAction, registerActions, retitleAction, type Action } from "@/platform/actions";
|
||||
import { registerAction, registerActions, type Action } from "@/platform/actions";
|
||||
import { setContext } from "@/platform/context";
|
||||
import { formatMessage, tx } from "@/platform/i18n";
|
||||
import { occurrenceNavigator, showStatusInfo, useContributions } from "../contributions";
|
||||
@@ -27,7 +27,6 @@ import {
|
||||
lastUsedToolWindow,
|
||||
resizeActiveToolWindow,
|
||||
setToolWindowViewMode,
|
||||
toolWindowsRestorable,
|
||||
useToolWindowLayout,
|
||||
toggleMaximizeToolWindow,
|
||||
viewModeOf,
|
||||
@@ -214,13 +213,7 @@ export function installToolWindowActions(): () => void {
|
||||
};
|
||||
|
||||
const disposeStatic = registerActions([
|
||||
{
|
||||
id: "toolwindow.hideAll",
|
||||
title: "Hide All Tool Windows",
|
||||
category: "Window",
|
||||
keywords: ["restore tool windows"],
|
||||
run: hideAllToolWindows,
|
||||
},
|
||||
{ id: "toolwindow.hideAll", title: "Hide All Tool Windows", category: "Window", run: hideAllToolWindows },
|
||||
{
|
||||
id: "toolwindow.jumpToLast",
|
||||
title: "Jump to Last Tool Window",
|
||||
@@ -319,17 +312,9 @@ export function installToolWindowActions(): () => void {
|
||||
})),
|
||||
]);
|
||||
|
||||
// Pressed again with every window hidden, Hide All restores them: its title says so.
|
||||
const retitleHideAll = () =>
|
||||
retitleAction("toolwindow.hideAll", toolWindowsRestorable() ? "Restore Tool Windows" : undefined);
|
||||
retitleHideAll();
|
||||
const unsubscribeHideAll = useToolWindowLayout.subscribe(retitleHideAll);
|
||||
|
||||
return () => {
|
||||
unsubscribe();
|
||||
unsubscribeLayouts();
|
||||
unsubscribeHideAll();
|
||||
retitleAction("toolwindow.hideAll", undefined);
|
||||
disposeStatic();
|
||||
perWindow.forEach((e) => e.dispose());
|
||||
perWindow.clear();
|
||||
|
||||
@@ -243,21 +243,6 @@ describe("tool window persistence", () => {
|
||||
});
|
||||
|
||||
describe("tool window actions", () => {
|
||||
it("titles Hide All Tool Windows 'Restore Tool Windows' while it would restore them", async () => {
|
||||
const dispose = installToolWindowActions();
|
||||
try {
|
||||
showToolWindow("terminal");
|
||||
expect(getAction("toolwindow.hideAll")?.title).toBe("Hide All Tool Windows");
|
||||
await executeAction("toolwindow.hideAll");
|
||||
expect(getAction("toolwindow.hideAll")?.title).toBe("Restore Tool Windows");
|
||||
await executeAction("toolwindow.hideAll");
|
||||
expect(isToolWindowVisible("terminal")).toBe(true);
|
||||
expect(getAction("toolwindow.hideAll")?.title).toBe("Hide All Tool Windows");
|
||||
} finally {
|
||||
dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it("registers toolwindow.<id> and generic actions", async () => {
|
||||
const dispose = installToolWindowActions();
|
||||
expect(getAction("toolwindow.terminal")?.title).toBe("Terminal");
|
||||
|
||||
@@ -557,13 +557,6 @@ export function focusToolWindow(id: string) {
|
||||
update({ focusRequest: { id, seq: ++focusSeq }, lastActive: id }, false);
|
||||
}
|
||||
|
||||
/** Whether Hide All Tool Windows would now restore the windows it hid (nothing visible, a stash kept). */
|
||||
export function toolWindowsRestorable(
|
||||
s: Pick<ToolWindowLayoutState, "visible" | "stashed"> = useToolWindowLayout.getState(),
|
||||
) {
|
||||
return !!s.stashed && !SLOTS.some((slot) => s.visible[slot]);
|
||||
}
|
||||
|
||||
/** Hides every visible window; called again with nothing visible, restores them. */
|
||||
export function hideAllToolWindows() {
|
||||
const s = useToolWindowLayout.getState();
|
||||
|
||||
Reference in new issue
Заблокувати користувача