mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-22 19:49:35 -10:00
Compare commits
36
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1e61b3b270 | ||
|
|
0809eb417c | ||
|
|
86531ee1ba | ||
|
|
54f0373acf | ||
|
|
137b1cc384 | ||
|
|
6c9d432504 | ||
|
|
2395c9544b | ||
|
|
4b55039e6e | ||
|
|
7264194b0f | ||
|
|
9ebdf0d68f | ||
|
|
0843dd8363 | ||
|
|
9935bfb7c6 | ||
|
|
db08dbc4f5 | ||
|
|
cfab86588b | ||
|
|
ba300ecbf9 | ||
|
|
1e79ccaf41 | ||
|
|
6815cb5f89 | ||
|
|
a79d551bd3 | ||
|
|
0284b7091b | ||
|
|
93143ce872 | ||
|
|
6cbb27ed82 | ||
|
|
74cf06505f | ||
|
|
d6d73e1072 | ||
|
|
bbea793adf | ||
|
|
f1c556e2ec | ||
|
|
2d99a79e69 | ||
|
|
ca778e2382 | ||
|
|
414353a5bd | ||
|
|
3080dc6100 | ||
|
|
1bb9f8d07c | ||
|
|
a539baec37 | ||
|
|
7dff6e1852 | ||
|
|
fc7fa85850 | ||
|
|
7e5a2cf051 | ||
|
|
c4e08a9676 | ||
|
|
2c0b76c9e6 |
No files matched your search
@@ -102,24 +102,44 @@ jobs:
|
||||
name: Rust (${{ matrix.os }})
|
||||
needs: changes
|
||||
if: needs.changes.outputs.rust == 'true'
|
||||
permissions:
|
||||
contents: read
|
||||
timeout-minutes: 60
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [macos-latest, ubuntu-22.04, windows-latest]
|
||||
runs-on: ${{ matrix.os }}
|
||||
# Self-hosted runners (scripts/selfhost-runner) only for trusted events, and only while the
|
||||
# SELFHOSTED_RUNNERS repository variable is 'true': runs-on cannot fall back when none is online.
|
||||
runs-on: ${{ matrix.os == 'ubuntu-22.04' && vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || matrix.os }}
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: pnpm/action-setup@v5
|
||||
with: { version: 11 }
|
||||
- uses: actions/setup-node@v5
|
||||
with: { node-version: 22, cache: pnpm }
|
||||
with:
|
||||
node-version: 22
|
||||
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
|
||||
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with: { components: "clippy, rustfmt" }
|
||||
# Only main saves the cache (saving takes minutes on Windows); PRs restore main's.
|
||||
# Self-hosted runners keep persistent local Cargo caches; GitHub-hosted runners use Actions cache
|
||||
# (only main saves it because saving takes minutes on Windows; PRs restore main's).
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
if: runner.environment != 'self-hosted'
|
||||
with:
|
||||
save-if: ${{ github.ref == 'refs/heads/main' }}
|
||||
# The persistent target dir makes incremental builds pay off; cap its size so it can't fill the disk.
|
||||
- name: Persistent Cargo target dir
|
||||
if: runner.environment == 'self-hosted'
|
||||
shell: bash
|
||||
run: |
|
||||
echo "CARGO_INCREMENTAL=1" >> "$GITHUB_ENV"
|
||||
size=$(du -sm "$CARGO_TARGET_DIR" 2>/dev/null | cut -f1 || true)
|
||||
if [ "${size:-0}" -gt 40000 ]; then
|
||||
echo "$CARGO_TARGET_DIR is ${size} MB; clearing it"
|
||||
rm -rf "$CARGO_TARGET_DIR"
|
||||
fi
|
||||
- uses: taiki-e/install-action@nextest
|
||||
- name: Linux deps
|
||||
if: runner.os == 'Linux'
|
||||
|
||||
+45
-29
@@ -38,7 +38,7 @@ pub use skill_installer::{
|
||||
};
|
||||
|
||||
use conversation::{Conversation, SavedSubagent, Session};
|
||||
use ide_core::{IdeError, IdeResult, IpcPath};
|
||||
use ide_core::{IdeError, IdeResult, IpcPath, error::ErrorKind};
|
||||
use ide_jsonrpc::{Framing, Handler, Peer, RpcError, codes};
|
||||
use ide_vcs::Repo;
|
||||
use parking_lot::{Mutex, RwLock};
|
||||
@@ -95,6 +95,8 @@ const MAX_EMBED: u64 = 256 * 1024;
|
||||
const PROBE_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
/// How long deleting a task waits for its agent to exit before removing the worktree.
|
||||
const EXIT_WAIT: Duration = Duration::from_secs(5);
|
||||
/// Change lists can each open several Git pipes; leave room for interactive VCS operations.
|
||||
const MAX_CHANGE_READS: usize = 4;
|
||||
|
||||
/// The agent tasks of one project.
|
||||
pub struct AgentManager {
|
||||
@@ -189,6 +191,7 @@ struct Shared {
|
||||
new_task_approvals: RwLock<Option<NewTaskApprovalsHook>>,
|
||||
workspace_roots: RwLock<Option<WorkspaceRootsHook>>,
|
||||
git_executable: RwLock<Option<GitExecutableHook>>,
|
||||
change_reads: Arc<tokio::sync::Semaphore>,
|
||||
known: Arc<Mutex<HashMap<String, Known>>>,
|
||||
providers: RwLock<Vec<provider::ProviderSpec>>,
|
||||
/// Last probe of each provider.
|
||||
@@ -604,6 +607,7 @@ impl AgentManager {
|
||||
new_task_approvals: RwLock::new(None),
|
||||
workspace_roots: RwLock::new(None),
|
||||
git_executable: RwLock::new(None),
|
||||
change_reads: Arc::new(tokio::sync::Semaphore::new(MAX_CHANGE_READS)),
|
||||
known,
|
||||
providers,
|
||||
probes: Mutex::new(HashMap::new()),
|
||||
@@ -1168,35 +1172,14 @@ impl AgentManager {
|
||||
|
||||
/// Drops a queued message.
|
||||
pub fn unqueue(&self, id: &str, queued: &str) -> IdeResult<AgentQueued> {
|
||||
let task = self.task(id)?;
|
||||
let item = {
|
||||
let mut s = task.state.lock();
|
||||
let i =
|
||||
s.task.queue.iter().position(|q| q.id == queued).ok_or_else(|| IdeError::not_found("already sent"))?;
|
||||
s.task.queue.remove(i)
|
||||
};
|
||||
task.persist();
|
||||
task.emit_task();
|
||||
Ok(item)
|
||||
self.task(id)?.take_queued(queued, false).map(|(item, _)| item)
|
||||
}
|
||||
|
||||
/// Sends queued message `queued` now: into the running turn when the agent takes
|
||||
/// messages mid-turn, else next, cancelling the current turn if there is one.
|
||||
pub async fn send_queued_now(&self, id: &str, queued: &str) -> IdeResult<()> {
|
||||
let task = self.task(id)?;
|
||||
let (item, busy) = {
|
||||
let mut s = task.state.lock();
|
||||
let i =
|
||||
s.task.queue.iter().position(|q| q.id == queued).ok_or_else(|| IdeError::not_found("already sent"))?;
|
||||
let item = s.task.queue.remove(i);
|
||||
let busy = s.busy;
|
||||
if !busy {
|
||||
s.busy = true;
|
||||
}
|
||||
(item, busy)
|
||||
};
|
||||
task.persist();
|
||||
task.emit_task();
|
||||
let (item, busy) = task.take_queued(queued, true)?;
|
||||
if !busy {
|
||||
self.shared.runtime.spawn(async move { task.run(item.prompt).await });
|
||||
return Ok(());
|
||||
@@ -1847,7 +1830,7 @@ impl AgentManager {
|
||||
let task = self.task(id)?;
|
||||
let at = task.base();
|
||||
let (before, touched) = task.attribution();
|
||||
vcs(&self.shared, move || Ok(worktree::made_by_task(at.changes(&before)?, touched.as_deref()))).await
|
||||
read_changes(&self.shared, move || at.changes(&before, touched.as_deref())).await
|
||||
}
|
||||
|
||||
/// The task's uncommitted changes and, for a worktree task, the commits made since it
|
||||
@@ -1856,7 +1839,7 @@ impl AgentManager {
|
||||
let task = self.task(id)?;
|
||||
let at = task.base();
|
||||
let (before, touched) = task.attribution();
|
||||
vcs(&self.shared, move || {
|
||||
read_changes(&self.shared, move || {
|
||||
let mut grouped = at.grouped_changes(&before)?;
|
||||
grouped.uncommitted = worktree::made_by_task(grouped.uncommitted, touched.as_deref());
|
||||
Ok(grouped)
|
||||
@@ -1869,7 +1852,7 @@ impl AgentManager {
|
||||
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()) };
|
||||
vcs(&self.shared, move || {
|
||||
read_changes(&self.shared, move || {
|
||||
let changed = match &turn.changed {
|
||||
Some(changed) => changed.clone(),
|
||||
None => worktree::changed_in_turn(&cwd, &turn)?.1,
|
||||
@@ -1926,7 +1909,7 @@ impl AgentManager {
|
||||
let (restamped, restored) = vcs(&self.shared, 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 | AgentChangesView::LastTurn => (at.changes(&before, None)?, at.rev()?),
|
||||
};
|
||||
let changes = worktree::made_by_task(changes, touched.as_deref());
|
||||
let sources = match rev.as_deref() {
|
||||
@@ -2341,6 +2324,23 @@ impl Task {
|
||||
self.shared.emit(AgentEvent::Task { task: Box::new(task) });
|
||||
}
|
||||
|
||||
/// Takes the item and, for Send now, claims an idle turn under the same lock.
|
||||
fn take_queued(&self, id: &str, for_send: bool) -> IdeResult<(AgentQueued, bool)> {
|
||||
let mut s = self.state.lock();
|
||||
let Some(index) = s.task.queue.iter().position(|item| item.id == id) else {
|
||||
drop(s);
|
||||
self.emit_task();
|
||||
return Err(IdeError::new(ErrorKind::OutOfSync, "Message is no longer queued"));
|
||||
};
|
||||
let item = s.task.queue.remove(index);
|
||||
let was_busy = s.busy;
|
||||
s.busy |= for_send;
|
||||
drop(s);
|
||||
self.persist();
|
||||
self.emit_task();
|
||||
Ok((item, was_busy))
|
||||
}
|
||||
|
||||
/// Shows (or clears) the agent's pending retry; emitted only when it changes.
|
||||
fn set_retry(&self, retry: Option<AgentRetry>) {
|
||||
{
|
||||
@@ -2549,7 +2549,10 @@ impl Task {
|
||||
self.push_entry(AgentEntry::Error { message: "The agent declined to continue.".into() });
|
||||
}
|
||||
match (next, result) {
|
||||
(Some(queued), _) => prompt = queued.prompt,
|
||||
(Some(queued), _) => {
|
||||
self.emit_task();
|
||||
prompt = queued.prompt;
|
||||
}
|
||||
(None, Ok(stop)) => {
|
||||
self.set_status(AgentStatus::Ready, None);
|
||||
if stop != "cancelled" {
|
||||
@@ -4270,6 +4273,19 @@ async fn vcs<T: Send + 'static>(shared: &Shared, f: impl FnOnce() -> IdeResult<T
|
||||
blocking(move || ide_vcs::with_git_executable(git.as_deref(), f)).await
|
||||
}
|
||||
|
||||
async fn read_changes<T: Send + 'static>(
|
||||
shared: &Shared,
|
||||
f: impl FnOnce() -> IdeResult<T> + Send + 'static,
|
||||
) -> IdeResult<T> {
|
||||
let permit = shared.change_reads.clone().acquire_owned().await.map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
vcs(shared, move || {
|
||||
// Dropping the caller doesn't cancel a blocking job. Keep the slot with the work.
|
||||
let _permit = permit;
|
||||
f()
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod replay;
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -452,6 +452,57 @@ fn manager(dir: &Path, agent: Arc<FakeAgent>) -> AgentManager {
|
||||
manager_at(dir, &dir.join("models.json"), agent)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn change_reads_share_a_budget_until_the_blocking_work_finishes() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::default());
|
||||
let submitted = Arc::new(AtomicU32::new(0));
|
||||
mgr.set_git_executable_hook(Arc::new({
|
||||
let submitted = submitted.clone();
|
||||
move || {
|
||||
submitted.fetch_add(1, Ordering::SeqCst);
|
||||
None
|
||||
}
|
||||
}));
|
||||
let (started, mut starts) = tokio::sync::mpsc::unbounded_channel();
|
||||
let (finished, mut finishes) = tokio::sync::mpsc::unbounded_channel();
|
||||
let mut releases = Vec::new();
|
||||
let mut reads = Vec::new();
|
||||
for job in 0..12 {
|
||||
let (release, gate) = tokio::sync::oneshot::channel::<()>();
|
||||
releases.push(release);
|
||||
let (started, finished) = (started.clone(), finished.clone());
|
||||
let mut read = Box::pin(read_changes(&mgr.shared, move || {
|
||||
started.send(()).unwrap();
|
||||
gate.blocking_recv().unwrap();
|
||||
finished.send(()).unwrap();
|
||||
Ok(())
|
||||
}));
|
||||
tokio::select! { biased; _ = &mut read => panic!("read finished before release"), _ = std::future::ready(()) => {} }
|
||||
reads.push(read);
|
||||
if job == 0 {
|
||||
// Cancelling the requester cannot stop the blocking job or free its slot.
|
||||
starts.recv().await.unwrap();
|
||||
drop(reads.pop());
|
||||
}
|
||||
}
|
||||
let admitted = submitted.load(Ordering::SeqCst);
|
||||
for _ in 1..admitted {
|
||||
starts.recv().await.unwrap();
|
||||
}
|
||||
for release in releases {
|
||||
release.send(()).unwrap();
|
||||
}
|
||||
for read in reads {
|
||||
read.await.unwrap();
|
||||
}
|
||||
for _ in 0..12 {
|
||||
finishes.recv().await.unwrap();
|
||||
}
|
||||
eprintln!("change-read fixture: peak active {admitted}; completed 12/12");
|
||||
assert_eq!(admitted, 4);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn subscribers_do_not_replace_or_close_each_other() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -1375,6 +1426,46 @@ async fn steers_through_session_steering() {
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn stale_queue_actions_refresh_the_queue_without_starting_another_turn() {
|
||||
use ide_core::error::ErrorKind;
|
||||
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let task = mgr
|
||||
.create(NewAgentTask { provider: "claude".into(), prompt: text("ask"), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
|
||||
mgr.prompt(&task.id, text("again"), false).await.unwrap();
|
||||
let handle = mgr.task(&task.id).unwrap();
|
||||
let queued = handle.state.lock().task.queue[0].id.clone();
|
||||
let permission = *handle.permissions.lock().keys().next().unwrap();
|
||||
let (tx, mut updates) = tokio::sync::mpsc::unbounded_channel();
|
||||
let weak = Arc::downgrade(&handle);
|
||||
mgr.subscribe(Arc::new(move |event| {
|
||||
if let AgentEvent::Task { task } = event
|
||||
&& task.queue.is_empty()
|
||||
&& let Some(handle) = weak.upgrade()
|
||||
{
|
||||
let _ = tx.send(handle.turns.load(Ordering::Acquire));
|
||||
}
|
||||
}));
|
||||
mgr.respond(&task.id, permission, Some("yes".into())).unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
assert_eq!(updates.try_recv().unwrap(), 1, "publish the dequeue before starting the second turn");
|
||||
while updates.try_recv().is_ok() {}
|
||||
|
||||
for error in
|
||||
[mgr.unqueue(&task.id, &queued).unwrap_err(), mgr.send_queued_now(&task.id, &queued).await.unwrap_err()]
|
||||
{
|
||||
assert_eq!(error.kind, ErrorKind::OutOfSync);
|
||||
assert_eq!(updates.try_recv().unwrap(), 2, "a stale action gets the current queue");
|
||||
}
|
||||
assert!(!handle.state.lock().busy);
|
||||
assert_eq!(mgr.unqueue("missing-task", &queued).unwrap_err().kind, ErrorKind::NotFound);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn messages_sent_while_busy_are_queued_and_send_now_interrupts() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -65,7 +65,7 @@ impl TurnRepos {
|
||||
|
||||
/// The innermost repository holding `path`.
|
||||
fn owner(&self, path: &Path) -> Option<&Repo> {
|
||||
self.repos.iter().filter(|r| path.starts_with(r.root())).max_by_key(|r| r.root().as_os_str().len())
|
||||
owning_repo(&self.repos, path)
|
||||
}
|
||||
|
||||
/// `repo`'s `HEAD` as the turn `start` began.
|
||||
@@ -78,6 +78,10 @@ fn root_key(root: &Path) -> String {
|
||||
root.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
fn owning_repo<'a>(repos: &'a [Repo], path: &Path) -> Option<&'a Repo> {
|
||||
repos.iter().filter(|r| path.starts_with(r.root())).max_by_key(|r| r.root().as_os_str().len())
|
||||
}
|
||||
|
||||
/// `path` as a task in `base` names it, if it is not in a repository nested below `repo` (that
|
||||
/// one lists it itself; to `repo` its folder is untracked).
|
||||
fn nested_rel(base: &Path, repo: &Repo, roots: &[PathBuf], path: &Path) -> Option<String> {
|
||||
@@ -91,11 +95,25 @@ fn nested_rel(base: &Path, repo: &Repo, roots: &[PathBuf], path: &Path) -> Optio
|
||||
}
|
||||
|
||||
/// The uncommitted changes in every repository of the project, against each one's `HEAD`.
|
||||
fn nested_changes(cwd: &Path) -> IdeResult<Vec<AgentChange>> {
|
||||
let Some((base, repos)) = nested_repos(cwd)? else { return Ok(Vec::new()) };
|
||||
fn nested_changes(base: &Path, repos: &[Repo], touched: Option<&BTreeSet<String>>) -> IdeResult<Vec<AgentChange>> {
|
||||
let roots: Vec<PathBuf> = repos.iter().map(|r| r.root().to_path_buf()).collect();
|
||||
// Match deletions too: find the owner by path components, not by opening the file.
|
||||
// Display paths use slash separators and lossy Unicode (see nested_rel). If a checkout's
|
||||
// name cannot round-trip from that representation, keep the full-read fallback.
|
||||
let owners = touched
|
||||
.filter(|_| {
|
||||
roots.iter().all(|root| {
|
||||
root.strip_prefix(base).is_ok_and(|rel| base.join(rel.to_string_lossy().replace('\\', "/")) == *root)
|
||||
})
|
||||
})
|
||||
.map(|paths| {
|
||||
paths.iter().filter_map(|rel| owning_repo(repos, &base.join(rel)).map(Repo::root)).collect::<BTreeSet<_>>()
|
||||
});
|
||||
let mut out: Vec<AgentChange> = Vec::new();
|
||||
for repo in &repos {
|
||||
for repo in repos {
|
||||
if owners.as_ref().is_some_and(|owners| !owners.contains(repo.root())) {
|
||||
continue;
|
||||
}
|
||||
let listed = match repo.head()?.1 {
|
||||
Some(head) => changes(repo.root(), &head)?,
|
||||
None => {
|
||||
@@ -103,7 +121,7 @@ fn nested_changes(cwd: &Path) -> IdeResult<Vec<AgentChange>> {
|
||||
}
|
||||
};
|
||||
for mut c in listed {
|
||||
let Some(rel) = nested_rel(&base, repo, &roots, &c.path.0) else { continue };
|
||||
let Some(rel) = nested_rel(base, repo, &roots, &c.path.0) else { continue };
|
||||
if out.iter().any(|o| o.path == c.path) {
|
||||
continue;
|
||||
}
|
||||
@@ -364,13 +382,30 @@ impl TaskBase {
|
||||
}
|
||||
|
||||
/// The files the task changed, less those changed before it started and untouched since.
|
||||
pub(crate) fn changes(&self, before: &BTreeMap<String, Stamp>) -> IdeResult<Vec<AgentChange>> {
|
||||
pub(crate) fn changes(
|
||||
&self,
|
||||
before: &BTreeMap<String, Stamp>,
|
||||
touched: Option<&BTreeSet<String>>,
|
||||
) -> IdeResult<Vec<AgentChange>> {
|
||||
if touched.is_some_and(BTreeSet::is_empty) {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
Ok(made_by_task(self.read_changes(before, touched)?, touched))
|
||||
}
|
||||
|
||||
fn read_changes(
|
||||
&self,
|
||||
before: &BTreeMap<String, Stamp>,
|
||||
touched: Option<&BTreeSet<String>>,
|
||||
) -> IdeResult<Vec<AgentChange>> {
|
||||
let (cwd, start) = match self {
|
||||
Self::Worktree { cwd, base } => return Ok(without_untouched(changes(cwd, base)?, before)),
|
||||
Self::Local { cwd, .. } if spans_repos(cwd) => {
|
||||
return Ok(without_untouched(nested_changes(cwd)?, before));
|
||||
Self::Local { cwd, start } => {
|
||||
if let Some((base, repos)) = nested_repos(cwd)? {
|
||||
return Ok(without_untouched(nested_changes(&base, &repos, touched)?, before));
|
||||
}
|
||||
(cwd, start.as_deref())
|
||||
}
|
||||
Self::Local { cwd, start } => (cwd, start.as_deref()),
|
||||
};
|
||||
let Some(repo) = discover(cwd)? else { return Ok(Vec::new()) };
|
||||
// What is uncommitted, as the Commit tool window lists it: commits made since the task
|
||||
@@ -429,7 +464,7 @@ impl TaskBase {
|
||||
pub(crate) fn grouped_changes(&self, before: &BTreeMap<String, Stamp>) -> IdeResult<AgentChanges> {
|
||||
let cwd = self.cwd();
|
||||
if spans_repos(cwd) {
|
||||
return Ok(AgentChanges { uncommitted: self.changes(before)?, commits: Vec::new() });
|
||||
return Ok(AgentChanges { uncommitted: self.changes(before, None)?, commits: Vec::new() });
|
||||
}
|
||||
let Some(repo) = discover(cwd)? else { return Ok(AgentChanges::default()) };
|
||||
let head = repo.head()?.1;
|
||||
@@ -1122,6 +1157,57 @@ mod tests {
|
||||
assert!(ok, "git {args:?}");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn attributed_changes_only_diff_the_owning_checkout() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap().join("project");
|
||||
for n in 0..15 {
|
||||
let repo = root.join(format!("repo{n:02}"));
|
||||
std::fs::create_dir_all(&repo).unwrap();
|
||||
git(&repo, &["init", "-q", "-b", "main"]);
|
||||
std::fs::write(repo.join("a.txt"), "one\n").unwrap();
|
||||
git(&repo, &["add", "a.txt"]);
|
||||
git(&repo, &["commit", "-q", "-m", "initial"]);
|
||||
std::fs::write(repo.join("a.txt"), "two\n").unwrap();
|
||||
}
|
||||
// Count real Git diff processes, not walks to discover the topology.
|
||||
let git = tmp.path().join("count-git");
|
||||
let log = tmp.path().join("count-git.log");
|
||||
std::fs::write(
|
||||
&git,
|
||||
"#!/bin/sh\nfor arg do\nif [ \"$arg\" = diff ]; then pwd >> \"$0.log\"; break; fi\ndone\nexec git \"$@\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::set_permissions(&git, std::fs::Permissions::from_mode(0o700)).unwrap();
|
||||
let at = TaskBase::Local { cwd: root, start: None };
|
||||
let before = BTreeMap::new();
|
||||
let one = BTreeSet::from(["repo07/a.txt".to_owned()]);
|
||||
let read = |touched: Option<&BTreeSet<String>>| {
|
||||
std::fs::write(&log, "").unwrap();
|
||||
let start = std::time::Instant::now();
|
||||
let changes = ide_vcs::with_git_executable(Some(&git), || at.changes(&before, touched).unwrap());
|
||||
let elapsed = start.elapsed();
|
||||
let calls = std::fs::read_to_string(&log).unwrap();
|
||||
eprintln!("change read: touched={:?} elapsed={elapsed:?}", touched.map(BTreeSet::len));
|
||||
(changes, calls.lines().count())
|
||||
};
|
||||
let (all, full_calls) = read(None);
|
||||
let (selected, selected_calls) = read(Some(&one));
|
||||
let (empty, empty_calls) = read(Some(&BTreeSet::new()));
|
||||
assert_eq!(all.len(), 15);
|
||||
assert_eq!(
|
||||
serde_json::to_value(selected).unwrap(),
|
||||
serde_json::to_value(made_by_task(all, Some(&one))).unwrap()
|
||||
);
|
||||
assert!(empty.is_empty());
|
||||
eprintln!("git diff children: full {full_calls}, one touched {selected_calls}, none touched {empty_calls}");
|
||||
assert!(selected_calls > 0);
|
||||
assert_eq!(selected_calls * 15, full_calls);
|
||||
assert_eq!(empty_calls, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_project_with_nested_repositories_sees_changes_in_each_one() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -1144,7 +1230,7 @@ mod tests {
|
||||
std::fs::write(nested.join("b.txt"), "new\n").unwrap();
|
||||
std::fs::write(deeper.join("a.txt"), "two\n").unwrap();
|
||||
let at = TaskBase::Local { cwd: root.clone(), start: None };
|
||||
let changed = at.changes(&before).unwrap();
|
||||
let changed = at.changes(&before, None).unwrap();
|
||||
let listed: Vec<(&str, &Path)> =
|
||||
changed.iter().map(|c| (c.rel_path.as_str(), c.repo.as_ref().unwrap().0.as_path())).collect();
|
||||
assert_eq!(
|
||||
@@ -1168,6 +1254,12 @@ mod tests {
|
||||
}
|
||||
assert!(!nested.join("b.txt").exists());
|
||||
assert!(root.join("mine.txt").exists(), "the user's own change stays");
|
||||
// A deleted file cannot be canonicalized, but still belongs to its innermost repo.
|
||||
std::fs::remove_file(deeper.join("a.txt")).unwrap();
|
||||
let removed = at.changes(&before, Some(&BTreeSet::from(["libs/validation/pkg/sdk/a.txt".into()]))).unwrap();
|
||||
assert_eq!(removed.len(), 1);
|
||||
assert_eq!(removed[0].repo.as_ref().unwrap().0, deeper);
|
||||
assert_eq!(removed[0].kind, ChangeKind::Deleted);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -24,6 +24,21 @@ pub(crate) const MAX_LINE_BYTES: usize = 1024 * 1024;
|
||||
/// `Output::text` stops growing past this while the pipes keep draining: a chatty build can
|
||||
/// print far more than is ever parsed back out of the retained copy.
|
||||
pub(crate) const MAX_TEXT_BYTES: usize = 32 * 1024 * 1024;
|
||||
/// Lines the pipe readers may queue ahead of the consumer. A build printing faster than
|
||||
/// `on_line` takes its lines waits on its full pipe, as it would on a terminal, instead of
|
||||
/// the lines piling up in memory (a line is at most [`MAX_LINE_BYTES`] in [`run_bounded`]).
|
||||
const LINE_QUEUE: usize = 64;
|
||||
/// What [`pump_bounded`] reads from a pipe at a time.
|
||||
const PUMP_CHUNK: usize = 64 * 1024;
|
||||
|
||||
/// One line of a child's output, with the stream it came from.
|
||||
type Line = (Stream, String);
|
||||
|
||||
/// The queue from the pipe readers to the consumer: bounded, so the readers wait while the
|
||||
/// consumer is behind.
|
||||
fn line_queue() -> (mpsc::SyncSender<Line>, mpsc::Receiver<Line>) {
|
||||
mpsc::sync_channel(LINE_QUEUE)
|
||||
}
|
||||
|
||||
pub(crate) struct Output {
|
||||
pub success: bool,
|
||||
@@ -33,20 +48,20 @@ pub(crate) struct Output {
|
||||
pub truncated: bool,
|
||||
}
|
||||
|
||||
/// Bounded pump for callers that stream every line and only summarize errors: reads fixed
|
||||
/// 64 KiB chunks, splits newline-free runs at a UTF-8 char boundary at the line cap, and
|
||||
/// never grows one line buffer without bound.
|
||||
fn pump_bounded(stream: Box<dyn Read + Send>, kind: Stream, tx: &mpsc::Sender<(Stream, String)>) {
|
||||
/// Bounded pump for callers that stream every line and only summarize errors: reads
|
||||
/// [`PUMP_CHUNK`] chunks, splits newline-free runs at a UTF-8 char boundary at the line cap,
|
||||
/// and never grows one line buffer without bound.
|
||||
fn pump_bounded(stream: Box<dyn Read + Send>, kind: Stream, tx: &mpsc::SyncSender<Line>) {
|
||||
let mut reader = BufReader::new(stream);
|
||||
// `terminated`: the buffer ends in the stream's newline. A segment cut from a
|
||||
// newline-free run at the line cap must keep a trailing `\r` — it is data.
|
||||
let send = |buf: &mut Vec<u8>, terminated: bool, tx: &mpsc::Sender<(Stream, String)>| {
|
||||
let send = |buf: &mut Vec<u8>, terminated: bool, tx: &mpsc::SyncSender<Line>| {
|
||||
let line = ide_core::output_encoding::decode_tool_output(buf);
|
||||
let line = if terminated { line.trim_end_matches(['\n', '\r']).to_owned() } else { line };
|
||||
buf.clear();
|
||||
tx.send((kind, line)).is_ok()
|
||||
};
|
||||
let mut chunk = vec![0u8; 64 * 1024];
|
||||
let mut chunk = vec![0u8; PUMP_CHUNK];
|
||||
let mut line: Vec<u8> = Vec::with_capacity(256);
|
||||
'read: loop {
|
||||
let n = match reader.read(&mut chunk) {
|
||||
@@ -179,8 +194,8 @@ fn run_with_env_capture(
|
||||
}
|
||||
let mut child =
|
||||
command.spawn().map_err(|e| IdeError::unavailable(format!("cannot start {}: {e}", program.display())))?;
|
||||
let (tx, rx) = mpsc::channel::<(Stream, String)>();
|
||||
let pump = |stream: Box<dyn Read + Send>, kind: Stream, tx: mpsc::Sender<(Stream, String)>| {
|
||||
let (tx, rx) = line_queue();
|
||||
let pump = |stream: Box<dyn Read + Send>, kind: Stream, tx: mpsc::SyncSender<Line>| {
|
||||
std::thread::spawn(move || {
|
||||
if bounded {
|
||||
pump_bounded(stream, kind, &tx);
|
||||
@@ -212,7 +227,8 @@ fn run_with_env_capture(
|
||||
// Retained copy of the output: the first half of the cap, then — once output overflows —
|
||||
// a rolling tail instead of the middle. Error summaries read the end of the output, while
|
||||
// listings parsed out of a successful run read from the start. The pipes keep draining
|
||||
// either way: `on_line` still sees every line, so the child never blocks on a full pipe.
|
||||
// either way: `on_line` still sees every line, and the child waits on its pipe only
|
||||
// while `on_line` is behind, never because the retained copy is full.
|
||||
let cap = MAX_TEXT_BYTES / 2;
|
||||
let mut head = String::new();
|
||||
let mut tail: std::collections::VecDeque<Vec<u8>> = Default::default();
|
||||
@@ -295,6 +311,9 @@ fn run_with_env_capture(
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::time::Instant;
|
||||
|
||||
#[test]
|
||||
fn a_model_line_over_one_mebibyte_is_kept_whole_for_the_parsers() {
|
||||
@@ -500,4 +519,124 @@ mod tests {
|
||||
assert!(out.text.starts_with("pad\n"));
|
||||
assert!(out.text.ends_with("FATAL: the real error\n"));
|
||||
}
|
||||
|
||||
/// Numbered lines of `LINE_LEN` bytes each, counting the bytes taken: a pipe stand-in that
|
||||
/// reports when it is dropped, which is when the pump owning it ends.
|
||||
const LINE_LEN: usize = 100;
|
||||
|
||||
struct NumberedLines {
|
||||
next: usize,
|
||||
lines: usize,
|
||||
taken: Arc<AtomicUsize>,
|
||||
gone: mpsc::Sender<()>,
|
||||
}
|
||||
|
||||
fn numbered(n: usize) -> String {
|
||||
format!("{n:0width$}", width = LINE_LEN - 1)
|
||||
}
|
||||
|
||||
impl Read for NumberedLines {
|
||||
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
|
||||
let mut n = 0;
|
||||
while self.next < self.lines && n + LINE_LEN <= buf.len() {
|
||||
buf[n..n + LINE_LEN - 1].copy_from_slice(numbered(self.next).as_bytes());
|
||||
buf[n + LINE_LEN - 1] = b'\n';
|
||||
self.next += 1;
|
||||
n += LINE_LEN;
|
||||
}
|
||||
self.taken.fetch_add(n, Ordering::SeqCst);
|
||||
Ok(n)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for NumberedLines {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.gone.send(());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_slow_consumer_holds_the_pump_back_instead_of_queueing_every_line() {
|
||||
const LINES: usize = 50_000;
|
||||
let taken = Arc::new(AtomicUsize::new(0));
|
||||
let (gone, _) = mpsc::channel();
|
||||
let pipe = NumberedLines { next: 0, lines: LINES, taken: taken.clone(), gone };
|
||||
let (tx, rx) = line_queue();
|
||||
let pump = std::thread::spawn(move || pump_bounded(Box::new(pipe), Stream::Stdout, &tx));
|
||||
let (mut count, mut peak) = (0usize, 0usize);
|
||||
loop {
|
||||
match rx.recv_timeout(Duration::from_secs(60)) {
|
||||
Ok((stream, line)) => {
|
||||
assert_eq!(stream, Stream::Stdout);
|
||||
assert_eq!(line, numbered(count), "a line arrived out of order or damaged");
|
||||
// Read from the pipe but not yet handed over: the rest of the chunk the pump
|
||||
// is cutting into lines, and the queue.
|
||||
peak = peak.max(taken.load(Ordering::SeqCst) - count * LINE_LEN);
|
||||
count += 1;
|
||||
// A consumer that cannot keep up with the process.
|
||||
if count.is_multiple_of(LINE_QUEUE) {
|
||||
std::thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
}
|
||||
Err(mpsc::RecvTimeoutError::Disconnected) => break,
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => panic!("the pump stalled"),
|
||||
}
|
||||
}
|
||||
pump.join().unwrap();
|
||||
assert_eq!(count, LINES);
|
||||
let bound = PUMP_CHUNK + (LINE_QUEUE + 2) * LINE_LEN;
|
||||
assert!(peak <= bound, "{peak} bytes read ahead of the consumer, more than {bound}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pump_blocked_on_a_full_queue_ends_when_the_consumer_is_gone() {
|
||||
let taken = Arc::new(AtomicUsize::new(0));
|
||||
let (gone_tx, gone) = mpsc::channel();
|
||||
// Far more than the queue and a few chunks hold.
|
||||
let pipe = NumberedLines { next: 0, lines: 100_000, taken: taken.clone(), gone: gone_tx };
|
||||
let (tx, rx) = line_queue();
|
||||
let pump = std::thread::spawn(move || pump_bounded(Box::new(pipe), Stream::Stdout, &tx));
|
||||
// A consumer that takes nothing: the queue fills, with the pump inside its first chunk.
|
||||
let deadline = Instant::now() + Duration::from_secs(30);
|
||||
while taken.load(Ordering::SeqCst) == 0 {
|
||||
assert!(Instant::now() < deadline, "the pump never read");
|
||||
std::thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
// Time for a pump that does not wait to run ahead.
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
assert!(taken.load(Ordering::SeqCst) <= PUMP_CHUNK, "the pump read past a full queue");
|
||||
assert!(gone.try_recv().is_err(), "the pump ended while its consumer was still there");
|
||||
drop(rx);
|
||||
gone.recv_timeout(Duration::from_secs(30)).expect("the pump stayed blocked after the consumer was gone");
|
||||
pump.join().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_slow_on_line_still_sees_every_line_in_order_and_the_exit_status() {
|
||||
if cfg!(windows) {
|
||||
return;
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let args = ["-c".into(), "awk 'BEGIN{for(i=1;i<=300000;i++)print i}'; exit 4".into()];
|
||||
for bounded in [false, true] {
|
||||
let mut next = 1usize;
|
||||
let on_line = |stream: Stream, line: &str| {
|
||||
assert_eq!(stream, Stream::Stdout);
|
||||
assert_eq!(line, next.to_string());
|
||||
next += 1;
|
||||
if next.is_multiple_of(1000) {
|
||||
std::thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
};
|
||||
let cancel = CancellationToken::new();
|
||||
let out = if bounded {
|
||||
run_bounded("sh", &args, tmp.path(), &BTreeMap::new(), &cancel, on_line)
|
||||
} else {
|
||||
run("sh", &args, tmp.path(), &BTreeMap::new(), &cancel, on_line)
|
||||
}
|
||||
.unwrap();
|
||||
assert!(!out.success);
|
||||
assert_eq!(next, 300_001, "lines were lost");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -95,7 +95,7 @@ pub enum ErrorKind {
|
||||
AlreadyExists,
|
||||
PermissionDenied,
|
||||
InvalidInput,
|
||||
/// Document version mismatch; the UI must resync the full text.
|
||||
/// The requested state is stale; the UI must use the current snapshot.
|
||||
OutOfSync,
|
||||
Cancelled,
|
||||
TimedOut,
|
||||
|
||||
@@ -1752,9 +1752,7 @@ impl DebugManager {
|
||||
let body = session.conn.request_timeout("continue", json!({ "threadId": thread_id }), REQUEST_TIMEOUT).await?;
|
||||
// DAP: a response without the flag continued every thread.
|
||||
let all = body.get("allThreadsContinued").and_then(Value::as_bool).unwrap_or(true);
|
||||
session.suspended.resumed(ticket, thread_id, all);
|
||||
stream_trace::release_done(&session);
|
||||
session.emit(ide_core::event::DebugEvent::Continued { thread_id, all_threads_continued: all });
|
||||
session.finish_resume(ticket, thread_id, all);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1801,9 +1799,7 @@ impl DebugManager {
|
||||
let sent = session.conn.request_timeout(command, json!({ "threadId": thread_id }), REQUEST_TIMEOUT).await;
|
||||
step_settled(&session, sent)?;
|
||||
// A step runs its thread; other threads stopped by their own events stay stopped.
|
||||
session.suspended.resumed(ticket, thread_id, false);
|
||||
stream_trace::release_done(&session);
|
||||
session.emit(ide_core::event::DebugEvent::Continued { thread_id, all_threads_continued: false });
|
||||
session.finish_resume(ticket, thread_id, false);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1913,9 +1909,7 @@ impl DebugManager {
|
||||
.request_timeout("stepIn", json!({ "threadId": thread_id, "targetId": target_id }), REQUEST_TIMEOUT)
|
||||
.await;
|
||||
step_settled(&session, sent)?;
|
||||
session.suspended.resumed(ticket, thread_id, false);
|
||||
stream_trace::release_done(&session);
|
||||
session.emit(ide_core::event::DebugEvent::Continued { thread_id, all_threads_continued: false });
|
||||
session.finish_resume(ticket, thread_id, false);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
+137
-16
@@ -160,19 +160,36 @@ impl Stops {
|
||||
}
|
||||
|
||||
/// Ends the stops taken by ticket `upto` of `thread`, or of every thread.
|
||||
fn release(&mut self, thread: Option<i64>, every: bool, upto: u64) {
|
||||
/// Returns whether any stop was removed.
|
||||
fn release(&mut self, thread: Option<i64>, every: bool, upto: u64) -> bool {
|
||||
let latest = self.latest();
|
||||
let before = (self.all, self.threads.len());
|
||||
if every || thread.is_none() || self.all.is_some_and(|t| t <= upto) {
|
||||
self.all = self.all.filter(|&t| t > upto);
|
||||
self.threads.retain(|&(_, t)| t > upto);
|
||||
} else {
|
||||
self.threads.retain(|&(id, t)| Some(id) != thread || t > upto);
|
||||
}
|
||||
let changed = (self.all, self.threads.len()) != before;
|
||||
// Back on an earlier thread's stop, as the JDWP link moves to it with a new generation.
|
||||
let now = self.latest();
|
||||
if now.is_some() && now != latest {
|
||||
self.ticket += 1;
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// Whether a stop taken after `after` would be undone by a synthetic `continued` event for
|
||||
/// `thread` (or for every thread when `every` is set).
|
||||
fn superseded(&self, thread: i64, every: bool, after: u64) -> bool {
|
||||
if self.all.is_some_and(|t| t > after) {
|
||||
return true;
|
||||
}
|
||||
if every {
|
||||
self.threads.iter().any(|&(_, t)| t > after)
|
||||
} else {
|
||||
self.threads.iter().any(|&(id, t)| id == thread && t > after)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -197,12 +214,27 @@ impl Suspension {
|
||||
}
|
||||
}
|
||||
|
||||
/// A `continued` event; `all`: its `allThreadsContinued`.
|
||||
pub fn continued(&self, thread: Option<i64>, all: bool) {
|
||||
self.0.lock().release(thread, all, u64::MAX);
|
||||
/// Runs `emit` under the suspension lock so a synthetic `continued` from a resume reply cannot
|
||||
/// be emitted after a `stopped` event once that stop has been recorded.
|
||||
pub fn emit_synced(&self, emit: impl FnOnce()) {
|
||||
let _stops = self.0.lock();
|
||||
emit();
|
||||
}
|
||||
|
||||
/// Take before sending a resume-like request and pass to [`Self::resumed`].
|
||||
/// A `continued` event; `all`: its `allThreadsContinued`. Runs `emit` under the same lock so
|
||||
/// synthetic `continued` events from resume replies stay ordered against it.
|
||||
pub fn continued_and_emit(&self, thread: Option<i64>, all: bool, emit: impl FnOnce()) {
|
||||
let mut stops = self.0.lock();
|
||||
stops.release(thread, all, u64::MAX);
|
||||
emit();
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn continued(&self, thread: Option<i64>, all: bool) {
|
||||
self.continued_and_emit(thread, all, || {});
|
||||
}
|
||||
|
||||
/// Take before sending a resume-like request and pass to [`Self::resumed_and_emit`].
|
||||
pub fn ticket(&self) -> u64 {
|
||||
self.0.lock().ticket
|
||||
}
|
||||
@@ -215,8 +247,19 @@ impl Suspension {
|
||||
}
|
||||
|
||||
/// After a successful resume-like request for `thread`; `all`: every thread ran.
|
||||
/// Runs `emit` under the lock only when a prior stop was ended and no newer stop superseded it.
|
||||
pub fn resumed_and_emit(&self, ticket: u64, thread: i64, all: bool, emit: impl FnOnce()) {
|
||||
let mut stops = self.0.lock();
|
||||
let superseded = stops.superseded(thread, all, ticket);
|
||||
let released = stops.release(Some(thread), all, ticket);
|
||||
if released && !superseded {
|
||||
emit();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn resumed(&self, ticket: u64, thread: i64, all: bool) {
|
||||
self.0.lock().release(Some(thread), all, ticket);
|
||||
self.resumed_and_emit(ticket, thread, all, || {});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -316,6 +359,16 @@ impl Session {
|
||||
self.owner.sink.emit(IdeEvent::Debug { session: self.id, event });
|
||||
}
|
||||
|
||||
/// Completes a successful resume or step reply (`ticket` taken before the request): ends the
|
||||
/// prior stops and emits a synthetic `continued` event unless an adapter event already ended
|
||||
/// them or a newer `stopped` event superseded it.
|
||||
pub(crate) fn finish_resume(&self, ticket: u64, thread_id: i64, all: bool) {
|
||||
self.suspended.resumed_and_emit(ticket, thread_id, all, || {
|
||||
self.emit(DebugEvent::Continued { thread_id, all_threads_continued: all });
|
||||
});
|
||||
crate::stream_trace::release_done(self);
|
||||
}
|
||||
|
||||
/// `path` as sent to the adapter (resolved for [`RESOLVES_PATHS`] adapters).
|
||||
pub fn adapter_path(&self, path: &Path) -> PathBuf {
|
||||
if let Some(path) = self.kotlin_mirror.lock().as_ref().and_then(|m| m.adapter_path(path)) {
|
||||
@@ -789,23 +842,26 @@ async fn on_event(mgr: &Arc<DebugManager>, s: &Arc<Session>, event: &str, mut bo
|
||||
reason = quirks.stop_reason(reason);
|
||||
}
|
||||
mgr.restore_breakpoints(s).await;
|
||||
s.emit(DebugEvent::Stopped {
|
||||
thread_id: int("threadId").unwrap_or(0),
|
||||
reason,
|
||||
description: str_("description").or_else(|| str_("text")),
|
||||
all_threads_stopped: all,
|
||||
s.suspended.emit_synced(|| {
|
||||
s.emit(DebugEvent::Stopped {
|
||||
thread_id: int("threadId").unwrap_or(0),
|
||||
reason,
|
||||
description: str_("description").or_else(|| str_("text")),
|
||||
all_threads_stopped: all,
|
||||
});
|
||||
});
|
||||
}
|
||||
"continued" => {
|
||||
let all = body.get("allThreadsContinued").and_then(Value::as_bool);
|
||||
// DAP: an event without the flag continues its thread alone. The UI keeps treating
|
||||
// it as all threads; the suspension, which holds only threads that stopped, need not.
|
||||
s.suspended.continued(int("threadId"), all.unwrap_or(false));
|
||||
crate::stream_trace::release_done(s);
|
||||
s.emit(DebugEvent::Continued {
|
||||
thread_id: int("threadId").unwrap_or(0),
|
||||
all_threads_continued: all.unwrap_or(true),
|
||||
s.suspended.continued_and_emit(int("threadId"), all.unwrap_or(false), || {
|
||||
s.emit(DebugEvent::Continued {
|
||||
thread_id: int("threadId").unwrap_or(0),
|
||||
all_threads_continued: all.unwrap_or(true),
|
||||
});
|
||||
});
|
||||
crate::stream_trace::release_done(s);
|
||||
}
|
||||
"output" => {
|
||||
let category = str_("category").unwrap_or_else(|| "console".into());
|
||||
@@ -1465,6 +1521,71 @@ mod tests {
|
||||
assert!(!s.get());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn synthetic_continued_is_suppressed_when_a_newer_stop_or_continued_already_landed() {
|
||||
let emit_if_resumed = |s: &Suspension, ticket, thread, all| {
|
||||
let mut emitted = false;
|
||||
s.resumed_and_emit(ticket, thread, all, || emitted = true);
|
||||
emitted
|
||||
};
|
||||
|
||||
// Normal step without an adapter `continued` event emits a synthetic one.
|
||||
let s = Suspension::default();
|
||||
s.stopped(Some(1), true);
|
||||
assert!(emit_if_resumed(&s, s.ticket(), 1, false));
|
||||
|
||||
// Next `stopped` (all-threads or single-thread) overtakes the reply: no synthetic `continued`.
|
||||
for next_all in [true, false] {
|
||||
let s = Suspension::default();
|
||||
s.stopped(Some(1), true);
|
||||
let ticket = s.ticket();
|
||||
s.stopped(Some(1), next_all);
|
||||
assert!(!emit_if_resumed(&s, ticket, 1, false), "next_all={next_all}");
|
||||
assert!(s.get());
|
||||
}
|
||||
|
||||
// Adapter's own `continued` event already ended the stop: no duplicate synthetic `continued`.
|
||||
let s = Suspension::default();
|
||||
s.stopped(Some(1), true);
|
||||
let ticket = s.ticket();
|
||||
s.continued(Some(1), true);
|
||||
assert!(!emit_if_resumed(&s, ticket, 1, true));
|
||||
|
||||
// Multi-thread: thread 7 steps while thread 9 stops alone -> thread 7 still emits `continued(all=false)`.
|
||||
let s = two_threads_stopped();
|
||||
let ticket = s.ticket();
|
||||
s.stopped(Some(9), false);
|
||||
assert!(emit_if_resumed(&s, ticket, 7, false));
|
||||
assert!(s.get());
|
||||
|
||||
// Multi-thread: `continue(all=true)` while thread 9 stops alone -> suppressed so thread 9 stays paused.
|
||||
let s = two_threads_stopped();
|
||||
let ticket = s.ticket();
|
||||
s.stopped(Some(9), false);
|
||||
assert!(!emit_if_resumed(&s, ticket, 7, true));
|
||||
assert!(s.get());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn concurrent_stop_and_resume_never_emit_continued_after_the_new_stop() {
|
||||
for _ in 0..200 {
|
||||
let s = std::sync::Arc::new(Suspension::default());
|
||||
let log = std::sync::Arc::new(parking_lot::Mutex::new(Vec::<&'static str>::new()));
|
||||
s.stopped(Some(1), true);
|
||||
let ticket = s.ticket();
|
||||
let s2 = s.clone();
|
||||
let log2 = log.clone();
|
||||
let stop = std::thread::spawn(move || {
|
||||
s2.stopped(Some(1), false);
|
||||
s2.emit_synced(|| log2.lock().push("stopped"));
|
||||
});
|
||||
s.resumed_and_emit(ticket, 1, false, || log.lock().push("continued"));
|
||||
stop.join().unwrap();
|
||||
let events = log.lock().clone();
|
||||
assert!(events == ["continued", "stopped"] || events == ["stopped"], "unexpected order: {events:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kotlin_launch_starts_attach_listener_first() {
|
||||
assert_eq!(
|
||||
|
||||
@@ -157,6 +157,11 @@ struct Script {
|
||||
breakpoints_after_continue: usize,
|
||||
/// The `reason` of the stop a `next` ends with (`step` when unset; kotlin-lsp says `breakpoint`).
|
||||
step_reason: Option<&'static str>,
|
||||
/// Send `stopped` before answering `next` / `stepIn` / `stepOut` / `continue` (like php-debug
|
||||
/// when Xdebug finishes a step before the DAP reply is handled).
|
||||
stop_before_reply: bool,
|
||||
/// Send `continued` before answering `next` / `continue`.
|
||||
continued_before_reply: bool,
|
||||
/// Refuse `next`, then stop at a breakpoint (one the program hit meanwhile).
|
||||
refuse_next: bool,
|
||||
/// Send `invalidated { areas: ["variables"] }` right after the first `stopped` event.
|
||||
@@ -213,6 +218,8 @@ impl Default for Script {
|
||||
refuse_continue: false,
|
||||
breakpoints_after_continue: 0,
|
||||
step_reason: None,
|
||||
stop_before_reply: false,
|
||||
continued_before_reply: false,
|
||||
refuse_next: false,
|
||||
invalidated_after_stop: false,
|
||||
stop_during_threads: false,
|
||||
@@ -414,6 +421,19 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
send!(json!({"type": "event", "event": "stopped", "body": {"reason": "breakpoint", "threadId": 1}}));
|
||||
}
|
||||
"next" if script.stop_before_reply => {
|
||||
let reason = script.step_reason.unwrap_or("step");
|
||||
send!(json!({"type": "event", "event": "stopped", "body": {"reason": reason, "threadId": 1}}));
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
ok!(msg, Value::Null);
|
||||
}
|
||||
"next" if script.continued_before_reply => {
|
||||
send!(
|
||||
json!({"type": "event", "event": "continued", "body": {"threadId": 1, "allThreadsContinued": false}})
|
||||
);
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
ok!(msg, Value::Null);
|
||||
}
|
||||
"next" => {
|
||||
ok!(msg, Value::Null);
|
||||
let reason = script.step_reason.unwrap_or("step");
|
||||
@@ -553,6 +573,20 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
|
||||
"stepOut" if script.refuse_step_out => send!(
|
||||
json!({"type": "response", "request_seq": msg["seq"], "command": "stepOut", "success": false, "message": "Thread is not suspended"})
|
||||
),
|
||||
"continue" if script.stop_before_reply => {
|
||||
send!(
|
||||
json!({"type": "event", "event": "stopped", "body": {"reason": "breakpoint", "threadId": 1, "allThreadsStopped": true}})
|
||||
);
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
ok!(msg, json!({"allThreadsContinued": true}));
|
||||
}
|
||||
"continue" if script.continued_before_reply => {
|
||||
send!(
|
||||
json!({"type": "event", "event": "continued", "body": {"threadId": 1, "allThreadsContinued": true}})
|
||||
);
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
ok!(msg, json!({"allThreadsContinued": true}));
|
||||
}
|
||||
"continue" if script.stop_after_continue => {
|
||||
ok!(msg, json!({"allThreadsContinued": true}));
|
||||
send!(
|
||||
@@ -575,6 +609,11 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
|
||||
send!(json!({"type": "event", "event": "stopped", "body": {"reason": reason, "threadId": thread}}));
|
||||
}
|
||||
}
|
||||
"stepIn" | "stepOut" if script.stop_before_reply => {
|
||||
send!(json!({"type": "event", "event": "stopped", "body": {"reason": "step", "threadId": 1}}));
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
ok!(msg, Value::Null);
|
||||
}
|
||||
"stepIn" | "stepOut" | "pause" => ok!(msg, Value::Null),
|
||||
"hotReload" => {
|
||||
ok!(msg, Value::Null);
|
||||
@@ -2789,6 +2828,74 @@ async fn step_of_one_thread_keeps_the_others_suspended() {
|
||||
}
|
||||
}
|
||||
|
||||
/// When an adapter emits the next `stopped` event before replying to `next` / `stepIn` / `stepOut`
|
||||
/// / `continue` (as php-debug / Xdebug can on fast steps), no trailing synthetic `continued` may
|
||||
/// overwrite the new stop.
|
||||
#[tokio::test]
|
||||
async fn stop_before_reply_does_not_emit_trailing_continued() {
|
||||
let h = harness(Script { stop_before_reply: true, ..Script::default() });
|
||||
let id = h.start(config()).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
|
||||
let session = h.manager.session(id).unwrap();
|
||||
|
||||
let run_events = |from: usize| {
|
||||
h.events
|
||||
.lock()
|
||||
.iter()
|
||||
.skip(from)
|
||||
.filter_map(|e| match e {
|
||||
IdeEvent::Debug { event: DebugEvent::Stopped { reason, .. }, .. } => Some(format!("stopped:{reason}")),
|
||||
IdeEvent::Debug { event: DebugEvent::Continued { .. }, .. } => Some("continued".into()),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
|
||||
for (label, expected) in [
|
||||
("over", "stopped:step"),
|
||||
("into", "stopped:step"),
|
||||
("out", "stopped:step"),
|
||||
("target", "stopped:step"),
|
||||
("resume", "stopped:breakpoint"),
|
||||
] {
|
||||
let before = h.events.lock().len();
|
||||
match label {
|
||||
"over" => h.manager.step(id, 1, StepKind::Over).await.unwrap(),
|
||||
"into" => h.manager.step(id, 1, StepKind::Into).await.unwrap(),
|
||||
"out" => h.manager.step(id, 1, StepKind::Out).await.unwrap(),
|
||||
"target" => h.manager.step_in_target(id, 1, 1).await.unwrap(),
|
||||
"resume" => h.manager.resume(id, 1).await.unwrap(),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
assert!(session.suspended.get(), "{label}: session must remain suspended");
|
||||
assert_eq!(run_events(before), [expected], "{label}: must not emit continued after stopped");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn continued_event_before_reply_does_not_emit_duplicate_continued() {
|
||||
for is_resume in [false, true] {
|
||||
let h = harness(Script { continued_before_reply: true, ..Script::default() });
|
||||
let id = h.start(config()).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
|
||||
|
||||
let before = h.events.lock().len();
|
||||
if is_resume {
|
||||
h.manager.resume(id, 1).await.unwrap();
|
||||
} else {
|
||||
h.manager.step(id, 1, StepKind::Over).await.unwrap();
|
||||
}
|
||||
let continued = h
|
||||
.events
|
||||
.lock()
|
||||
.iter()
|
||||
.skip(before)
|
||||
.filter(|e| matches!(e, IdeEvent::Debug { event: DebugEvent::Continued { .. }, .. }))
|
||||
.count();
|
||||
assert_eq!(continued, 1, "is_resume={is_resume}: adapter continued event already reported it");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn lazy_variables_are_resolved_when_the_adapter_declares_them_safe() {
|
||||
let h = harness(Script::default());
|
||||
|
||||
@@ -658,7 +658,12 @@ mod local_tests {
|
||||
let batches = Mutex::new(Vec::<Vec<u32>>::new());
|
||||
let result = batched(Duration::from_millis(30), &|b| batches.lock().unwrap().push(b), |line| {
|
||||
(0..1000).for_each(line);
|
||||
std::thread::sleep(Duration::from_millis(80));
|
||||
// Wait for the flusher to emit the whole burst rather than assuming a fixed
|
||||
// sleep outlasts its scheduling: a loaded runner can starve the thread
|
||||
// past the quiet spell and fold the trailing line into the burst.
|
||||
while batches.lock().unwrap().iter().map(Vec::len).sum::<usize>() < 1000 {
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
line(1000);
|
||||
"done"
|
||||
});
|
||||
|
||||
@@ -43,12 +43,19 @@ pub fn agent_unsubscribe(host: &Host, window: &str, subscriber: String) -> IdeRe
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Reads the ACP registry's install state for every provider from disk, so it runs on the
|
||||
/// blocking pool.
|
||||
#[command(trust = trusted)]
|
||||
pub fn agent_providers(host: &Host, window: &str) -> IdeResult<Vec<AgentProvider>> {
|
||||
pub async fn agent_providers(host: &Host, window: &str) -> IdeResult<Vec<AgentProvider>> {
|
||||
host.require_trust(window)?;
|
||||
let mut providers = host.project(window)?.agents.providers();
|
||||
ide_agent::registry::mark_updates(®istry_paths(host), &mut providers);
|
||||
Ok(providers)
|
||||
let agents = host.project(window)?.agents.clone();
|
||||
let paths = registry_paths(host);
|
||||
host.blocking(move || {
|
||||
let mut providers = agents.providers();
|
||||
ide_agent::registry::mark_updates(&paths, &mut providers);
|
||||
Ok(providers)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Hermes Agent profiles on this machine (`default` first); empty without Hermes.
|
||||
@@ -249,9 +256,15 @@ pub async fn agent_commands(
|
||||
host.project(window)?.agents.commands(&provider, task.as_deref()).await
|
||||
}
|
||||
|
||||
/// Entries of `task`'s conversation, or of its subagent `subagent`'s.
|
||||
/// Entries of `task`'s conversation, or of its subagent `subagent`'s. Async so a long
|
||||
/// conversation is cloned and serialised off the main thread.
|
||||
#[command(trust = always)]
|
||||
pub fn agent_entries(host: &Host, window: &str, task: String, subagent: Option<String>) -> IdeResult<Vec<AgentEntry>> {
|
||||
pub async fn agent_entries(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
task: String,
|
||||
subagent: Option<String>,
|
||||
) -> IdeResult<Vec<AgentEntry>> {
|
||||
host.project(window)?.agents.entries(&task, subagent)
|
||||
}
|
||||
|
||||
|
||||
@@ -140,7 +140,10 @@ pub struct WorkspaceMember {
|
||||
}
|
||||
|
||||
/// The workspace projects outside the window's project folder, for Mark Directory as there.
|
||||
#[command(trust = always)]
|
||||
/// Each member's `for_project().layer(Project)` re-parses both settings layers and validates the
|
||||
/// merged tree against `Settings`; that stack-hungry work must not run on the IPC (main) thread,
|
||||
/// whose 1 MiB stack overflows on project open (STATUS_STACK_OVERFLOW).
|
||||
#[command(trust = always, desktop_body = spawn)]
|
||||
pub fn project_workspace_members(host: &Host, window: &str) -> IdeResult<Vec<WorkspaceMember>> {
|
||||
let project = host.project(window)?;
|
||||
Ok(project
|
||||
@@ -156,7 +159,8 @@ pub fn project_workspace_members(host: &Host, window: &str) -> IdeResult<Vec<Wor
|
||||
|
||||
/// Sets a `projectStructure.*` key in the settings of `root`, a project attached to the window's
|
||||
/// project (Mark Directory as there). Every open window holding that project follows.
|
||||
#[command(trust = always)]
|
||||
/// Like `project_workspace_members`, its `for_project` settings re-parse runs off the IPC thread.
|
||||
#[command(trust = always, desktop_body = spawn)]
|
||||
pub fn project_workspace_member_set(
|
||||
host: &Arc<Host>,
|
||||
window: &str,
|
||||
|
||||
@@ -67,20 +67,24 @@ fn scan_roots(root: &Path, content_roots: Vec<PathBuf>) -> Vec<PathBuf> {
|
||||
roots
|
||||
}
|
||||
|
||||
/// Every mapping source of the project, for the request-path index.
|
||||
pub fn spring_route_sources(host: &Host, window: &str) -> IdeResult<Vec<RouteSource>> {
|
||||
/// Every mapping source of the project, for the request-path index. Walks the whole tree,
|
||||
/// so it runs on the blocking pool.
|
||||
pub async fn spring_route_sources(host: &Host, window: &str) -> IdeResult<Vec<RouteSource>> {
|
||||
let project = host.project(window)?;
|
||||
let mut out = Vec::new();
|
||||
for root in scan_roots(&project.root, project.content_roots()) {
|
||||
out.extend(sources_in(&root, &project.search_excludes_in(&root)));
|
||||
}
|
||||
out.sort_by(|a, b| a.path.cmp(&b.path));
|
||||
out.dedup_by(|a, b| a.path == b.path);
|
||||
match out.len() {
|
||||
0 => tracing::warn!("spring routes: no mapping source under {:?}", project.root),
|
||||
n => tracing::info!("spring routes: {n} mapping sources under {:?}", project.root),
|
||||
}
|
||||
Ok(out)
|
||||
host.blocking(move || {
|
||||
let mut out = Vec::new();
|
||||
for root in scan_roots(&project.root, project.content_roots()) {
|
||||
out.extend(sources_in(&root, &project.search_excludes_in(&root)));
|
||||
}
|
||||
out.sort_by(|a, b| a.path.cmp(&b.path));
|
||||
out.dedup_by(|a, b| a.path == b.path);
|
||||
match out.len() {
|
||||
0 => tracing::warn!("spring routes: no mapping source under {:?}", project.root),
|
||||
n => tracing::info!("spring routes: {n} mapping sources under {:?}", project.root),
|
||||
}
|
||||
Ok(out)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -111,7 +111,7 @@ pub(crate) fn search_project(
|
||||
};
|
||||
let literals = |path: &Path, text: &str| literals_of(project, syntax, path, text);
|
||||
let defaults = project.documents.file_defaults();
|
||||
let decode = |path: &Path, bytes: &[u8]| ide_vfs::decode_text(bytes, defaults.fallback_for(path));
|
||||
let fallback = |path: &Path| defaults.fallback_for(path).map(str::to_owned);
|
||||
let mut total = SearchSummary::default();
|
||||
for dir in std::iter::once(root).filter(|_| include_root).chain(&content_roots) {
|
||||
let mut remaining = query.clone();
|
||||
@@ -139,7 +139,7 @@ pub(crate) fn search_project(
|
||||
&remaining,
|
||||
Some(&filter),
|
||||
Some(&literals),
|
||||
ide_search::TextSource { overlay: &|p| project.documents.search_text_of(p), decode: &decode },
|
||||
ide_search::TextSource { overlay: &|p| project.documents.search_text_of(p), fallback: &fallback },
|
||||
cancel,
|
||||
&|mut file| {
|
||||
if let Some(prefix) = &prefix {
|
||||
@@ -188,6 +188,11 @@ pub(crate) fn rebase_masks(masks: &[String], prefix: &str) -> Vec<String> {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn search_leaves_unread_the_texts_the_parser_does_not_take() {
|
||||
assert_eq!(ide_search::MAX_LITERALS_TEXT_BYTES, ide_language::MAX_PARSE_BYTES);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn masks_follow_the_root_they_search() {
|
||||
let masks = vec![".wt/a/src/**, src/**".into(), "*.rs".into(), "!.wt/a/out/**".into(), "**/build/**".into()];
|
||||
|
||||
@@ -24,8 +24,8 @@ fn remember_codex_modes(data: &Path, root: &Path) {
|
||||
std::fs::write(data.join("agents/models.json"), modes.to_string()).unwrap();
|
||||
}
|
||||
|
||||
fn codex_mode(host: &Host) -> Option<String> {
|
||||
let providers = ide_host::ops::agent::agent_providers(host, "main").unwrap();
|
||||
async fn codex_mode(host: &Host) -> Option<String> {
|
||||
let providers = ide_host::ops::agent::agent_providers(host, "main").await.unwrap();
|
||||
let codex = providers.into_iter().find(|p| p.id == "codex").expect("codex is listed");
|
||||
codex.config.into_iter().find(|o| o.id == "mode").and_then(|o| o.current)
|
||||
}
|
||||
@@ -54,10 +54,10 @@ async fn new_tasks_start_asking_for_approval_when_the_user_chose_so() {
|
||||
}));
|
||||
host.trust.decide(&root, true, false).unwrap();
|
||||
host.open_project("main", &root).unwrap();
|
||||
assert_eq!(codex_mode(&host).as_deref(), Some("ask"));
|
||||
assert_eq!(codex_mode(&host).await.as_deref(), Some("ask"));
|
||||
|
||||
// The default keeps starting new tasks without approvals.
|
||||
std::fs::remove_file(config.join("settings.toml")).unwrap();
|
||||
host.project("main").unwrap().settings.reload();
|
||||
assert_eq!(codex_mode(&host).as_deref(), Some("full-access"));
|
||||
assert_eq!(codex_mode(&host).await.as_deref(), Some("full-access"));
|
||||
}
|
||||
@@ -30,8 +30,8 @@ fn open(host: &Host, tmp: &tempfile::TempDir) {
|
||||
host.open_project("main", &root).unwrap();
|
||||
}
|
||||
|
||||
fn env_of(host: &Host, id: &str) -> BTreeMap<String, String> {
|
||||
let providers = ide_host::ops::agent::agent_providers(host, "main").unwrap();
|
||||
async fn env_of(host: &Host, id: &str) -> BTreeMap<String, String> {
|
||||
let providers = ide_host::ops::agent::agent_providers(host, "main").await.unwrap();
|
||||
providers.into_iter().find(|p| p.id == id).unwrap_or_else(|| panic!("{id}")).env
|
||||
}
|
||||
|
||||
@@ -60,8 +60,8 @@ async fn agent_environment_values_stay_out_of_agent_files() {
|
||||
|
||||
let host = self::host(tmp.path());
|
||||
open(&host, &tmp);
|
||||
assert_eq!(env_of(&host, "claude"), env);
|
||||
assert_eq!(env_of(&host, "mine"), env);
|
||||
assert_eq!(env_of(&host, "claude").await, env);
|
||||
assert_eq!(env_of(&host, "mine").await, env);
|
||||
ide_host::ops::agent::remove_custom_agent(&host, "main", "mine".into()).unwrap();
|
||||
ide_host::ops::agent::agent_set_env(&host, "main", "claude".into(), BTreeMap::new()).unwrap();
|
||||
assert_eq!(host.agent_secrets.keys("agent/"), Vec::<String>::new());
|
||||
@@ -81,6 +81,6 @@ async fn values_in_agent_files_move_to_the_credential_store() {
|
||||
let host = host(tmp.path());
|
||||
open(&host, &tmp);
|
||||
assert_eq!(files_containing(tmp.path(), VALUE), Vec::<PathBuf>::new());
|
||||
assert_eq!(env_of(&host, "mine"), BTreeMap::from([("TOKEN".to_owned(), VALUE.to_owned())]));
|
||||
assert_eq!(env_of(&host, "mine").await, BTreeMap::from([("TOKEN".to_owned(), VALUE.to_owned())]));
|
||||
host.close_project("main");
|
||||
}
|
||||
@@ -71,9 +71,10 @@ async fn external_maven_link_persists_reloads_and_unlink_keeps_files() {
|
||||
}
|
||||
|
||||
/// The language server's Maven import roots once `ready` holds: a settings change refreshes them in
|
||||
/// the background.
|
||||
/// the background. The deadline is generous because a loaded CI runner can take well over a few
|
||||
/// seconds to re-import.
|
||||
async fn import_roots(host: &Host, ready: impl Fn(&[std::path::PathBuf]) -> bool) -> Vec<std::path::PathBuf> {
|
||||
for _ in 0..200 {
|
||||
for _ in 0..600 {
|
||||
let roots = host.project("main").unwrap().lsp.jdtls_import_roots();
|
||||
if ready(&roots) {
|
||||
return roots;
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
|
||||
use ide_core::{Range, SymbolKind};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Bit set of the (lower-cased) ASCII letters/digits/punctuation present in a
|
||||
@@ -588,6 +588,9 @@ pub(crate) struct IndexData {
|
||||
free: Vec<u32>,
|
||||
pub file_count: u32,
|
||||
pub symbol_count: u32,
|
||||
/// Full passes over `by_path` made to remove folders.
|
||||
#[cfg(test)]
|
||||
pub key_scans: usize,
|
||||
}
|
||||
|
||||
impl IndexData {
|
||||
@@ -792,9 +795,15 @@ impl IndexData {
|
||||
Some(old)
|
||||
}
|
||||
|
||||
/// Removes every file at or below `dir`; returns their paths.
|
||||
pub(crate) fn remove_tree(&mut self, dir: &Path) -> Vec<PathBuf> {
|
||||
let doomed: Vec<PathBuf> = self.by_path.keys().filter(|p| p.starts_with(dir)).cloned().collect();
|
||||
/// Removes every file at or below any of `dirs` in a single pass over the
|
||||
/// indexed paths; returns their paths.
|
||||
pub(crate) fn remove_trees(&mut self, dirs: &HashSet<PathBuf>) -> Vec<PathBuf> {
|
||||
#[cfg(test)]
|
||||
{
|
||||
self.key_scans += 1;
|
||||
}
|
||||
let doomed: Vec<PathBuf> =
|
||||
self.by_path.keys().filter(|p| p.ancestors().any(|a| dirs.contains(a))).cloned().collect();
|
||||
doomed.into_iter().filter(|p| self.remove(p).is_some()).collect()
|
||||
}
|
||||
|
||||
@@ -867,6 +876,10 @@ mod tests {
|
||||
FileEntry::new(PathBuf::from("/r").join(path), path.to_owned(), record)
|
||||
}
|
||||
|
||||
fn path_set(paths: &[&str]) -> HashSet<PathBuf> {
|
||||
paths.iter().map(PathBuf::from).collect()
|
||||
}
|
||||
|
||||
fn insert(d: &mut IndexData, path: &str, symbols: usize) {
|
||||
let (e, s) = entry(path, symbols);
|
||||
d.insert(e, s);
|
||||
@@ -944,11 +957,25 @@ mod tests {
|
||||
d.remove(Path::new("/r/a/b/c.rs"));
|
||||
assert!(!d.dirs.contains_key("a/b/"));
|
||||
assert_consistent(&d);
|
||||
d.remove_tree(Path::new("/r/a"));
|
||||
d.remove_trees(&path_set(&["/r/a"]));
|
||||
assert!(d.dirs.is_empty());
|
||||
assert_consistent(&d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_trees_takes_only_files_below_the_given_folders() {
|
||||
let mut d = IndexData::default();
|
||||
for path in ["a/x.rs", "a/b/y.rs", "ab/z.rs", "c/d/w.rs", "c/keep.rs", "top.rs"] {
|
||||
insert(&mut d, path, 1);
|
||||
}
|
||||
let mut gone = d.remove_trees(&path_set(&["/r/a", "/r/a/b", "/r/c/d", "/r/missing"]));
|
||||
gone.sort();
|
||||
assert_eq!(gone, ["/r/a/b/y.rs", "/r/a/x.rs", "/r/c/d/w.rs"].map(PathBuf::from));
|
||||
assert_eq!(d.file_count, 3);
|
||||
assert!(["/r/ab/z.rs", "/r/c/keep.rs", "/r/top.rs"].iter().all(|p| d.get(Path::new(p)).is_some()));
|
||||
assert_consistent(&d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn insert_replace_remove_keep_counts() {
|
||||
let mut d = IndexData::default();
|
||||
@@ -964,7 +991,7 @@ mod tests {
|
||||
insert(&mut d, "d.rs", 0);
|
||||
assert_eq!(d.files.len(), 2, "slot reused");
|
||||
assert_consistent(&d);
|
||||
assert_eq!(d.remove_tree(Path::new("/r/a")), vec![PathBuf::from("/r/a/b.rs")]);
|
||||
assert_eq!(d.remove_trees(&path_set(&["/r/a"])), vec![PathBuf::from("/r/a/b.rs")]);
|
||||
assert_eq!((d.file_count, d.symbol_count), (1, 0));
|
||||
let e = d.get(Path::new("/r/d.rs")).unwrap();
|
||||
assert_eq!((e.name(), e.dir()), ("d.rs", ""));
|
||||
@@ -1039,7 +1066,7 @@ mod tests {
|
||||
insert(&mut d, "a/b/two.rs", 3);
|
||||
insert(&mut d, "a/three.rs", 1);
|
||||
insert(&mut d, "elsewhere/four.rs", 1);
|
||||
assert_eq!(d.remove_tree(Path::new("/r/a")).len(), 3);
|
||||
assert_eq!(d.remove_trees(&path_set(&["/r/a"])).len(), 3);
|
||||
assert_consistent(&d);
|
||||
assert_eq!(d.hot.rows.iter().filter(|r| r.live).count(), 1);
|
||||
assert!(d.hot.row(0).is_none(), "removed slots have no live row");
|
||||
|
||||
@@ -900,16 +900,21 @@ impl Shared {
|
||||
|
||||
// Removals first; a path removed then re-created shows up in `changed` too.
|
||||
let mut deletes = Vec::new();
|
||||
// Paths that are not indexed files: removed directories (or files that were never indexed).
|
||||
let mut gone_dirs = HashSet::new();
|
||||
for path in removed {
|
||||
if path.exists() {
|
||||
changed.push(path);
|
||||
continue;
|
||||
}
|
||||
let mut d = self.data.write();
|
||||
let gone = match d.remove(&path) {
|
||||
Some(_) => vec![path],
|
||||
None => d.remove_tree(&path),
|
||||
};
|
||||
if self.data.write().remove(&path).is_some() {
|
||||
deletes.extend(filter.store_key(&path));
|
||||
} else {
|
||||
gone_dirs.insert(path);
|
||||
}
|
||||
}
|
||||
if !gone_dirs.is_empty() {
|
||||
let gone = self.data.write().remove_trees(&gone_dirs);
|
||||
deletes.extend(gone.iter().filter_map(|p| filter.store_key(p)));
|
||||
}
|
||||
if !deletes.is_empty() {
|
||||
@@ -1156,6 +1161,69 @@ mod metric_tests {
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removed_subtree_costs_one_key_scan_per_batch() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(dir.path()).unwrap();
|
||||
let shared = shared(&root);
|
||||
let mut batch = std::collections::BTreeSet::new();
|
||||
for i in 0..40 {
|
||||
let sub = root.join("gone").join(format!("p{}", i / 10));
|
||||
std::fs::create_dir_all(&sub).unwrap();
|
||||
std::fs::write(sub.join(format!("f{i}.txt")), "x").unwrap();
|
||||
batch.extend([sub.join(format!("f{i}.txt")), sub, root.join("gone")]);
|
||||
}
|
||||
std::fs::write(root.join("keep.txt"), "x").unwrap();
|
||||
shared.scan(None, None, SystemTime::now()).unwrap();
|
||||
assert_eq!(shared.data.read().file_count, 41);
|
||||
|
||||
std::fs::remove_dir_all(root.join("gone")).unwrap();
|
||||
shared.data.write().key_scans = 0;
|
||||
// The watcher's batches are sorted: each directory precedes its children.
|
||||
shared.process(vec![Job::Removed(batch.into_iter().collect())]);
|
||||
|
||||
let data = shared.data.read();
|
||||
assert_eq!(data.file_count, 1);
|
||||
assert!(data.get(&root.join("keep.txt")).is_some());
|
||||
assert!(data.key_scans <= 1, "{} full key scans for one removed subtree", data.key_scans);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_removal_handles_files_dirs_recreated_and_unknown_paths() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(dir.path()).unwrap();
|
||||
let shared = shared(&root);
|
||||
for rel in ["gone/a.txt", "gone/deep/b.txt", "kept/c.txt", "redo/d.txt", "redo/e.txt", "lone.txt", "stay.txt"] {
|
||||
let p = root.join(rel);
|
||||
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
|
||||
std::fs::write(p, "x").unwrap();
|
||||
}
|
||||
shared.scan(None, None, SystemTime::now()).unwrap();
|
||||
assert_eq!(shared.data.read().file_count, 7);
|
||||
|
||||
std::fs::remove_dir_all(root.join("gone")).unwrap();
|
||||
std::fs::remove_file(root.join("lone.txt")).unwrap();
|
||||
std::fs::remove_file(root.join("redo/e.txt")).unwrap();
|
||||
let outside = root.join("never/indexed/f.txt");
|
||||
let removed = [
|
||||
root.join("gone/deep/b.txt"),
|
||||
root.join("gone"),
|
||||
root.join("gone/deep"),
|
||||
root.join("lone.txt"),
|
||||
root.join("redo"),
|
||||
root.join("redo/e.txt"),
|
||||
root.join("stay.txt"),
|
||||
outside,
|
||||
];
|
||||
shared.process(vec![Job::Removed(removed.to_vec())]);
|
||||
|
||||
let data = shared.data.read();
|
||||
let mut left: Vec<_> = data.paths().map(|p| p.strip_prefix(&root).unwrap().to_owned()).collect();
|
||||
left.sort();
|
||||
// `redo` and `stay.txt` still exist: they are re-read, not dropped.
|
||||
assert_eq!(left, ["kept/c.txt", "redo/d.txt", "stay.txt"].map(PathBuf::from));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn streaming_scan_counts_full_batch_and_tail() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -635,11 +635,12 @@ async fn java_sharing_cancels_a_retiring_initialize_before_starting_its_replacem
|
||||
let old = state.peer();
|
||||
shared.store(true, Ordering::SeqCst);
|
||||
let switched = tokio::time::timeout(Duration::from_secs(2), h.mgr.reconfigure()).await;
|
||||
let closed_before_response = old.is_closed();
|
||||
gate.open();
|
||||
switched.expect("initialize cancellation must not wait for its response");
|
||||
// The retiring transport closes asynchronously; wait for it before releasing
|
||||
// the initialize response so the ordering check does not race the close.
|
||||
eventually(|| old.is_closed()).await;
|
||||
gate.open();
|
||||
eventually(|| state.requested("initialize").len() == 2).await;
|
||||
assert!(closed_before_response, "the old transport must close before its initialize response is released");
|
||||
assert_eq!(h.mgr.servers().len(), 1);
|
||||
assert_eq!(h.mgr.servers()[0].root.as_ref(), h.root.as_path());
|
||||
h.mgr.shutdown_all().await;
|
||||
|
||||
@@ -12,11 +12,17 @@ use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, ExitStatus, Stdio};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::mpsc::{self, RecvTimeoutError, Sender};
|
||||
use std::sync::mpsc::{self, RecvTimeoutError, SyncSender};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const BATCH_INTERVAL: Duration = Duration::from_millis(8);
|
||||
const BATCH_BYTES: usize = 64 * 1024;
|
||||
/// Size of one pipe read, so the most one queued [`Msg::Data`] holds.
|
||||
const READ_BUF: usize = 16 * 1024;
|
||||
/// Chunks the readers may queue ahead of the pump (at most `OUTPUT_QUEUE_CHUNKS * READ_BUF`,
|
||||
/// 2 MiB). A process printing faster than the console takes its output waits on its full
|
||||
/// pipe, as it would on a terminal, instead of piling the flood up in memory here.
|
||||
const OUTPUT_QUEUE_CHUNKS: usize = 128;
|
||||
/// After the main process exits, how long to wait for pipes still held by
|
||||
/// orphaned descendants before reporting the exit.
|
||||
const EXIT_DRAIN: Duration = Duration::from_millis(500);
|
||||
@@ -112,6 +118,12 @@ enum Msg {
|
||||
Exited(Exit),
|
||||
}
|
||||
|
||||
/// The queue from the readers (and the waiter) to the pump: bounded, so the readers wait
|
||||
/// while the pump is behind.
|
||||
fn output_queue() -> (SyncSender<Msg>, mpsc::Receiver<Msg>) {
|
||||
mpsc::sync_channel(OUTPUT_QUEUE_CHUNKS)
|
||||
}
|
||||
|
||||
/// The program and arguments actually executed, plus the echoed command line.
|
||||
pub(crate) struct Invocation {
|
||||
pub program: PathBuf,
|
||||
@@ -484,7 +496,7 @@ impl ProcessManager {
|
||||
|
||||
on_output(OutputChunk::System { text: format!("{}\n", inv.display) });
|
||||
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let (tx, rx) = output_queue();
|
||||
let stdout = child.stdout.take();
|
||||
let stderr = child.stderr.take();
|
||||
let result = (|| -> std::io::Result<()> {
|
||||
@@ -631,7 +643,7 @@ impl ProcessManager {
|
||||
self.register(entry.clone());
|
||||
on_output(OutputChunk::System { text: format!("{}\n", inv.display) });
|
||||
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let (tx, rx) = output_queue();
|
||||
let result = spawn_reader(
|
||||
id,
|
||||
Stream::Stdout,
|
||||
@@ -824,7 +836,7 @@ fn run_followup(
|
||||
config: &RunConfig,
|
||||
cwd: &Path,
|
||||
entry: &Entry,
|
||||
tx: &Sender<Msg>,
|
||||
tx: &SyncSender<Msg>,
|
||||
) -> std::io::Result<ExitStatus> {
|
||||
let mut pid = entry.pid.lock();
|
||||
if entry.stopping.load(Ordering::Acquire) {
|
||||
@@ -1106,16 +1118,19 @@ fn kill_tree(entry: &Entry, pid: u32, _force: bool) {
|
||||
.status();
|
||||
}
|
||||
|
||||
/// Reads `pipe` into `tx` until EOF. It waits in `send` while the pump is a full queue behind
|
||||
/// (the process then waits on its pipe). The pump dropping its receiver fails the `send`
|
||||
/// and ends the reader, so no reader stays blocked once the pump is gone.
|
||||
fn spawn_reader(
|
||||
id: RunId,
|
||||
stream: Stream,
|
||||
mut pipe: impl Read + Send + 'static,
|
||||
tx: Sender<Msg>,
|
||||
tx: SyncSender<Msg>,
|
||||
#[cfg(unix)] mut wait_readable: Option<Box<dyn FnMut() -> std::io::Result<()> + Send>>,
|
||||
) -> std::io::Result<()> {
|
||||
let label = if stream == Stream::Stdout { "out" } else { "err" };
|
||||
std::thread::Builder::new().name(format!("openidea-run-{label}-{}", id.0)).spawn(move || {
|
||||
let mut buf = vec![0u8; 16 * 1024];
|
||||
let mut buf = vec![0u8; READ_BUF];
|
||||
loop {
|
||||
match pipe.read(&mut buf) {
|
||||
Ok(0) => break,
|
||||
@@ -1424,6 +1439,7 @@ fn input_writer(
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
@@ -1569,4 +1585,109 @@ mod tests {
|
||||
assert_eq!(resolve_program("./gradlew", cwd, &config, true), cwd.join("./gradlew"));
|
||||
assert_eq!(resolve_program(".venv/bin/python", cwd, &config, false), cwd.join(".venv/bin/python"));
|
||||
}
|
||||
|
||||
/// A pipe stand-in that counts the bytes taken from it.
|
||||
struct Counted<R> {
|
||||
inner: R,
|
||||
taken: Arc<AtomicUsize>,
|
||||
}
|
||||
|
||||
impl<R: Read> Read for Counted<R> {
|
||||
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
|
||||
let n = self.inner.read(buf)?;
|
||||
self.taken.fetch_add(n, Ordering::SeqCst);
|
||||
Ok(n)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_slow_pump_holds_a_flooding_process_back_instead_of_queueing_its_output() {
|
||||
const LINES: usize = 2_000_000;
|
||||
// (Not `seq`: macOS prints large numbers in exponent form.)
|
||||
let mut child = Command::new("awk")
|
||||
.arg(format!("BEGIN{{for(i=1;i<={LINES};i++)print i}}"))
|
||||
.stdout(Stdio::piped())
|
||||
.spawn()
|
||||
.expect("awk");
|
||||
let taken = Arc::new(AtomicUsize::new(0));
|
||||
let pipe = Counted { inner: child.stdout.take().unwrap(), taken: taken.clone() };
|
||||
let (tx, rx) = output_queue();
|
||||
spawn_reader(RunId::next(), Stream::Stdout, pipe, tx, None).unwrap();
|
||||
let (mut received, mut peak, mut all) = (0usize, 0usize, Vec::new());
|
||||
loop {
|
||||
match rx.recv_timeout(Duration::from_secs(60)) {
|
||||
Ok(Msg::Data(stream, bytes)) => {
|
||||
assert!(stream == Stream::Stdout);
|
||||
// Read from the pipe but not yet handled: the queue, plus the chunk the
|
||||
// reader holds while it waits for room, plus the one just received.
|
||||
peak = peak.max(taken.load(Ordering::SeqCst) - received);
|
||||
received += bytes.len();
|
||||
all.extend_from_slice(&bytes);
|
||||
// A console that cannot keep up with the process.
|
||||
std::thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
Ok(Msg::Exited(_)) => unreachable!("only the waiter sends the exit"),
|
||||
Err(mpsc::RecvTimeoutError::Disconnected) => break,
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => panic!("the reader stalled"),
|
||||
}
|
||||
}
|
||||
assert!(child.wait().unwrap().success());
|
||||
let bound = (OUTPUT_QUEUE_CHUNKS + 2) * READ_BUF;
|
||||
assert!(peak <= bound, "{peak} bytes queued ahead of the pump, more than {bound}");
|
||||
let expected: String = (1..=LINES).map(|n| format!("{n}\n")).collect();
|
||||
assert!(all == expected.as_bytes(), "the output arrived incomplete or out of order");
|
||||
}
|
||||
|
||||
/// Endless output (cut at a size an unbounded queue could still hold in a test) that
|
||||
/// reports when it is dropped, which is when the reader thread owning it ends.
|
||||
struct Endless {
|
||||
served: Arc<AtomicUsize>,
|
||||
gone: mpsc::Sender<()>,
|
||||
}
|
||||
|
||||
impl Read for Endless {
|
||||
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
|
||||
if self.served.load(Ordering::SeqCst) >= 8 * OUTPUT_QUEUE_CHUNKS {
|
||||
return Ok(0);
|
||||
}
|
||||
self.served.fetch_add(1, Ordering::SeqCst);
|
||||
buf.fill(b'x');
|
||||
Ok(buf.len())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Endless {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.gone.send(());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reader_blocked_on_a_full_queue_ends_when_the_pump_is_gone() {
|
||||
let served = Arc::new(AtomicUsize::new(0));
|
||||
let (gone_tx, gone) = mpsc::channel();
|
||||
let (tx, rx) = output_queue();
|
||||
spawn_reader(
|
||||
RunId::next(),
|
||||
Stream::Stdout,
|
||||
Endless { served: served.clone(), gone: gone_tx },
|
||||
tx,
|
||||
#[cfg(unix)]
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
// A pump that takes nothing: the queue fills and the reader holds one more chunk.
|
||||
let deadline = Instant::now() + Duration::from_secs(30);
|
||||
while served.load(Ordering::SeqCst) < OUTPUT_QUEUE_CHUNKS + 1 {
|
||||
assert!(Instant::now() < deadline, "the reader never filled the queue");
|
||||
std::thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
// Time for a reader that does not wait to run ahead.
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
assert_eq!(served.load(Ordering::SeqCst), OUTPUT_QUEUE_CHUNKS + 1, "the reader ran past the full queue");
|
||||
assert!(gone.try_recv().is_err(), "the reader ended while its pump was still there");
|
||||
drop(rx);
|
||||
gone.recv_timeout(Duration::from_secs(30)).expect("the reader stayed blocked after the pump was gone");
|
||||
}
|
||||
}
|
||||
@@ -278,6 +278,73 @@ fn large_output_is_complete_and_batched() {
|
||||
assert!(chunks.lock().len() < 3000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_console_slower_than_the_process_still_gets_all_output_in_order_and_the_exit() {
|
||||
const LINES: usize = 1_000_000;
|
||||
let h = harness();
|
||||
let chunks: Chunks = Arc::default();
|
||||
let sink = chunks.clone();
|
||||
let info =
|
||||
h.pm.start(
|
||||
h.root.path(),
|
||||
&cfg("t:slow-console", "awk", &[&format!("BEGIN{{for(i=1;i<={LINES};i++)print i}}")]),
|
||||
&StartOptions::default(),
|
||||
h.sink.clone(),
|
||||
Box::new(move |c| {
|
||||
sink.lock().push(c);
|
||||
std::thread::sleep(Duration::from_millis(1));
|
||||
}),
|
||||
)
|
||||
.expect("start");
|
||||
assert_eq!(wait_exit(&h, info.id, Duration::from_secs(120)), Some(0));
|
||||
let expected: String = (1..=LINES).map(|n| format!("{n}\n")).collect();
|
||||
assert!(text(&chunks, stdout) == expected, "the output arrived incomplete or out of order");
|
||||
// The exit is reported after the output, never before the last of it.
|
||||
let all = chunks.lock();
|
||||
assert!(matches!(all.last(), Some(OutputChunk::System { text }) if text.contains("exit code 0")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stop_ends_a_flooding_run_whose_console_stalled() {
|
||||
let h = harness();
|
||||
let chunks: Chunks = Arc::default();
|
||||
let sink = chunks.clone();
|
||||
let (stalled_tx, stalled) = mpsc::channel();
|
||||
let (resume_tx, resume) = mpsc::channel::<()>();
|
||||
// The first output blocks the console until `resume_tx` is dropped.
|
||||
let resume = Mutex::new(Some(resume));
|
||||
let info =
|
||||
h.pm.start(
|
||||
h.root.path(),
|
||||
&cfg("t:stalled-console", "yes", &[]),
|
||||
&StartOptions::default(),
|
||||
h.sink.clone(),
|
||||
Box::new(move |c| {
|
||||
let output = matches!(c, OutputChunk::Stdout { .. });
|
||||
sink.lock().push(c);
|
||||
if output && let Some(resume) = resume.lock().take() {
|
||||
let _ = stalled_tx.send(());
|
||||
let _ = resume.recv();
|
||||
}
|
||||
}),
|
||||
)
|
||||
.expect("start");
|
||||
stalled.recv_timeout(Duration::from_secs(10)).expect("no output reached the console");
|
||||
// The pipe and the queue behind the stalled console fill up and `yes` waits on its pipe.
|
||||
std::thread::sleep(Duration::from_millis(300));
|
||||
h.pm.stop(info.id).unwrap();
|
||||
let pid = i32::try_from(info.pid.expect("pid")).unwrap();
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
while alive(pid) {
|
||||
assert!(Instant::now() < deadline, "the stalled run survived Stop");
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
drop(resume_tx);
|
||||
assert_eq!(wait_exit(&h, info.id, Duration::from_secs(30)), Some(130));
|
||||
let out = text(&chunks, stdout);
|
||||
assert!(!out.is_empty() && out.lines().all(|l| l == "y"), "the output was damaged");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relative_program_resolves_against_cwd() {
|
||||
let h = harness();
|
||||
|
||||
@@ -24,6 +24,11 @@ const CANCEL_CHECK_LINES: u32 = 256;
|
||||
/// How many matches a file keeps before claiming them from the shared budget: each file
|
||||
/// searched in parallel holds about this many unclaimed matches at most, not up to the whole budget.
|
||||
const CLAIM_BATCH: u32 = 64;
|
||||
/// Bytes at the start of a text that the searcher checks for binary content up front.
|
||||
const BINARY_HEAD_LEN: usize = 64 * 1024;
|
||||
/// Files longer than this hold no text the parser takes, whatever their encoding (UTF-16 halves
|
||||
/// the bytes of ASCII text, nothing else comes close): their comments and strings are not looked for.
|
||||
const MAX_LITERALS_FILE_BYTES: u64 = 2 * crate::MAX_LITERALS_TEXT_BYTES as u64;
|
||||
|
||||
pub(crate) struct Request<'a> {
|
||||
pub root: &'a Path,
|
||||
@@ -63,9 +68,11 @@ impl Control<'_> {
|
||||
|
||||
/// Also polls the cancellation token (which takes a lock).
|
||||
fn should_stop(&self) -> bool {
|
||||
if self.stopped() {
|
||||
return true;
|
||||
}
|
||||
self.stopped() || self.cancel_requested()
|
||||
}
|
||||
|
||||
/// Polls the cancellation token only: a search stopped by its match limit is not cancelled.
|
||||
fn cancel_requested(&self) -> bool {
|
||||
if self.cancel.is_cancelled() {
|
||||
self.cancelled.store(true, Relaxed);
|
||||
self.stop.store(true, Relaxed);
|
||||
@@ -302,22 +309,37 @@ impl Ctx<'_> {
|
||||
{
|
||||
return;
|
||||
}
|
||||
// The search context needs the whole text to find comments and string literals.
|
||||
// The search context needs the whole text to find comments and string literals. A file
|
||||
// whose text is past the longest the parser takes has none, so it is not read for them.
|
||||
let in_context = match self.literals {
|
||||
Some(literals) => {
|
||||
Some(literals) => 'context: {
|
||||
let text = match (self.text.overlay)(path) {
|
||||
Some(text) => text,
|
||||
None => match std::fs::read(path) {
|
||||
Ok(bytes) => match String::from_utf8(bytes) {
|
||||
Ok(text) => text,
|
||||
// Binary content has nothing to classify.
|
||||
Err(e) => match (self.text.decode)(path, e.as_bytes()) {
|
||||
Some(text) => text,
|
||||
None => return,
|
||||
None => {
|
||||
match std::fs::metadata(path) {
|
||||
Ok(meta) if meta.len() > MAX_LITERALS_FILE_BYTES => {
|
||||
if self.context.needs_literals() {
|
||||
return;
|
||||
}
|
||||
break 'context None;
|
||||
}
|
||||
Ok(_) => {}
|
||||
Err(_) => return,
|
||||
}
|
||||
match std::fs::read(path) {
|
||||
Ok(bytes) => match String::from_utf8(bytes) {
|
||||
Ok(text) => text,
|
||||
// Binary content has nothing to classify.
|
||||
Err(e) => {
|
||||
match ide_vfs::decode_text(e.as_bytes(), (self.text.fallback)(path).as_deref()) {
|
||||
Some(text) => text,
|
||||
None => return,
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
Err(_) => return,
|
||||
},
|
||||
Err(_) => return,
|
||||
}
|
||||
}
|
||||
};
|
||||
let ranges = literals(path, &text);
|
||||
if ranges.is_none() && self.context.needs_literals() {
|
||||
@@ -354,7 +376,8 @@ impl Ctx<'_> {
|
||||
}
|
||||
|
||||
/// Streams the file's bytes; a file that turns out not to be UTF-8 (GBK,
|
||||
/// UTF-16 …) is searched again in the text `decode` gives it.
|
||||
/// UTF-16 …) is searched again in its text decoded as the editor opens it,
|
||||
/// which is decoded as it is read.
|
||||
fn search_disk<'s>(
|
||||
&'s self,
|
||||
path: &Path,
|
||||
@@ -362,7 +385,7 @@ impl Ctx<'_> {
|
||||
searcher: &mut Searcher,
|
||||
sink: &mut FileSink<'s>,
|
||||
) -> io::Result<()> {
|
||||
let mut reader = Utf8Probe::new(StopReader { inner: std::fs::File::open(path)?, ctl: &self.ctl });
|
||||
let mut reader = Utf8Probe::new(StopReader { inner: std::fs::File::open(path)?, ctl: &self.ctl, hard: true });
|
||||
let result = searcher.search_reader(matcher, &mut reader, &mut *sink);
|
||||
// NUL bytes in the head of UTF-16 text stop the byte search; later ones mark binary.
|
||||
let decode = if sink.binary {
|
||||
@@ -374,14 +397,29 @@ impl Ctx<'_> {
|
||||
if !decode || (self.ctl.stopped() && sink.claimed == 0) {
|
||||
return result;
|
||||
}
|
||||
let Some(text) = (self.text.decode)(path, &std::fs::read(path)?) else {
|
||||
// Only cancellation ends the reading: a search that hit the match limit still fills its claim.
|
||||
let open = || Ok(StopReader { inner: std::fs::File::open(path)?, ctl: &self.ctl, hard: false });
|
||||
let Some(text) = ide_vfs::decode_stream(open, (self.text.fallback)(path).as_deref())? else {
|
||||
sink.binary = true;
|
||||
return Ok(());
|
||||
};
|
||||
let mut text = text;
|
||||
// Text held whole gets the searcher's binary check only on its first 64 KiB and on the
|
||||
// lines that match; this keeps that for the text read piece by piece.
|
||||
let mut head = Vec::with_capacity(BINARY_HEAD_LEN);
|
||||
(&mut text).take(BINARY_HEAD_LEN as u64).read_to_end(&mut head)?;
|
||||
if head.contains(&0) {
|
||||
sink.binary = true;
|
||||
return Ok(());
|
||||
}
|
||||
let claimed = sink.claimed;
|
||||
*sink = FileSink::new(matcher, &self.ctl, None);
|
||||
sink.claimed = claimed;
|
||||
searcher.search_slice(matcher, text.as_bytes(), sink)
|
||||
sink.binary_in_matches = true;
|
||||
searcher.set_binary_detection(BinaryDetection::none());
|
||||
let result = searcher.search_reader(matcher, io::Cursor::new(head).chain(text), sink);
|
||||
searcher.set_binary_detection(BinaryDetection::quit(0));
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
@@ -404,6 +442,8 @@ struct FileSink<'a> {
|
||||
/// file is searched again under the claim of its byte search.
|
||||
claimed: u32,
|
||||
binary: bool,
|
||||
/// A NUL byte in a matching line marks the file binary (the searcher's own check is off).
|
||||
binary_in_matches: bool,
|
||||
ticks: u32,
|
||||
/// Scratch buffers reused across lines.
|
||||
found: Vec<(usize, usize)>,
|
||||
@@ -425,6 +465,7 @@ impl<'a> FileSink<'a> {
|
||||
count: 0,
|
||||
claimed: 0,
|
||||
binary: false,
|
||||
binary_in_matches: false,
|
||||
ticks: 0,
|
||||
found: Vec::new(),
|
||||
ranges: Vec::new(),
|
||||
@@ -467,6 +508,10 @@ impl Sink for FileSink<'_> {
|
||||
type Error = io::Error;
|
||||
|
||||
fn matched(&mut self, _searcher: &Searcher, m: &SinkMatch<'_>) -> Result<bool, io::Error> {
|
||||
if self.binary_in_matches && memchr::memchr(0, m.bytes()).is_some() {
|
||||
self.binary = true;
|
||||
return Ok(false);
|
||||
}
|
||||
self.ticks += 1;
|
||||
let stop = self.ctl.stopped() || (self.ticks.is_multiple_of(CANCEL_CHECK_LINES) && self.ctl.should_stop());
|
||||
// Unless cancelled, a decoded file still fills the claim its byte search took.
|
||||
@@ -534,15 +579,17 @@ impl Sink for FileSink<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Aborts disk reads once the search is stopped or cancelled.
|
||||
/// Aborts disk reads once the search is cancelled, or with `hard` once it is stopped.
|
||||
struct StopReader<'a, R> {
|
||||
inner: R,
|
||||
ctl: &'a Control<'a>,
|
||||
hard: bool,
|
||||
}
|
||||
|
||||
impl<R: Read> Read for StopReader<'_, R> {
|
||||
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
|
||||
if self.ctl.should_stop() {
|
||||
let stop = if self.hard { self.ctl.should_stop() } else { self.ctl.cancel_requested() };
|
||||
if stop {
|
||||
return Err(io::Error::other("search stopped"));
|
||||
}
|
||||
self.inner.read(buf)
|
||||
|
||||
@@ -112,8 +112,14 @@ impl SearchContext {
|
||||
}
|
||||
}
|
||||
|
||||
/// The longest file text, in bytes, that is searched for comments and string literals: the
|
||||
/// parser's limit (`ide_language::MAX_PARSE_BYTES`), above which a [`Literals`] finds none.
|
||||
/// The search leaves a longer text unread by it.
|
||||
pub const MAX_LITERALS_TEXT_BYTES: usize = 16 * 1024 * 1024;
|
||||
|
||||
/// Comments and string literals of a file's text (sorted, non-overlapping),
|
||||
/// or `None` when its language has no syntax tree.
|
||||
/// or `None` when its language has no syntax tree or the text is longer than
|
||||
/// [`MAX_LITERALS_TEXT_BYTES`].
|
||||
pub type Literals<'a> = &'a (dyn Fn(&Path, &str) -> Option<Vec<LiteralRange>> + Sync);
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
@@ -198,21 +204,23 @@ pub struct SearchSummary {
|
||||
/// Text of unsaved open documents takes precedence over disk content.
|
||||
pub type Overlay<'a> = &'a (dyn Fn(&Path) -> Option<String> + Sync);
|
||||
|
||||
/// Text of a file whose bytes are not UTF-8 (GBK, UTF-16 …); `None` for binary content.
|
||||
pub type Decode<'a> = &'a (dyn Fn(&Path, &[u8]) -> Option<String> + Sync);
|
||||
/// The encoding to read a file with when it is not UTF-8 and the encoding detected for it is not
|
||||
/// trusted to be right (GBK, UTF-16 …): its label, or `None` to go by what is detected.
|
||||
pub type FallbackEncoding<'a> = &'a (dyn Fn(&Path) -> Option<String> + Sync);
|
||||
|
||||
/// Where a search reads file text from: the open document when `overlay` has
|
||||
/// it, else the file on disk, decoded by `decode` when it is not UTF-8.
|
||||
/// it, else the file on disk, decoded as the editor opens it when it is not UTF-8
|
||||
/// (`fallback` picks the encoding that [`ide_vfs::decode_text`] takes).
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct TextSource<'a> {
|
||||
pub overlay: Overlay<'a>,
|
||||
pub decode: Decode<'a>,
|
||||
pub fallback: FallbackEncoding<'a>,
|
||||
}
|
||||
|
||||
impl<'a> TextSource<'a> {
|
||||
/// Non-UTF-8 files decode as detected, without a configured fallback encoding.
|
||||
pub fn detected(overlay: Overlay<'a>) -> Self {
|
||||
Self { overlay, decode: &|_, bytes| ide_vfs::decode_text(bytes, None) }
|
||||
Self { overlay, fallback: &|_| None }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
//! Searching a big file holds a bounded amount of it in memory, whatever its encoding and the
|
||||
//! search context. Allocations of the whole process are counted, so this is one test with
|
||||
//! sequential scenarios.
|
||||
|
||||
use ide_core::CancellationToken;
|
||||
use ide_search::{
|
||||
FileMatches, Literals, SearchContext, SearchQuery, SearchScope, SearchSummary, TextSource, search_in_context,
|
||||
};
|
||||
use std::alloc::{GlobalAlloc, Layout, System};
|
||||
use std::path::Path;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering::Relaxed};
|
||||
|
||||
struct Counting;
|
||||
|
||||
static LIVE: AtomicUsize = AtomicUsize::new(0);
|
||||
static PEAK: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
fn grow(by: usize) {
|
||||
let live = LIVE.fetch_add(by, Relaxed) + by;
|
||||
PEAK.fetch_max(live, Relaxed);
|
||||
}
|
||||
|
||||
unsafe impl GlobalAlloc for Counting {
|
||||
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
|
||||
grow(layout.size());
|
||||
unsafe { System.alloc(layout) }
|
||||
}
|
||||
|
||||
unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
|
||||
grow(layout.size());
|
||||
unsafe { System.alloc_zeroed(layout) }
|
||||
}
|
||||
|
||||
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
|
||||
LIVE.fetch_sub(layout.size(), Relaxed);
|
||||
unsafe { System.dealloc(ptr, layout) }
|
||||
}
|
||||
|
||||
unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
|
||||
if new_size >= layout.size() {
|
||||
grow(new_size - layout.size());
|
||||
} else {
|
||||
LIVE.fetch_sub(layout.size() - new_size, Relaxed);
|
||||
}
|
||||
unsafe { System.realloc(ptr, layout, new_size) }
|
||||
}
|
||||
}
|
||||
|
||||
#[global_allocator]
|
||||
static ALLOC: Counting = Counting;
|
||||
|
||||
const MIB: usize = 1024 * 1024;
|
||||
/// What a search may hold at once: a few buffers of the reader and the decoder. The files are
|
||||
/// 16 to 40 MiB, so a search that reads one whole (or decodes it whole) is far over.
|
||||
const BOUND: usize = 4 * MIB;
|
||||
|
||||
fn query(context: SearchContext) -> SearchQuery {
|
||||
SearchQuery {
|
||||
pattern: "needle".into(),
|
||||
is_regex: false,
|
||||
case_sensitive: true,
|
||||
whole_word: false,
|
||||
include: vec![],
|
||||
exclude: vec![],
|
||||
scope: SearchScope::Project,
|
||||
max_matches: 1_000_000,
|
||||
context,
|
||||
include_excluded: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs a search and returns its result with the most memory it held over what was live before.
|
||||
fn measured(
|
||||
root: &Path,
|
||||
context: SearchContext,
|
||||
literals: Option<Literals<'_>>,
|
||||
) -> (Vec<FileMatches>, SearchSummary, usize) {
|
||||
let out = Mutex::new(Vec::new());
|
||||
let before = LIVE.load(Relaxed);
|
||||
PEAK.store(before, Relaxed);
|
||||
let summary = search_in_context(
|
||||
root,
|
||||
&query(context),
|
||||
None,
|
||||
literals,
|
||||
TextSource::detected(&|_| None),
|
||||
&CancellationToken::new(),
|
||||
&|f| out.lock().unwrap().push(f),
|
||||
)
|
||||
.unwrap();
|
||||
let held = PEAK.load(Relaxed).saturating_sub(before);
|
||||
// The results are in `out` and count against the search; they are small.
|
||||
(out.into_inner().unwrap(), summary, held)
|
||||
}
|
||||
|
||||
fn write_repeated(path: &Path, bom: &[u8], block: &[u8], size: usize) {
|
||||
use std::io::Write;
|
||||
let mut file = std::io::BufWriter::new(std::fs::File::create(path).unwrap());
|
||||
file.write_all(bom).unwrap();
|
||||
for _ in 0..size / block.len() + 1 {
|
||||
file.write_all(block).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
fn utf16le(text: &str) -> Vec<u8> {
|
||||
text.encode_utf16().flat_map(u16::to_le_bytes).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn searching_a_big_file_holds_a_bounded_part_of_it() {
|
||||
let block = "2026-11-22 13:00:01 INFO caf\u{e9} \u{4e2d}\u{6587} request ok\n".repeat(50)
|
||||
+ "2026-11-22 13:00:02 ERROR needle marker found\n";
|
||||
let latin_text = block.replace(['\u{4e2d}', '\u{6587}'], "x");
|
||||
let (latin1, _, _) = encoding_rs::WINDOWS_1252.encode(&latin_text);
|
||||
let (gbk, _, _) = encoding_rs::GBK.encode(&block);
|
||||
let parsed = Mutex::new(Vec::new());
|
||||
let literals = |path: &Path, _: &str| {
|
||||
parsed.lock().unwrap().push(path.file_name().unwrap().to_string_lossy().into_owned());
|
||||
None
|
||||
};
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut expected = Vec::new();
|
||||
for (name, bom, bytes, size) in [
|
||||
("latin1.log", &b""[..], &latin1[..], 16 * MIB),
|
||||
("gbk.log", &b""[..], &gbk[..], 16 * MIB),
|
||||
("utf16.log", &[0xFF, 0xFE][..], &utf16le(&block)[..], 24 * MIB),
|
||||
("utf8.log", &b""[..], block.as_bytes(), 40 * MIB),
|
||||
] {
|
||||
let one = tempfile::tempdir_in(dir.path()).unwrap();
|
||||
write_repeated(&one.path().join(name), bom, bytes, size);
|
||||
// Plain search: the byte search, then the decoded search of a non-UTF-8 file.
|
||||
let (files, summary, held) = measured(one.path(), SearchContext::Any, None);
|
||||
assert_eq!(files.len(), 1, "{name}");
|
||||
assert!(summary.matches > 100, "{name}");
|
||||
assert!(held < BOUND, "{name}: plain search held {} MiB", held / MIB);
|
||||
expected.push((name, summary.matches, one));
|
||||
}
|
||||
|
||||
// Searching with a context reads a file whole only to find its comments and strings, and
|
||||
// past the parser's limit it has none: the file is searched as it is read.
|
||||
for (name, matches, one) in &expected {
|
||||
for context in [SearchContext::ExceptComments, SearchContext::ExceptCommentsAndStringLiterals] {
|
||||
let (files, summary, held) = measured(one.path(), context, Some(&literals));
|
||||
if *name == "utf8.log" {
|
||||
assert_eq!(summary.matches, *matches, "{name} {context:?}");
|
||||
assert_eq!(files.len(), 1);
|
||||
assert!(held < BOUND, "{name}: {context:?} held {} MiB", held / MIB);
|
||||
}
|
||||
}
|
||||
}
|
||||
let (_, only_in, held) = measured(expected[3].2.path(), SearchContext::InComments, Some(&literals));
|
||||
assert_eq!(only_in.matches, 0, "a file without comments has no match in them");
|
||||
assert!(held < BOUND, "held {} MiB", held / MIB);
|
||||
let parsed = parsed.into_inner().unwrap();
|
||||
assert!(parsed.iter().any(|name| name == "gbk.log"), "files within the limit are still analysed");
|
||||
assert!(!parsed.iter().any(|name| name == "utf8.log"), "a 40 MiB text is never handed to the parser");
|
||||
}
|
||||
@@ -890,8 +890,7 @@ fn non_utf8_files_use_the_given_decoder() {
|
||||
// Text too short to detect reliably decodes with the configured encoding.
|
||||
let p = project(&[("a.txt", &gbk("中文\n"))]);
|
||||
let out = Mutex::new(Vec::new());
|
||||
let decode = |_: &Path, bytes: &[u8]| ide_vfs::decode_text(bytes, Some("gbk"));
|
||||
let source = TextSource { overlay: &|_| None, decode: &decode };
|
||||
let source = TextSource { overlay: &|_| None, fallback: &|_| Some("gbk".into()) };
|
||||
ide_search::search_in_context(p.path(), &query("中文"), None, None, source, &CancellationToken::new(), &|f| {
|
||||
out.lock().unwrap().push(f)
|
||||
})
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
//! Files that are not UTF-8 are decoded while they are searched. Searching the text decoded whole
|
||||
//! (what an unsaved editor buffer of the file is) is the reference: the matches must be the same.
|
||||
|
||||
use ide_core::CancellationToken;
|
||||
use ide_search::{FileMatches, SearchQuery, SearchScope, SearchSummary, TextSource, search_in_context};
|
||||
use std::path::Path;
|
||||
use std::sync::Mutex;
|
||||
|
||||
fn query(pattern: &str, is_regex: bool) -> SearchQuery {
|
||||
SearchQuery {
|
||||
pattern: pattern.into(),
|
||||
is_regex,
|
||||
case_sensitive: false,
|
||||
whole_word: false,
|
||||
include: vec![],
|
||||
exclude: vec![],
|
||||
scope: SearchScope::Project,
|
||||
max_matches: 1_000_000,
|
||||
context: Default::default(),
|
||||
include_excluded: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn run(root: &Path, q: &SearchQuery, source: TextSource<'_>) -> (Vec<FileMatches>, SearchSummary) {
|
||||
let out = Mutex::new(Vec::new());
|
||||
let summary =
|
||||
search_in_context(root, q, None, None, source, &CancellationToken::new(), &|f| out.lock().unwrap().push(f))
|
||||
.unwrap();
|
||||
let mut files = out.into_inner().unwrap();
|
||||
files.sort_by(|a, b| a.rel_path.cmp(&b.rel_path));
|
||||
(files, summary)
|
||||
}
|
||||
|
||||
/// The matches of every file in `root`, read from disk and from its whole decoded text.
|
||||
fn both_ways(root: &Path, q: &SearchQuery, fallback: Option<&str>) -> (String, String) {
|
||||
let streamed = run(root, q, TextSource { overlay: &|_| None, fallback: &|_| fallback.map(str::to_owned) });
|
||||
let whole = run(
|
||||
root,
|
||||
q,
|
||||
TextSource {
|
||||
overlay: &|path| ide_vfs::decode_text(&std::fs::read(path).unwrap(), fallback),
|
||||
fallback: &|_| None,
|
||||
},
|
||||
);
|
||||
let show = |(files, summary): (Vec<FileMatches>, SearchSummary)| {
|
||||
format!("{:#?}\nmatches {} limit {}", files, summary.matches, summary.limit_hit)
|
||||
};
|
||||
(show(streamed), show(whole))
|
||||
}
|
||||
|
||||
fn first_difference(a: &str, b: &str) -> String {
|
||||
let (a, b): (Vec<_>, Vec<_>) = (a.lines().collect(), b.lines().collect());
|
||||
let at = a.iter().zip(&b).take_while(|(x, y)| x == y).count();
|
||||
format!(
|
||||
"line {at}:\nstreamed {:?}\nwhole {:?}",
|
||||
&a[at.saturating_sub(3)..a.len().min(at + 3)],
|
||||
&b[at.saturating_sub(3)..b.len().min(at + 3)]
|
||||
)
|
||||
}
|
||||
|
||||
fn utf16(text: &str, bom: bool, big: bool) -> Vec<u8> {
|
||||
let mut bytes = if bom { vec![if big { 0xFE } else { 0xFF }, if big { 0xFF } else { 0xFE }] } else { Vec::new() };
|
||||
for unit in text.encode_utf16() {
|
||||
bytes.extend(if big { unit.to_be_bytes() } else { unit.to_le_bytes() });
|
||||
}
|
||||
bytes
|
||||
}
|
||||
|
||||
/// Lines of mixed width: ASCII, accents, CJK, astral characters (surrogate pairs), CRLF.
|
||||
fn lines(count: usize) -> String {
|
||||
let mut text = String::new();
|
||||
for i in 0..count {
|
||||
match i % 6 {
|
||||
0 => text.push_str(&format!("{i} needle in plain ascii\n")),
|
||||
1 => text.push_str(&format!("{i} caf\u{e9} needle cr\u{e8}me\n")),
|
||||
2 => text.push_str(&format!("{i} \u{4e2d}\u{6587} needle \u{6d4b}\u{8bd5}\n")),
|
||||
3 => text.push_str(&format!("{i} \u{1f600} needle \u{1f4a9}\n")),
|
||||
4 => text.push_str(&format!("{i} crlf needle\r\n")),
|
||||
_ => text.push_str(&format!("{i} nothing here\n")),
|
||||
}
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
fn write(dir: &Path, name: &str, bytes: &[u8]) {
|
||||
std::fs::write(dir.join(name), bytes).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decoded_files_give_the_matches_of_their_whole_text() {
|
||||
let wide = lines(12_000);
|
||||
let gbk_text = wide.replace(['\u{1f600}', '\u{1f4a9}', '\u{e9}', '\u{e8}'], "");
|
||||
let latin_text = wide.replace(|c: char| c as u32 > 0xff, "");
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
// (BOM-less UTF-16 is not searched in decoded text, and not covered here: only the byte search sees it.)
|
||||
// Each file is well past the sizes the decoder reads at a time (64 KiB).
|
||||
assert!(wide.len() > 250_000);
|
||||
write(dir.path(), "utf16le_bom.txt", &utf16(&wide, true, false));
|
||||
write(dir.path(), "utf16be_bom.txt", &utf16(&wide, true, true));
|
||||
write(dir.path(), "gbk.txt", &encoding_rs::GBK.encode(&gbk_text).0);
|
||||
write(dir.path(), "latin1.txt", &encoding_rs::WINDOWS_1252.encode(&latin_text).0);
|
||||
write(dir.path(), "utf8.txt", wide.as_bytes());
|
||||
|
||||
let queries = [
|
||||
query("needle", false),
|
||||
query("caf\u{e9}", false),
|
||||
query("\u{1f600}", false),
|
||||
query("\u{4e2d}\u{6587} needle", false),
|
||||
query(r"\d+ \S+ needle", true),
|
||||
query(r"needle\r?$", true),
|
||||
// A multi-line pattern reads the whole text, however it arrives.
|
||||
query("needle in plain ascii\n1 caf", false),
|
||||
SearchQuery { case_sensitive: true, whole_word: true, ..query("needle", false) },
|
||||
];
|
||||
for q in &queries {
|
||||
for fallback in [None, Some("gbk"), Some("windows-1252")] {
|
||||
let (streamed, whole) = both_ways(dir.path(), q, fallback);
|
||||
assert!(
|
||||
streamed == whole,
|
||||
"{:?} fallback {fallback:?}\n{}",
|
||||
q.pattern,
|
||||
first_difference(&streamed, &whole)
|
||||
);
|
||||
assert!(streamed.len() > 100, "{:?} found nothing", q.pattern);
|
||||
}
|
||||
}
|
||||
// The match limit keeps the first matches of a file, and files take their share in any order:
|
||||
// one file at a time.
|
||||
for name in ["utf16le_bom.txt", "utf16be_bom.txt", "gbk.txt", "latin1.txt"] {
|
||||
for max_matches in [7, 64, 65, 5_000] {
|
||||
let q = SearchQuery { max_matches, include: vec![name.into()], ..query("needle", false) };
|
||||
let (streamed, whole) = both_ways(dir.path(), &q, None);
|
||||
assert!(streamed == whole, "{name} limit {max_matches}\n{}", first_difference(&streamed, &whole));
|
||||
assert!(streamed.contains(&format!("matches {max_matches} limit true")), "{name} {max_matches}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decoded_files_keep_their_multibyte_characters_across_every_read_boundary() {
|
||||
// A character sits on each of the 64 KiB read boundaries, at all alignments.
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
for pad in 0..8usize {
|
||||
let mut gbk = "x".repeat(64 * 1024 - 5 + pad);
|
||||
let mut utf16_text = gbk.clone();
|
||||
for i in 0..40 {
|
||||
gbk.push_str("\u{4e2d}\u{6587}");
|
||||
utf16_text.push_str(if i % 2 == 0 { "\u{1f600}" } else { "\u{4e2d}" });
|
||||
gbk.push_str(&"y".repeat(i % 3));
|
||||
utf16_text.push_str(&"y".repeat(i % 3));
|
||||
}
|
||||
gbk.push_str("yy needle\n");
|
||||
utf16_text.push_str("yy needle\n");
|
||||
write(dir.path(), &format!("gbk{pad}.txt"), &encoding_rs::GBK.encode(&gbk).0);
|
||||
write(dir.path(), &format!("utf16_{pad}.txt"), &utf16(&utf16_text, true, pad % 2 == 0));
|
||||
write(
|
||||
dir.path(),
|
||||
&format!("latin{pad}.txt"),
|
||||
&[gbk.as_bytes()[..64 * 1024 - 7 + pad].to_vec(), b"\xe9\xe8 needle\n".to_vec()].concat(),
|
||||
);
|
||||
}
|
||||
for pattern in ["needle", "y+ needle", "\u{4e2d}\u{6587}"] {
|
||||
let q = query(pattern, pattern.contains('+'));
|
||||
let (streamed, whole) = both_ways(dir.path(), &q, None);
|
||||
assert!(streamed == whole, "{pattern}\n{}", first_difference(&streamed, &whole));
|
||||
assert!(streamed.len() > 100, "{pattern} found nothing");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nul_characters_in_decoded_text_mark_it_binary_as_in_the_whole_text() {
|
||||
// Text held whole is binary when a NUL is in its first 64 KiB or in a line that matches,
|
||||
// which is not the same as a NUL anywhere.
|
||||
let text = lines(20_000);
|
||||
let with_nul = |at: &str| text.replacen(at, &format!("\0{at}"), 1);
|
||||
let cases = [
|
||||
("early", with_nul("5 nothing here"), false),
|
||||
("late in a line that does not match", with_nul("19997 nothing here"), true),
|
||||
("late in a line that matches", with_nul("19998 needle"), false),
|
||||
];
|
||||
for (name, text, found) in cases {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
write(dir.path(), "a.txt", &utf16(&text, true, false));
|
||||
let (streamed, whole) = both_ways(dir.path(), &query("needle", false), None);
|
||||
assert!(streamed == whole, "{name}\n{}", first_difference(&streamed, &whole));
|
||||
assert_eq!(streamed.contains("a.txt"), found, "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_is_decoded_when_its_search_reaches_the_byte_that_is_not_utf8() {
|
||||
// Valid UTF-8 up to the last line: the whole file is read as the detected Windows-1252.
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
write(dir.path(), "late.txt", &[lines(1500).as_bytes(), b"caf\xe9 needle\n"].concat());
|
||||
for q in [query("needle", false), query("caf", false)] {
|
||||
let (streamed, whole) = both_ways(dir.path(), &q, None);
|
||||
assert!(streamed == whole, "{}", first_difference(&streamed, &whole));
|
||||
assert!(streamed.contains("café"), "decoded as Windows-1252");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,366 @@
|
||||
//! [`decode_text`](crate::decode_text) for files too large to hold: the same
|
||||
//! decisions, taken while reading a chunk at a time.
|
||||
|
||||
use crate::encoding::{SNIFF_LEN, sniff_utf16};
|
||||
use encoding_rs::{Decoder, Encoding, UTF_8, UTF_16BE, UTF_16LE};
|
||||
use std::io::{self, Read};
|
||||
|
||||
/// Raw bytes read per step; a step holds this plus its UTF-8 expansion (at most 3x).
|
||||
const CHUNK: usize = 64 * 1024;
|
||||
|
||||
/// The text of a file as UTF-8 bytes, decoded as it is read.
|
||||
pub struct DecodedReader<R> {
|
||||
reader: R,
|
||||
decoder: Decoder,
|
||||
raw: Vec<u8>,
|
||||
/// Decoded bytes of the last step; `out[pos..len]` is unread.
|
||||
out: Vec<u8>,
|
||||
pos: usize,
|
||||
len: usize,
|
||||
done: bool,
|
||||
}
|
||||
|
||||
/// Decodes the file `open` reads like [`decode_text`](crate::decode_text) does (BOM, UTF-8 and
|
||||
/// UTF-16 as detected, other text as `fallback` or else the detected encoding) without holding
|
||||
/// it: `None` for binary content, else a reader of the text as UTF-8.
|
||||
///
|
||||
/// Deciding the encoding of text that is neither BOM-marked nor UTF-8 needs a pass over the whole
|
||||
/// file before the decoding pass, so `open` gives a fresh reader of the file up to twice.
|
||||
pub fn decode_stream<R: Read>(
|
||||
open: impl FnMut() -> io::Result<R>,
|
||||
fallback: Option<&str>,
|
||||
) -> io::Result<Option<DecodedReader<R>>> {
|
||||
decode_stream_in(open, fallback, CHUNK)
|
||||
}
|
||||
|
||||
fn decode_stream_in<R: Read>(
|
||||
mut open: impl FnMut() -> io::Result<R>,
|
||||
fallback: Option<&str>,
|
||||
chunk: usize,
|
||||
) -> io::Result<Option<DecodedReader<R>>> {
|
||||
let Some((detected, bom_len, has_bom)) = detect(&mut open, chunk)? else { return Ok(None) };
|
||||
let fallback = fallback.and_then(|label| Encoding::for_label(label.trim().as_bytes()));
|
||||
let encoding = match fallback {
|
||||
Some(enc)
|
||||
if !has_bom && enc != detected && detected != UTF_8 && detected != UTF_16LE && detected != UTF_16BE =>
|
||||
{
|
||||
enc
|
||||
}
|
||||
_ => detected,
|
||||
};
|
||||
let mut reader = open()?;
|
||||
io::copy(&mut (&mut reader).take(bom_len as u64), &mut io::sink())?;
|
||||
let decoder = encoding.new_decoder_without_bom_handling();
|
||||
let out = vec![0; decoder.max_utf8_buffer_length(chunk).unwrap_or(chunk * 3)];
|
||||
Ok(Some(DecodedReader { reader, decoder, raw: vec![0; chunk], out, pos: 0, len: 0, done: false }))
|
||||
}
|
||||
|
||||
/// The encoding [`decode`](crate::encoding::decode) finds for the file, its BOM length and
|
||||
/// whether it has a BOM; `None` for binary content.
|
||||
fn detect<R: Read>(
|
||||
open: &mut impl FnMut() -> io::Result<R>,
|
||||
chunk: usize,
|
||||
) -> io::Result<Option<(&'static Encoding, usize, bool)>> {
|
||||
let mut reader = open()?;
|
||||
let mut head = vec![0; SNIFF_LEN];
|
||||
let n = read_full(&mut reader, &mut head)?;
|
||||
head.truncate(n);
|
||||
if let Some((enc, bom_len)) = Encoding::for_bom(&head) {
|
||||
return Ok(Some((enc, bom_len, true)));
|
||||
}
|
||||
if head.contains(&0) {
|
||||
return Ok(sniff_utf16(&head).map(|enc| (enc, 0, false)));
|
||||
}
|
||||
let mut detector = chardetng::EncodingDetector::new();
|
||||
let mut utf8 = Utf8Check::default();
|
||||
detector.feed(&head, false);
|
||||
utf8.feed(&head);
|
||||
if n == SNIFF_LEN {
|
||||
let mut buf = vec![0; chunk];
|
||||
loop {
|
||||
let n = read_retry(&mut reader, &mut buf)?;
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
detector.feed(&buf[..n], false);
|
||||
utf8.feed(&buf[..n]);
|
||||
}
|
||||
}
|
||||
detector.feed(&[], true);
|
||||
let encoding = if utf8.is_valid() { UTF_8 } else { detector.guess(None, true) };
|
||||
Ok(Some((encoding, 0, false)))
|
||||
}
|
||||
|
||||
/// Reads until `buf` is full or the reader ends.
|
||||
fn read_full(reader: &mut impl Read, buf: &mut [u8]) -> io::Result<usize> {
|
||||
let mut filled = 0;
|
||||
while filled < buf.len() {
|
||||
match read_retry(reader, &mut buf[filled..])? {
|
||||
0 => break,
|
||||
n => filled += n,
|
||||
}
|
||||
}
|
||||
Ok(filled)
|
||||
}
|
||||
|
||||
fn read_retry(reader: &mut impl Read, buf: &mut [u8]) -> io::Result<usize> {
|
||||
loop {
|
||||
match reader.read(buf) {
|
||||
Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
|
||||
result => return result,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks that bytes fed in pieces form valid UTF-8, as `std::str::from_utf8` does for the whole.
|
||||
#[derive(Default)]
|
||||
struct Utf8Check {
|
||||
/// The start of a character cut by the end of the previous piece.
|
||||
tail: Vec<u8>,
|
||||
invalid: bool,
|
||||
}
|
||||
|
||||
impl Utf8Check {
|
||||
fn feed(&mut self, mut bytes: &[u8]) {
|
||||
if self.invalid {
|
||||
return;
|
||||
}
|
||||
while !self.tail.is_empty() && !bytes.is_empty() {
|
||||
self.tail.push(bytes[0]);
|
||||
bytes = &bytes[1..];
|
||||
match std::str::from_utf8(&self.tail) {
|
||||
Ok(_) => self.tail.clear(),
|
||||
Err(e) if e.error_len().is_none() => {}
|
||||
Err(_) => {
|
||||
self.invalid = true;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
if !self.tail.is_empty() {
|
||||
return;
|
||||
}
|
||||
match std::str::from_utf8(bytes) {
|
||||
Ok(_) => {}
|
||||
Err(e) if e.error_len().is_none() => self.tail.extend_from_slice(&bytes[e.valid_up_to()..]),
|
||||
Err(_) => self.invalid = true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether everything fed so far was UTF-8 (a truncated final character is not).
|
||||
fn is_valid(&self) -> bool {
|
||||
!self.invalid && self.tail.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
impl<R: Read> Read for DecodedReader<R> {
|
||||
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
|
||||
while self.pos == self.len {
|
||||
if self.done {
|
||||
return Ok(0);
|
||||
}
|
||||
let n = read_retry(&mut self.reader, &mut self.raw)?;
|
||||
let last = n == 0;
|
||||
let needed = self.decoder.max_utf8_buffer_length(n).unwrap_or(n * 3 + 16);
|
||||
if self.out.len() < needed {
|
||||
self.out.resize(needed, 0);
|
||||
}
|
||||
// Malformed input becomes U+FFFD, as in `decode_without_bom_handling`.
|
||||
let (_, _, written, _) = self.decoder.decode_to_utf8(&self.raw[..n], &mut self.out, last);
|
||||
self.pos = 0;
|
||||
self.len = written;
|
||||
self.done = last;
|
||||
}
|
||||
let n = buf.len().min(self.len - self.pos);
|
||||
buf[..n].copy_from_slice(&self.out[self.pos..self.pos + n]);
|
||||
self.pos += n;
|
||||
Ok(n)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::decode_text;
|
||||
|
||||
/// Hands out at most `step` bytes per read, so chunk edges fall everywhere.
|
||||
struct Trickle<'a> {
|
||||
bytes: &'a [u8],
|
||||
step: usize,
|
||||
}
|
||||
|
||||
impl Read for Trickle<'_> {
|
||||
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
|
||||
let n = buf.len().min(self.step).min(self.bytes.len());
|
||||
buf[..n].copy_from_slice(&self.bytes[..n]);
|
||||
self.bytes = &self.bytes[n..];
|
||||
Ok(n)
|
||||
}
|
||||
}
|
||||
|
||||
fn streamed(bytes: &[u8], fallback: Option<&str>, chunk: usize, step: usize) -> Option<Vec<u8>> {
|
||||
let reader = decode_stream_in(|| Ok(Trickle { bytes, step }), fallback, chunk).unwrap()?;
|
||||
let mut out = Vec::new();
|
||||
let mut reader = reader;
|
||||
// Small reads too: the consumer's buffer is not the chunk either.
|
||||
let mut buf = [0; 7];
|
||||
loop {
|
||||
let n = reader.read(&mut buf).unwrap();
|
||||
if n == 0 {
|
||||
return Some(out);
|
||||
}
|
||||
out.extend_from_slice(&buf[..n]);
|
||||
}
|
||||
}
|
||||
|
||||
fn utf16(text: &str, bom: bool, big: bool) -> Vec<u8> {
|
||||
let mut bytes =
|
||||
if bom { vec![if big { 0xFE } else { 0xFF }, if big { 0xFF } else { 0xFE }] } else { Vec::new() };
|
||||
for unit in text.encode_utf16() {
|
||||
bytes.extend(if big { unit.to_be_bytes() } else { unit.to_le_bytes() });
|
||||
}
|
||||
bytes
|
||||
}
|
||||
|
||||
/// Text with multi-byte characters and surrogate pairs at every alignment.
|
||||
fn sample(len: usize) -> String {
|
||||
let mut text = String::new();
|
||||
let pieces = [
|
||||
"ascii line\n",
|
||||
"caf\u{e9} cr\u{e8}me\n",
|
||||
"\u{4e2d}\u{6587}\u{6d4b}\u{8bd5}\n",
|
||||
"\u{1f600}\u{1f4a9} x\n",
|
||||
"\u{20ac}5\r\n",
|
||||
];
|
||||
let mut i = 0;
|
||||
while text.len() < len {
|
||||
text.push_str(pieces[i * 7 % pieces.len()]);
|
||||
i += 1;
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
fn inputs() -> Vec<(String, Vec<u8>)> {
|
||||
let text = sample(1500);
|
||||
let mut inputs = vec![
|
||||
("utf8".to_string(), text.clone().into_bytes()),
|
||||
("utf8 bom".to_string(), [&[0xEF, 0xBB, 0xBF][..], text.as_bytes()].concat()),
|
||||
("utf16le bom".to_string(), utf16(&text, true, false)),
|
||||
("utf16be bom".to_string(), utf16(&text, true, true)),
|
||||
("utf16le".to_string(), utf16(&sample(1500).replace(|c: char| !c.is_ascii(), "e"), false, false)),
|
||||
("utf16be".to_string(), utf16(&sample(1500).replace(|c: char| !c.is_ascii(), "e"), false, true)),
|
||||
(
|
||||
"gbk".to_string(),
|
||||
encoding_rs::GBK
|
||||
.encode(&sample(1500).replace(['\u{1f600}', '\u{1f4a9}', '\u{20ac}'], ""))
|
||||
.0
|
||||
.into_owned(),
|
||||
),
|
||||
(
|
||||
"latin1".to_string(),
|
||||
encoding_rs::WINDOWS_1252
|
||||
.encode(&sample(1500).replace(|c: char| c as u32 > 0xff && c != '\u{20ac}', ""))
|
||||
.0
|
||||
.into_owned(),
|
||||
),
|
||||
("empty".to_string(), Vec::new()),
|
||||
("binary".to_string(), b"\x7FELF\x02\x01\x01\x00\x00\x00 and text".repeat(100)),
|
||||
("late nul".to_string(), [&b"abc caf\xe9 ".repeat(1200)[..], b"\0 tail"].concat()),
|
||||
("truncated utf8".to_string(), text.as_bytes()[..text.len() - 1].to_vec()),
|
||||
("truncated utf16".to_string(), utf16(&text, true, false)[..utf16(&text, true, false).len() - 1].to_vec()),
|
||||
(
|
||||
"lone surrogate".to_string(),
|
||||
[&[0xFF, 0xFE][..], &[0x3D, 0xD8, b'a', 0][..], &utf16(&text, false, false)[..]].concat(),
|
||||
),
|
||||
("invalid in the middle".to_string(), [text.as_bytes(), b"\xff\xfe\xc3", text.as_bytes()].concat()),
|
||||
(
|
||||
"shift jis".to_string(),
|
||||
encoding_rs::SHIFT_JIS
|
||||
.encode(
|
||||
"\u{3053}\u{3093}\u{306b}\u{3061}\u{306f}\u{4e16}\u{754c}\u{ff76}\u{ff85}\n"
|
||||
.repeat(200)
|
||||
.as_str(),
|
||||
)
|
||||
.0
|
||||
.into_owned(),
|
||||
),
|
||||
];
|
||||
// The evidence for the encoding comes long after the sniffed head.
|
||||
let chinese = "\u{4e2d}\u{6587}\u{6d4b}\u{8bd5}\u{4e00}\u{6bb5}\u{6587}\u{672c}\n".repeat(300);
|
||||
let gbk = encoding_rs::GBK.encode(&chinese).0.into_owned();
|
||||
let head = "plain ascii line\n".repeat(1500);
|
||||
inputs.push(("gbk after a long ascii head".to_string(), [head.as_bytes(), &gbk].concat()));
|
||||
// Characters at every alignment against the sniffing head and the chunks.
|
||||
for pad in 0..5 {
|
||||
let mut bytes = "x".repeat(SNIFF_LEN - 3 + pad).into_bytes();
|
||||
bytes.extend("\u{4e2d}\u{1f600}\u{e9}".as_bytes());
|
||||
inputs.push((format!("utf8 at the head edge {pad}"), bytes));
|
||||
let mut bytes = "y".repeat(SNIFF_LEN - 2 + pad).into_bytes();
|
||||
bytes.extend([0xE9, b'z', 0xFF, b'e']);
|
||||
inputs.push((format!("latin1 at the head edge {pad}"), bytes));
|
||||
}
|
||||
inputs
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn streamed_text_equals_the_whole_file_decode() {
|
||||
for (name, bytes) in inputs() {
|
||||
for fallback in [None, Some("gbk"), Some("windows-1252"), Some("utf-16le"), Some("nonsense")] {
|
||||
let expected = decode_text(&bytes, fallback).map(String::into_bytes);
|
||||
for chunk in [1, 2, 3, 4, 5, 16, 255, 4096, CHUNK] {
|
||||
for step in [1, 3, 8192, usize::MAX] {
|
||||
assert_eq!(
|
||||
streamed(&bytes, fallback, chunk, step),
|
||||
expected,
|
||||
"{name}, fallback {fallback:?}, chunk {chunk}, step {step}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn utf8_check_matches_from_utf8_for_any_split() {
|
||||
let samples: [&[u8]; 6] = [
|
||||
"a\u{e9}\u{4e2d}\u{1f600}z".as_bytes(),
|
||||
b"ab\xe4\xb8",
|
||||
b"\xe4\xb8a",
|
||||
b"\xf0\x9f\x98",
|
||||
b"ok\xc3(",
|
||||
b"\xed\xa0\x80",
|
||||
];
|
||||
for bytes in samples {
|
||||
for first in 0..=bytes.len() {
|
||||
for second in first..=bytes.len() {
|
||||
let mut check = Utf8Check::default();
|
||||
check.feed(&bytes[..first]);
|
||||
check.feed(&bytes[first..second]);
|
||||
check.feed(&bytes[second..]);
|
||||
assert_eq!(check.is_valid(), std::str::from_utf8(bytes).is_ok(), "{bytes:?} {first} {second}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_at_most_a_bounded_number_of_bytes_per_step() {
|
||||
// A reader that fails if asked for more than one chunk shows nothing is read whole.
|
||||
struct Capped<'a>(&'a [u8]);
|
||||
impl Read for Capped<'_> {
|
||||
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
|
||||
assert!(buf.len() <= SNIFF_LEN.max(1024), "asked for {} bytes", buf.len());
|
||||
let n = buf.len().min(self.0.len());
|
||||
buf[..n].copy_from_slice(&self.0[..n]);
|
||||
self.0 = &self.0[n..];
|
||||
Ok(n)
|
||||
}
|
||||
}
|
||||
let bytes = encoding_rs::WINDOWS_1252.encode(&"caf\u{e9}\n".repeat(50_000)).0.into_owned();
|
||||
let mut reader = decode_stream_in(|| Ok(Capped(&bytes)), None, 1024).unwrap().unwrap();
|
||||
let mut text = String::new();
|
||||
reader.read_to_string(&mut text).unwrap();
|
||||
assert_eq!(text, "caf\u{e9}\n".repeat(50_000));
|
||||
assert!(reader.out.len() <= 4 * 1024 + 16 && reader.raw.len() == 1024);
|
||||
}
|
||||
}
|
||||
@@ -103,7 +103,7 @@ pub fn save_properties_text(path: &Path, text: &str) -> IdeResult<f64> {
|
||||
}
|
||||
|
||||
/// Detects BOM-less UTF-16 from the distribution of NUL bytes in mostly-ASCII text.
|
||||
fn sniff_utf16(sample: &[u8]) -> Option<&'static Encoding> {
|
||||
pub(crate) fn sniff_utf16(sample: &[u8]) -> Option<&'static Encoding> {
|
||||
if sample.len() < 4 {
|
||||
return None;
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
mod archive;
|
||||
mod bytes;
|
||||
mod compare;
|
||||
mod decode_stream;
|
||||
mod encoding;
|
||||
mod ops;
|
||||
mod private;
|
||||
@@ -30,6 +31,7 @@ pub use compare::{
|
||||
DirectoryCompareEntry, DirectoryCompareMode, DirectoryCompareProgress, DirectoryCompareStatus, DirectorySyncAction,
|
||||
DirectorySyncFailure, DirectorySyncOperation, DirectorySyncProgress, compare_directories, copy_merge,
|
||||
};
|
||||
pub use decode_stream::{DecodedReader, decode_stream};
|
||||
use encoding::SNIFF_LEN;
|
||||
pub use encoding::{
|
||||
LARGE_FILE_THRESHOLD, MAX_OPEN_SIZE, READ_ONLY_THRESHOLD, decode_properties_escapes, encode,
|
||||
|
||||
@@ -464,15 +464,12 @@ impl LocalHistory {
|
||||
/// The watcher saw `paths` disappear: files with history that are gone get a
|
||||
/// "Deleted" entry pointing at their last content (unless one was recorded already).
|
||||
pub fn note_removed(&self, paths: &[PathBuf]) -> IdeResult<()> {
|
||||
if paths.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let mut state = self.state.lock();
|
||||
let gone: Vec<(PathBuf, String, u64)> = {
|
||||
let mut latest: HashMap<&Path, &HistoryEntry> = HashMap::new();
|
||||
for e in state.entries.iter().filter(|e| e.kind == HistoryKind::Snapshot) {
|
||||
if paths.iter().any(|p| e.path.starts_with(p)) {
|
||||
latest.insert(&e.path, e);
|
||||
}
|
||||
}
|
||||
latest
|
||||
latest_snapshots_under(&state.entries, paths)
|
||||
.into_values()
|
||||
.filter(|e| e.label != DELETED && !e.path.exists())
|
||||
.map(|e| (e.path.to_path_buf(), e.id.clone(), e.size))
|
||||
@@ -700,9 +697,32 @@ fn collect_files(dir: &Path, limit: usize, out: &mut Vec<PathBuf>) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The newest snapshot entry of every file at or below one of `roots`.
|
||||
/// Each entry is checked by looking up its own path and its ancestors in a set of the roots,
|
||||
/// so the cost does not grow with the number of roots (a batch can name tens of thousands).
|
||||
fn latest_snapshots_under<'a>(entries: &'a [HistoryEntry], roots: &[PathBuf]) -> HashMap<&'a Path, &'a HistoryEntry> {
|
||||
let roots: HashSet<&Path> = roots.iter().map(PathBuf::as_path).collect();
|
||||
let mut latest = HashMap::new();
|
||||
for e in entries.iter().filter(|e| e.kind == HistoryKind::Snapshot) {
|
||||
if e.path.ancestors().any(|dir| {
|
||||
#[cfg(test)]
|
||||
tests::ROOT_LOOKUPS.with(|n| n.set(n.get() + 1));
|
||||
roots.contains(dir)
|
||||
}) {
|
||||
latest.insert(&*e.path, e);
|
||||
}
|
||||
}
|
||||
latest
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::cell::Cell;
|
||||
|
||||
thread_local! {
|
||||
pub(super) static ROOT_LOOKUPS: Cell<usize> = const { Cell::new(0) };
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn record_list_dedupe_prune() {
|
||||
@@ -846,6 +866,79 @@ mod tests {
|
||||
assert_eq!(h.stored_bytes(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn note_removed_work_does_not_grow_with_the_number_of_removed_paths() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().join("project");
|
||||
let h = LocalHistory::open(&tmp.path().join("history"), &root).unwrap();
|
||||
let kept: Vec<PathBuf> =
|
||||
(0..300).map(|i| root.join("keep").join(format!("g{}", i / 50)).join(format!("f{i}.rs"))).collect();
|
||||
{
|
||||
let mut state = h.state.lock();
|
||||
for p in &kept {
|
||||
state.entries.push(HistoryEntry::snapshot(p, "x", "External change", now_ms()));
|
||||
}
|
||||
}
|
||||
let removed: Vec<PathBuf> =
|
||||
(0..5_000).map(|i| root.join("gone").join(format!("g{}", i / 50)).join(format!("f{i}.rs"))).collect();
|
||||
|
||||
ROOT_LOOKUPS.with(|n| n.set(0));
|
||||
h.note_removed(&removed).unwrap();
|
||||
|
||||
// At most one lookup per path component of each entry, however many paths were removed.
|
||||
let bound: usize = kept.iter().map(|p| p.components().count()).sum();
|
||||
let lookups = ROOT_LOOKUPS.with(Cell::get);
|
||||
assert!(lookups > 0 && lookups <= bound, "{lookups} root lookups for {} entries (bound {bound})", kept.len());
|
||||
assert_eq!(h.state.lock().entries.len(), kept.len(), "nothing was deleted, so nothing is appended");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn note_removed_marks_only_files_gone_under_a_removed_path() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().join("project");
|
||||
fs::create_dir_all(root.join("dir")).unwrap();
|
||||
fs::create_dir_all(root.join("dir2")).unwrap();
|
||||
let h = LocalHistory::open(&tmp.path().join("history"), &root).unwrap();
|
||||
let (a, b) = (root.join("dir/a.txt"), root.join("dir/b.txt"));
|
||||
let sibling = root.join("dir2/c.txt");
|
||||
let (solo, multi, present, already) =
|
||||
(root.join("solo.txt"), root.join("multi.txt"), root.join("present.txt"), root.join("already.txt"));
|
||||
for (path, text) in [(&a, "a"), (&b, "b"), (&sibling, "c"), (&solo, "s"), (&present, "p"), (&already, "d")] {
|
||||
h.record(path, text, "Saved").unwrap();
|
||||
}
|
||||
h.record(&multi, "v1", "Saved").unwrap();
|
||||
std::thread::sleep(std::time::Duration::from_millis(2));
|
||||
h.record(&multi, "v2", "Saved").unwrap();
|
||||
h.put_label(&root, "Before Git checkout").unwrap();
|
||||
let snapshots = |path: &Path| -> Vec<HistoryEntry> {
|
||||
h.list(path).unwrap().into_iter().filter(|e| e.kind == HistoryKind::Snapshot).collect()
|
||||
};
|
||||
fs::write(&present, "p").unwrap();
|
||||
h.note_removed(std::slice::from_ref(&already)).unwrap();
|
||||
let entries_before_removal = h.state.lock().entries.len();
|
||||
assert_eq!(snapshots(&already)[0].label, DELETED, "recorded as deleted before the batch");
|
||||
let already_entries = snapshots(&already).len();
|
||||
|
||||
// `dir2` shares the name prefix of `dir` but is not below it.
|
||||
h.note_removed(&[]).unwrap();
|
||||
assert_eq!(h.state.lock().entries.len(), entries_before_removal, "an empty batch changes nothing");
|
||||
h.note_removed(&[root.join("dir"), solo.clone(), multi.clone(), present.clone(), already.clone()]).unwrap();
|
||||
|
||||
for (path, text) in [(&a, "a"), (&b, "b"), (&solo, "s"), (&multi, "v2")] {
|
||||
let newest = &snapshots(path)[0];
|
||||
assert_eq!((newest.label.as_str(), h.content(&newest.id).unwrap().as_str()), (DELETED, text));
|
||||
}
|
||||
assert_eq!(snapshots(&multi).len(), 3, "Saved v1, Saved v2, Deleted");
|
||||
assert!(snapshots(&sibling).iter().all(|e| e.label != DELETED), "sibling with a shared name prefix");
|
||||
assert!(snapshots(&present).iter().all(|e| e.label != DELETED), "still on disk");
|
||||
assert_eq!(snapshots(&already).len(), already_entries, "already recorded as deleted");
|
||||
assert_eq!(
|
||||
h.state.lock().entries.len(),
|
||||
entries_before_removal + 4,
|
||||
"one Deleted entry each for a, b, solo and multi"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deletion_undo_captures_current_bytes_and_empty_folders() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import { expect, test } from "./fixtures";
|
||||
|
||||
async function show(page: Page, action: string) {
|
||||
await page.evaluate(async (action) => {
|
||||
const actions = "/src/platform/actions.ts";
|
||||
if (!(await (await import(/* @vite-ignore */ actions)).executeAction(action))) throw Error(action);
|
||||
}, action);
|
||||
}
|
||||
|
||||
test("analysis scope fields align with their radio choices and retain their values", async ({ workbench: page }) => {
|
||||
await page.evaluate(async () => {
|
||||
const search = "/src/platform/search.ts";
|
||||
(await import(/* @vite-ignore */ search)).saveCustomScopes([
|
||||
{ name: "Frontend", pattern: "file:src//*" },
|
||||
{ name: "Tests", pattern: "file:tests//*" },
|
||||
]);
|
||||
});
|
||||
await show(page, "analyze.inspectCode");
|
||||
const dialog = page.getByRole("dialog", { name: "Specify Inspection Scope" });
|
||||
const scope = dialog.getByRole("group", { name: "Scope" });
|
||||
const directory = scope.getByRole("textbox", { name: "Directory" });
|
||||
const custom = scope.getByRole("button", { name: "Custom scope", exact: true });
|
||||
const radio = scope.getByRole("radio", { name: "Module or directory" });
|
||||
const label = scope.getByText("Module or directory", { exact: true });
|
||||
|
||||
await radio.check();
|
||||
const path = (await directory.boundingBox())!;
|
||||
const choice = (await label.boundingBox())!;
|
||||
expect(path.y + path.height / 2).toBeCloseTo(choice.y + choice.height / 2, 0);
|
||||
await directory.fill("/dev/acme-api/src");
|
||||
await expect(custom).toBeDisabled();
|
||||
await scope.getByRole("radio", { name: "Custom scope", exact: true }).check();
|
||||
await expect(directory).toBeDisabled();
|
||||
expect((await custom.boundingBox())!.x).toBeCloseTo(path.x, 0);
|
||||
await custom.click();
|
||||
await page.getByRole("option", { name: /^Tests/ }).click();
|
||||
await expect(custom).toContainText("Tests");
|
||||
|
||||
await radio.check();
|
||||
await expect(directory).toHaveValue("/dev/acme-api/src");
|
||||
await scope.getByRole("radio", { name: "Custom scope", exact: true }).check();
|
||||
await expect(custom).toContainText("Tests");
|
||||
await page.setViewportSize({ width: 400, height: 640 });
|
||||
const stacked = (await directory.boundingBox())!;
|
||||
const customBox = (await custom.boundingBox())!;
|
||||
const radioBox = (await label.boundingBox())!;
|
||||
const next = (await scope.getByText("Current file", { exact: true }).boundingBox())!;
|
||||
expect(stacked.y).toBeGreaterThan(radioBox.y + radioBox.height);
|
||||
expect(stacked.y + stacked.height).toBeLessThan(next.y);
|
||||
expect(stacked.x).toBeCloseTo(customBox.x, 0);
|
||||
expect(await scope.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
|
||||
});
|
||||
|
||||
for (const [action, title] of [
|
||||
["code.cleanup", "Run Code Cleanup"],
|
||||
["analyze.locateDuplicates", "Locate Duplicates"],
|
||||
["find.structural", "Structural Search"],
|
||||
["find.replaceStructural", "Structural Replace"],
|
||||
] as const) {
|
||||
test(`${title} keeps directory options with their scope choice`, async ({ workbench: page }) => {
|
||||
await show(page, action);
|
||||
const dialog = page.getByRole("dialog", { name: title });
|
||||
const scope = dialog.getByRole("group", { name: "Scope" });
|
||||
const directory = scope.getByRole("textbox", { name: "Directory" });
|
||||
await expect(directory).toBeDisabled();
|
||||
await scope.getByRole("radio", { name: "Module or directory" }).check();
|
||||
await expect(directory).toBeEnabled();
|
||||
await expect(scope.getByRole("button", { name: "Browse…" })).toBeEnabled();
|
||||
});
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
* with its frames and variables, and stepping and resuming go back to the adapter. The adapter is
|
||||
* stubbed at the IPC layer; `crates/ide-dap/tests` drives real ones.
|
||||
*/
|
||||
import type { JvmMemoryResult } from "../src/platform/ipc";
|
||||
import { expect, ipcCalls, openFromTree, stubDesktop, test } from "./fixtures";
|
||||
|
||||
const ROOT = "/dev/acme-api";
|
||||
@@ -114,6 +115,83 @@ test("stops at a breakpoint, shows frames and variables, steps and resumes", asy
|
||||
await expect(debug.getByText("CreateOrderRequest(sku='A-1', qty=2)")).toBeHidden();
|
||||
});
|
||||
|
||||
test("Memory gives class filtering the available toolbar width and exposes changed-only filtering", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
const rows = [
|
||||
{ name: "OrderCache", instances: 64, deltaInstances: 12 },
|
||||
{ name: "OrderRepository", instances: 16, deltaInstances: 0 },
|
||||
].map((row) => ({ ...row, bytes: row.instances * 16, deltaBytes: null, module: null, ambiguous: false }));
|
||||
const result: JvmMemoryResult = {
|
||||
status: "ready",
|
||||
snapshot: {
|
||||
rows,
|
||||
totalInstances: 80,
|
||||
totalBytes: 1280,
|
||||
javaVersion: "21",
|
||||
takenWhileSuspended: true,
|
||||
hasBaseline: true,
|
||||
elapsedMs: 5,
|
||||
source: "debugger",
|
||||
},
|
||||
};
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(
|
||||
async ({ result, id }) => {
|
||||
const caps = { jvmMemory: true, jvmHeap: true };
|
||||
window.__ipc.handlers.debug_capabilities = () => caps;
|
||||
window.__ipc.handlers.debug_jvm_memory_classes = () => result;
|
||||
const debugPath = "/src/features/debugger/state.ts";
|
||||
const { adoptSession } = await import(/* @vite-ignore */ debugPath);
|
||||
adoptSession(id, { adapter: "java-debug", name: "Billing Service", status: "paused", caps });
|
||||
const dockPath = "/src/workbench/toolwindows/store.ts";
|
||||
const layout = await import(/* @vite-ignore */ dockPath);
|
||||
layout.moveToolWindow("debug", "bottom");
|
||||
layout.setToolWindowSize("bottom", 300);
|
||||
layout.showToolWindow("debug", true);
|
||||
},
|
||||
{ result, id: SESSION },
|
||||
);
|
||||
|
||||
const debug = page.getByRole("region", { name: "Debug", exact: true });
|
||||
await debug.getByRole("tab", { name: "Memory" }).click();
|
||||
const toolbar = debug.getByRole("toolbar", { name: "Memory", exact: true });
|
||||
const filter = toolbar.getByRole("textbox", { name: "Filter classes" });
|
||||
const options = toolbar.getByRole("button", { name: "View Options" });
|
||||
const grid = debug.getByRole("grid", { name: "Memory", exact: true });
|
||||
await expect(grid.getByText("OrderRepository", { exact: true })).toBeVisible();
|
||||
expect((await filter.boundingBox())!.width).toBeGreaterThan((await toolbar.boundingBox())!.width / 2);
|
||||
|
||||
await page.evaluate(async () => {
|
||||
const dockPath = "/src/workbench/toolwindows/store.ts";
|
||||
const layout = await import(/* @vite-ignore */ dockPath);
|
||||
layout.moveToolWindow("debug", "right");
|
||||
layout.setToolWindowSize("right", 330);
|
||||
});
|
||||
await expect.poll(async () => (await toolbar.boundingBox())!.width).toBeCloseTo(330, 0);
|
||||
const bar = (await toolbar.boundingBox())!;
|
||||
const gear = (await options.boundingBox())!;
|
||||
const input = (await filter.boundingBox())!;
|
||||
expect(input.width).toBeGreaterThan(bar.width / 2);
|
||||
expect(input.x + input.width).toBeLessThan(gear.x);
|
||||
expect(gear.x + gear.width).toBeLessThanOrEqual(bar.x + bar.width);
|
||||
|
||||
await filter.fill("cache");
|
||||
await expect(grid.getByText("OrderRepository", { exact: true })).toBeHidden();
|
||||
await toolbar.getByRole("button", { name: "Clear", exact: true }).click();
|
||||
await expect(grid.getByText("OrderRepository", { exact: true })).toBeVisible();
|
||||
|
||||
await options.press("Enter");
|
||||
const changed = page.getByRole("menuitemcheckbox", { name: "Changed only" });
|
||||
await expect(changed).not.toBeChecked();
|
||||
await changed.press("Enter");
|
||||
await expect(grid.getByText("OrderRepository", { exact: true })).toBeHidden();
|
||||
await expect(options).toHaveAttribute("aria-pressed", "true");
|
||||
await expect(options).toBeFocused();
|
||||
await options.press("Enter");
|
||||
await expect(changed).toBeChecked();
|
||||
});
|
||||
|
||||
test("Evaluate keeps a multiline expression and its result visible in a short dialog", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 580, height: 420 });
|
||||
await stubDesktop(page);
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
|
||||
|
||||
async function openTable(page: Page, columns: number) {
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async (columns) => {
|
||||
window.__ipc.handlers.debug_evaluate_in = ({ expression }) => {
|
||||
const query = String(expression);
|
||||
const sliced = query.includes("totals.iloc[:2, :2]");
|
||||
const visibleColumns = sliced ? 2 : Math.min(30, columns);
|
||||
const columnsInFrame = sliced ? 2 : columns;
|
||||
const start = query.includes("100, 100,") ? 100 : 0;
|
||||
const rows = sliced ? 2 : 220;
|
||||
const count = sliced ? 2 : 100;
|
||||
const result = query.includes("missing_table")
|
||||
? { error: "NameError: missing_table" }
|
||||
: {
|
||||
kind: "frame",
|
||||
shape: [rows, columnsInFrame],
|
||||
rows,
|
||||
columns: columnsInFrame,
|
||||
headers: Array.from({ length: visibleColumns }, (_, i) => `Amount ${i + 1}`),
|
||||
dtypes: Array.from({ length: visibleColumns }, () => "int64"),
|
||||
index: Array.from({ length: count }, (_, i) => String(i + start)),
|
||||
cells: Array.from({ length: count }, (_, row) =>
|
||||
Array.from({ length: visibleColumns }, (_, column) => String((row + start + 1) * 10 + column)),
|
||||
),
|
||||
};
|
||||
return {
|
||||
name: "",
|
||||
value: JSON.stringify(JSON.stringify(result)),
|
||||
typeName: "str",
|
||||
variablesReference: 0,
|
||||
evaluateName: null,
|
||||
};
|
||||
};
|
||||
const stateModule = "/src/features/debugger/state.ts";
|
||||
const overlaysModule = "/src/features/debugger/ui/popoverStore.ts";
|
||||
const { adoptSession } = await import(/* @vite-ignore */ stateModule);
|
||||
const { openTableView } = await import(/* @vite-ignore */ overlaysModule);
|
||||
adoptSession(91, { name: "Settlement review", adapter: "debugpy", status: "paused", selectedFrame: 11 });
|
||||
openTableView("totals", 91);
|
||||
}, columns);
|
||||
const dialog = page.getByRole("dialog", { name: "Table view of totals", exact: true });
|
||||
await expect(dialog.getByRole("table")).toBeVisible();
|
||||
return dialog;
|
||||
}
|
||||
|
||||
test("View as Table gives the grid the dialog width and puts the expression below it", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 1120, height: 760 });
|
||||
const dialog = await openTable(page, 3);
|
||||
const scroll = dialog.getByRole("region", { name: "Table", exact: true });
|
||||
const grid = dialog.getByRole("table");
|
||||
const expression = dialog.getByRole("textbox", { name: "Expression", exact: true });
|
||||
const shape = dialog.getByText("Shape (220, 3)", { exact: true });
|
||||
const body = (await scroll.boundingBox())!;
|
||||
const input = (await expression.boundingBox())!;
|
||||
expect(input.y).toBeGreaterThan(body.y + body.height);
|
||||
expect((await shape.boundingBox())!.y).toBeLessThan(body.y);
|
||||
expect(Math.abs((await grid.boundingBox())!.width - (await scroll.evaluate((el) => el.clientWidth)))).toBeLessThan(1);
|
||||
expect((await dialog.boundingBox())!.width).toBeCloseTo(700, 0);
|
||||
await expect(expression).toBeFocused();
|
||||
await expect(grid).toHaveCSS("font-family", /Inter/);
|
||||
await expect(grid.getByRole("columnheader").nth(1)).toHaveCSS("text-align", "center");
|
||||
await expect(grid.getByRole("rowheader").first()).toHaveCSS("text-align", "center");
|
||||
await expect(grid.getByRole("cell").first()).toHaveCSS("text-align", /^(start|left)$/);
|
||||
});
|
||||
|
||||
test("View as Table keeps paging, slice input and Close usable in a narrow window", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 450, height: 620 });
|
||||
const dialog = await openTable(page, 36);
|
||||
const expression = dialog.getByRole("textbox", { name: "Expression", exact: true });
|
||||
const scroll = dialog.getByRole("region", { name: "Table", exact: true });
|
||||
const rows = dialog.getByRole("button", { name: "Next Rows", exact: true });
|
||||
const columns = dialog.getByRole("button", { name: "Next Columns", exact: true });
|
||||
const close = dialog.getByRole("button", { name: "Close", exact: true }).filter({ hasText: /^Close$/ });
|
||||
const input = (await expression.boundingBox())!;
|
||||
const grid = (await scroll.boundingBox())!;
|
||||
expect(input.y).toBeGreaterThan(grid.y + grid.height);
|
||||
expect(input.width).toBeCloseTo(grid.width, 0);
|
||||
for (const control of [expression, rows, columns, close]) await expect(control).toBeInViewport({ ratio: 0.98 });
|
||||
await scroll.evaluate((el) => {
|
||||
el.scrollLeft = 300;
|
||||
el.scrollTop = 150;
|
||||
});
|
||||
await expect(dialog.getByRole("rowheader").filter({ hasText: /^9$/ })).toBeInViewport({ ratio: 0.98 });
|
||||
await rows.click();
|
||||
await expect(dialog.getByText("Rows 101–200 of 220", { exact: true })).toBeVisible();
|
||||
await expect
|
||||
.poll(() => ipcCalls(page, "debug_evaluate_in"))
|
||||
.toContainEqual(expect.objectContaining({ expression: expect.stringContaining("100, 100, 0, 30") }));
|
||||
await expression.fill("totals.iloc[:2, :2]");
|
||||
await expression.press("Enter");
|
||||
const sliced = page.getByRole("dialog", { name: "Table view of totals.iloc[:2, :2]", exact: true });
|
||||
await expect(sliced.getByText("Shape (2, 2)", { exact: true })).toBeVisible();
|
||||
const slicedExpression = sliced.getByRole("textbox", { name: "Expression", exact: true });
|
||||
await slicedExpression.fill("missing_table");
|
||||
await slicedExpression.press("Enter");
|
||||
const failed = page.getByRole("dialog", { name: "Table view of missing_table", exact: true });
|
||||
const alert = failed.getByRole("alert");
|
||||
await expect(alert).toHaveText("NameError: missing_table");
|
||||
expect((await alert.boundingBox())!.y).toBeGreaterThan(
|
||||
(await failed.getByRole("textbox", { name: "Expression", exact: true }).boundingBox())!.y,
|
||||
);
|
||||
await failed
|
||||
.getByRole("button", { name: "Close", exact: true })
|
||||
.filter({ hasText: /^Close$/ })
|
||||
.click();
|
||||
await expect(failed).toHaveCount(0);
|
||||
});
|
||||
@@ -0,0 +1,81 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import { expect, test } from "./fixtures";
|
||||
|
||||
async function openEditorTabsSettings(page: Page) {
|
||||
await page.evaluate(async () => {
|
||||
const actionsModule = "/src/platform/actions.ts";
|
||||
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
|
||||
await executeAction("file.settings", "editor.general.editorTabs");
|
||||
});
|
||||
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
|
||||
await expect(dialog.getByRole("region", { name: "Closing Policy", exact: true })).toBeVisible();
|
||||
return dialog;
|
||||
}
|
||||
|
||||
test("Editor Tabs aligns appearance fields and stacks closing choices at both widths", async ({ workbench: page }) => {
|
||||
const settings = await openEditorTabsSettings(page);
|
||||
const appearance = settings.getByRole("region", { name: "Appearance", exact: true });
|
||||
const placement = appearance.getByRole("button", { name: "Tab placement", exact: true });
|
||||
const closePosition = appearance.getByRole("button", { name: "Close button position", exact: true });
|
||||
const closing = settings.getByRole("region", { name: "Closing Policy", exact: true });
|
||||
const limit = closing.getByRole("textbox", { name: "Tab limit", exact: true });
|
||||
const footer = settings.getByRole("button", { name: "OK", exact: true });
|
||||
|
||||
for (const width of [1100, 580]) {
|
||||
await page.setViewportSize({ width, height: 760 });
|
||||
const placementBox = (await placement.boundingBox())!;
|
||||
const closeBox = (await closePosition.boundingBox())!;
|
||||
expect(Math.abs(placementBox.x - closeBox.x)).toBeLessThanOrEqual(1);
|
||||
expect(Math.abs(placementBox.width - closeBox.width)).toBeLessThanOrEqual(1);
|
||||
await expect(placement).toBeInViewport();
|
||||
await expect(limit).toHaveValue("30");
|
||||
|
||||
for (const name of ["When the tab limit is reached", "When the current tab is closed, activate"]) {
|
||||
const choices = closing.getByRole("radiogroup", { name, exact: true }).getByRole("radio");
|
||||
const first = (await choices.first().boundingBox())!;
|
||||
const last = (await choices.last().boundingBox())!;
|
||||
expect(Math.abs(first.x - last.x)).toBeLessThanOrEqual(1);
|
||||
expect(last.y).toBeGreaterThan(first.y + first.height);
|
||||
expect(last.x + last.width).toBeLessThanOrEqual(width);
|
||||
}
|
||||
await expect(footer).toBeInViewport();
|
||||
}
|
||||
});
|
||||
|
||||
test("Editor Tabs keeps row and overflow choices independently selected and keyboard operable", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
const settings = await openEditorTabsSettings(page);
|
||||
const group = settings.getByRole("radiogroup", { name: "Show tabs in", exact: true });
|
||||
const one = group.getByRole("radio", { name: /^One row/ });
|
||||
const multiple = group.getByRole("radio", { name: "Multiple rows", exact: true });
|
||||
const scroll = group.getByRole("radio", { name: "Scroll the tabs panel", exact: true });
|
||||
const squeeze = group.getByRole("radio", { name: "Squeeze tabs", exact: true });
|
||||
await expect(one).toBeChecked();
|
||||
await expect(scroll).toBeChecked();
|
||||
const oneBox = (await one.boundingBox())!;
|
||||
const scrollBox = (await scroll.boundingBox())!;
|
||||
const multipleBox = (await multiple.boundingBox())!;
|
||||
expect(scrollBox.x).toBeGreaterThan(oneBox.x + 8);
|
||||
expect(scrollBox.y).toBeGreaterThan(oneBox.y);
|
||||
expect(Math.abs(multipleBox.x - oneBox.x)).toBeLessThanOrEqual(1);
|
||||
expect(multipleBox.y).toBeGreaterThan(scrollBox.y);
|
||||
|
||||
await scroll.press("ArrowDown");
|
||||
await expect(squeeze).toBeFocused();
|
||||
await expect(squeeze).toBeChecked();
|
||||
await expect(one).toBeChecked();
|
||||
await one.press("ArrowDown");
|
||||
await expect(multiple).toBeFocused();
|
||||
await expect(multiple).toBeChecked();
|
||||
await expect(squeeze).toBeDisabled();
|
||||
await expect(squeeze).toBeChecked();
|
||||
await multiple.press("ArrowUp");
|
||||
await expect(one).toBeChecked();
|
||||
await expect(squeeze).toBeEnabled();
|
||||
await settings.getByRole("button", { name: "OK", exact: true }).click();
|
||||
|
||||
const reopened = await openEditorTabsSettings(page);
|
||||
await expect(reopened.getByRole("radio", { name: /^One row/ })).toBeChecked();
|
||||
await expect(reopened.getByRole("radio", { name: "Squeeze tabs", exact: true })).toBeChecked();
|
||||
});
|
||||
@@ -2,6 +2,7 @@
|
||||
* Git Log toolbar buttons close their popup when clicked again, as in IDEA, instead of
|
||||
* keeping it open (Branch) or replaying its opening (the menus). Git is stubbed at the IPC layer.
|
||||
*/
|
||||
import type { Page } from "@playwright/test";
|
||||
import { expect, stubDesktop, test } from "./fixtures";
|
||||
|
||||
test.beforeEach(async ({ workbench: page }) => {
|
||||
@@ -60,6 +61,98 @@ test.beforeEach(async ({ workbench: page }) => {
|
||||
await expect(page.getByRole("listbox", { name: "Commits" }).getByRole("option").first()).toBeVisible();
|
||||
});
|
||||
|
||||
async function openLogPathEditor(page: Page) {
|
||||
const toolbar = page.getByRole("toolbar", { name: "Log filters", exact: true });
|
||||
const filter = toolbar.getByRole("button", { name: /^Paths(:|$)/ });
|
||||
const overflow = toolbar.getByRole("button", { name: "More Filters", exact: true });
|
||||
const visible = await filter.isVisible();
|
||||
const anchor = visible ? filter : overflow;
|
||||
await anchor.click();
|
||||
if (!visible) await page.getByRole("menuitem", { name: /^Paths(:|$)/ }).click();
|
||||
await page.getByRole("menuitem", { name: "Select…", exact: true }).click();
|
||||
const editor = page.getByRole("dialog", { name: "Filter by Paths", exact: true });
|
||||
await expect(editor.getByRole("textbox", { name: "Paths", exact: true })).toBeFocused();
|
||||
return { anchor, editor };
|
||||
}
|
||||
|
||||
test("the Git Log path editor anchors to its filter and wraps long paths", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 1220, height: 760 });
|
||||
await page.evaluate(async () => {
|
||||
const logPath = "/src/features/vcs/logStore.ts";
|
||||
const optionsPath = "/src/features/vcs/logOptions.ts";
|
||||
const { setLogFilters } = await import(/* @vite-ignore */ logPath);
|
||||
const { setLogOptions } = await import(/* @vite-ignore */ optionsPath);
|
||||
setLogOptions({ showBranches: false, showDetails: false });
|
||||
setLogFilters({
|
||||
paths: ["/dev/acme-api/src/" + "settlement-".repeat(12) + "report.ts", "/dev/acme-api/docs/guide.md"],
|
||||
});
|
||||
});
|
||||
const { anchor, editor } = await openLogPathEditor(page);
|
||||
const input = editor.getByRole("textbox", { name: "Paths", exact: true });
|
||||
const popupBox = (await editor.boundingBox())!;
|
||||
const anchorBox = (await anchor.boundingBox())!;
|
||||
const gap = Math.min(
|
||||
Math.abs(popupBox.y - anchorBox.y - anchorBox.height),
|
||||
Math.abs(anchorBox.y - popupBox.y - popupBox.height),
|
||||
);
|
||||
expect(gap).toBeLessThanOrEqual(6);
|
||||
expect((await input.boundingBox())!.height).toBeGreaterThan(120);
|
||||
expect(await input.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
|
||||
await expect(editor.getByText("One path per line", { exact: true })).toBeVisible();
|
||||
|
||||
const grip = (await editor.getByRole("separator", { name: "Resize", exact: true }).boundingBox())!;
|
||||
const x = grip.x + grip.width / 2;
|
||||
const y = grip.y + grip.height / 2;
|
||||
await page.mouse.move(x, y);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(x, y + 34, { steps: 4 });
|
||||
await page.mouse.up();
|
||||
await expect.poll(async () => (await editor.boundingBox())!.height).toBeGreaterThan(popupBox.height + 20);
|
||||
await input.fill("src\ndocs/draft.md");
|
||||
await page.setViewportSize({ width: 460, height: 550 });
|
||||
const overflow = page.getByRole("toolbar", { name: "Log filters" }).getByRole("button", { name: "More Filters" });
|
||||
await expect(overflow).toBeVisible();
|
||||
await expect(input).toHaveValue("src\ndocs/draft.md");
|
||||
await expect(editor).toBeInViewport({ ratio: 0.98 });
|
||||
await input.press("Escape");
|
||||
await expect(editor).toHaveCount(0);
|
||||
});
|
||||
|
||||
test("the narrow Git Log path editor applies with the primary shortcut and discards outside clicks", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 460, height: 550 });
|
||||
const { editor } = await openLogPathEditor(page);
|
||||
const input = editor.getByRole("textbox", { name: "Paths", exact: true });
|
||||
await expect(editor.getByRole("separator", { name: "Resize", exact: true })).toBeVisible();
|
||||
await expect(editor.getByRole("button", { name: "OK", exact: true })).toBeInViewport({ ratio: 0.98 });
|
||||
const modifier = await page.evaluate(async () => {
|
||||
const module = "/src/platform/keymap.ts";
|
||||
const { isMacHost } = await import(/* @vite-ignore */ module);
|
||||
return isMacHost() ? "Meta" : "Control";
|
||||
});
|
||||
await input.fill("src");
|
||||
await input.press("End");
|
||||
await input.press("Enter");
|
||||
await expect(input).toHaveValue("src\n");
|
||||
await input.fill("../outside");
|
||||
await input.press(`${modifier}+Enter`);
|
||||
await expect(editor.getByRole("alert")).toHaveText("Choose a path inside a repository.");
|
||||
await input.fill("src\ndocs/guide.md\nsrc");
|
||||
await input.press(`${modifier}+Enter`);
|
||||
await expect(editor).toHaveCount(0);
|
||||
|
||||
const reopened = await openLogPathEditor(page);
|
||||
await expect(input).toHaveValue("src\ndocs/guide.md");
|
||||
await input.fill("discarded");
|
||||
await page.mouse.click(4, 4);
|
||||
await expect(reopened.editor).toHaveCount(0);
|
||||
const again = await openLogPathEditor(page);
|
||||
await expect(input).toHaveValue("src\ndocs/guide.md");
|
||||
await again.anchor.click();
|
||||
await expect(again.editor).toHaveCount(0);
|
||||
});
|
||||
|
||||
test("Git Log separates commit message typography from compact metadata", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 860, height: 720 });
|
||||
await page.evaluate(() => {
|
||||
|
||||
@@ -83,6 +83,10 @@ test("links independent Gradle roots, runs identical task paths in their own bui
|
||||
});
|
||||
const tasks = tree.getByRole("treeitem", { name: /^assemble\b/ });
|
||||
await expect(tasks).toHaveCount(2);
|
||||
expect(await tasks.allTextContents()).toEqual(["assemble", "assemble"]);
|
||||
for (const task of await tasks.all()) {
|
||||
await expect(task).toHaveAccessibleDescription("Assembles this project");
|
||||
}
|
||||
await page.screenshot({ path: info.outputPath("gradle-two-roots.png"), animations: "disabled" });
|
||||
|
||||
await tasks.nth(0).dblclick();
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import { expect, test } from "./fixtures";
|
||||
|
||||
async function editMacros(page: Page) {
|
||||
await page.evaluate(async () => {
|
||||
const actions = "/src/platform/actions.ts";
|
||||
if (!(await (await import(/* @vite-ignore */ actions)).executeAction("macro.edit"))) throw Error("Edit Macros");
|
||||
});
|
||||
}
|
||||
|
||||
test("Edit Macros keeps a balanced, resizable split for names and recorded steps", async ({ workbench: page }) => {
|
||||
await page.evaluate(async () => {
|
||||
const model = "/src/features/macros/model.ts";
|
||||
const { saveMacro } = await import(/* @vite-ignore */ model);
|
||||
saveMacro("Insert comment", [{ kind: "text", text: "Review this block" }]);
|
||||
saveMacro("Wrap selection", [
|
||||
{ kind: "key", key: "Home" },
|
||||
{ kind: "text", text: "beginProcessingCurrentSelectionImmediately();".repeat(6) },
|
||||
{ kind: "key", key: "End" },
|
||||
]);
|
||||
});
|
||||
await editMacros(page);
|
||||
|
||||
const editor = page.getByRole("dialog", { name: "Edit Macros", exact: true });
|
||||
const macros = editor.getByRole("listbox", { name: "Macros" });
|
||||
const steps = editor.getByRole("list", { name: "Recorded steps" });
|
||||
const options = editor.getByRole("toolbar", { name: "Macros" });
|
||||
const divider = editor.getByRole("separator", { name: "Macros" });
|
||||
const [initial, stepsWidth] = await editor.evaluate((dialog) => [
|
||||
dialog.querySelector('[role="listbox"]')!.getBoundingClientRect().width,
|
||||
dialog.querySelector("ol")!.getBoundingClientRect().width,
|
||||
]);
|
||||
expect(Math.abs(initial - stepsWidth)).toBeLessThanOrEqual(1);
|
||||
await expect(macros).toBeFocused();
|
||||
expect((await steps.boundingBox())!.height).toBeGreaterThan(260);
|
||||
expect((await options.boundingBox())!.y).toBeLessThan((await macros.boundingBox())!.y);
|
||||
|
||||
await macros.getByRole("option", { name: "Wrap selection" }).click();
|
||||
await expect(steps.getByText("Press Home")).toBeVisible();
|
||||
await divider.press("ArrowRight");
|
||||
await expect.poll(async () => (await macros.boundingBox())!.width).toBeGreaterThan(initial + 5);
|
||||
const resized = (await macros.boundingBox())!.width;
|
||||
await editor.locator("[data-dialog-footer]").getByRole("button", { name: "Close" }).click();
|
||||
await editMacros(page);
|
||||
await expect.poll(async () => (await macros.boundingBox())!.width).toBeCloseTo(resized, 0);
|
||||
|
||||
await page.setViewportSize({ width: 400, height: 620 });
|
||||
await macros.getByRole("option", { name: "Wrap selection" }).click();
|
||||
expect(await steps.evaluate((list) => list.scrollWidth - list.clientWidth)).toBeLessThanOrEqual(1);
|
||||
await options.getByRole("button", { name: "Rename Macro" }).click();
|
||||
const rename = page.getByRole("dialog", { name: "Rename Macro", exact: true });
|
||||
await rename.getByRole("textbox").fill("Wrap text");
|
||||
await rename.getByRole("button", { name: "Rename", exact: true }).click();
|
||||
await expect(macros.getByRole("option", { name: "Wrap text" })).toBeVisible();
|
||||
await expect(steps.getByText("Press Home")).toBeVisible();
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
import type { MavenModel } from "../src/platform/ipc";
|
||||
import { expect, stubDesktop, test } from "./fixtures";
|
||||
|
||||
const maven: MavenModel = {
|
||||
projects: [
|
||||
{
|
||||
pom: "pom.xml",
|
||||
dir: "",
|
||||
groupId: "dev.acme",
|
||||
artifactId: "billing",
|
||||
version: "1.0.0",
|
||||
packaging: "jar",
|
||||
displayName: "Billing",
|
||||
parent: null,
|
||||
modules: [],
|
||||
aggregated: false,
|
||||
plugins: [
|
||||
{
|
||||
groupId: "org.apache.maven.plugins",
|
||||
artifactId: "maven-surefire-plugin",
|
||||
version: "3.2.5",
|
||||
prefix: "surefire",
|
||||
goals: ["test"],
|
||||
},
|
||||
],
|
||||
dependencies: [],
|
||||
profiles: [],
|
||||
javaVersion: 21,
|
||||
command: "mvn",
|
||||
options: [],
|
||||
env: {},
|
||||
},
|
||||
],
|
||||
profiles: [],
|
||||
syncedAt: 1,
|
||||
stale: false,
|
||||
syncError: null,
|
||||
};
|
||||
|
||||
test("Maven plugin rows give the name priority over coordinates in narrow docks", async ({ workbench: page }) => {
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async (maven) => {
|
||||
window.__ipc.handlers.build_model = () => ({ maven, gradle: [] });
|
||||
const buildModule = "/src/features/build-tools/store.ts";
|
||||
const { loadModel, setExpanded } = await import(/* @vite-ignore */ buildModule);
|
||||
await loadModel();
|
||||
setExpanded("maven", new Set(["mvn:pom.xml", "mvn:pom.xml:plugins"]));
|
||||
const dockModule = "/src/workbench/toolwindows/store.ts";
|
||||
const { showToolWindow, setToolWindowSize } = await import(/* @vite-ignore */ dockModule);
|
||||
showToolWindow("maven", true);
|
||||
setToolWindowSize("right", 190);
|
||||
}, maven);
|
||||
|
||||
const tree = page.getByRole("tree", { name: "Maven projects" });
|
||||
const coordinates = "(org.apache.maven.plugins:maven-surefire-plugin:3.2.5)";
|
||||
const plugin = tree.getByRole("treeitem", { name: `surefire ${coordinates}`, exact: true });
|
||||
const name = plugin.getByText("surefire", { exact: true });
|
||||
const metadata = plugin.getByText(coordinates, { exact: true });
|
||||
await expect(name).toBeVisible();
|
||||
await expect(metadata).toHaveAttribute("title", coordinates);
|
||||
const fit = (el: Element) => {
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(el);
|
||||
return range.getBoundingClientRect().width <= el.getBoundingClientRect().width;
|
||||
};
|
||||
expect(await name.evaluate(fit)).toBe(true);
|
||||
expect(await metadata.evaluate(fit)).toBe(false);
|
||||
expect(await metadata.evaluate((el) => getComputedStyle(el).color)).not.toBe(
|
||||
await name.evaluate((el) => getComputedStyle(el).color),
|
||||
);
|
||||
|
||||
await plugin.locator("[data-tree-toggle]").click();
|
||||
await expect(tree.getByRole("treeitem", { name: "surefire:test", exact: true })).toBeVisible();
|
||||
});
|
||||
@@ -29,7 +29,14 @@ test("Find in Files keeps the scope list and pattern editor usable in a narrow w
|
||||
expect((await list.boundingBox())!.x).toBeLessThan((await name.boundingBox())!.x);
|
||||
|
||||
await page.setViewportSize({ width: 460, height: 530 });
|
||||
const fields = (await pattern.boundingBox())!;
|
||||
// The dialog relays out over a few frames after the resize; measure once it has settled.
|
||||
let fields = (await pattern.boundingBox())!;
|
||||
await expect(async () => {
|
||||
const previous = fields.y;
|
||||
await page.evaluate(() => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))));
|
||||
fields = (await pattern.boundingBox())!;
|
||||
expect(fields.y).toBe(previous);
|
||||
}).toPass();
|
||||
expect(fields.y).toBeGreaterThanOrEqual((await list.boundingBox())!.y + (await list.boundingBox())!.height);
|
||||
expect(fields.width).toBeGreaterThan(250);
|
||||
await list.evaluate((el) => (el.scrollTop = el.scrollHeight));
|
||||
|
||||
@@ -75,7 +75,7 @@ for (const locale of ["en", "zh"]) {
|
||||
const path = "/src/platform/i18n.ts";
|
||||
await (await import(/* @vite-ignore */ path)).setLocale(locale);
|
||||
}, locale);
|
||||
for (const id of ["appearance", "editor.font", "general", "general.httpProxy"]) {
|
||||
for (const id of ["appearance", "editor.font", "general", "general.httpProxy", "vcs.log"]) {
|
||||
await selectPage(page, id);
|
||||
const body = page.locator("[class*='pageBody']");
|
||||
for (const width of [1000, 784, 640, 520]) {
|
||||
@@ -108,6 +108,31 @@ test("keeps Open project in options within narrow System Settings", async ({ wor
|
||||
expect(overflow).toBeLessThanOrEqual(1);
|
||||
});
|
||||
|
||||
test("Git Log settings group display and column options with aligned checkboxes", async ({ workbench: page }) => {
|
||||
await page.keyboard.press("Meta+,");
|
||||
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
|
||||
await selectPage(page, "vcs.log");
|
||||
const view = dialog.getByRole("region", { name: "View Options" });
|
||||
const columns = dialog.getByRole("region", { name: "Visible columns" });
|
||||
const tagNames = view.getByRole("checkbox", { name: "Show tag names" });
|
||||
const hash = columns.getByRole("checkbox", { name: "Hash" });
|
||||
await expect(view.getByRole("checkbox")).toHaveCount(5);
|
||||
await expect(columns.getByRole("checkbox")).toHaveCount(4);
|
||||
|
||||
for (const width of [1000, 520]) {
|
||||
await page.setViewportSize({ width, height: 760 });
|
||||
// Read both rows together once the dialog has finished opening and relaid out.
|
||||
await expect
|
||||
.poll(async () => Math.abs((await tagNames.boundingBox())!.x - (await hash.boundingBox())!.x))
|
||||
.toBeLessThan(0.5);
|
||||
}
|
||||
|
||||
await expect(hash).not.toBeChecked();
|
||||
await hash.focus();
|
||||
await page.keyboard.press("Space");
|
||||
await expect(hash).toBeChecked();
|
||||
});
|
||||
|
||||
test("settings sidebar resizes with mouse and keyboard and remembers its width", async ({ workbench: page }) => {
|
||||
await page.keyboard.press("Meta+,");
|
||||
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
|
||||
|
||||
@@ -1,5 +1,41 @@
|
||||
import { expect, openFromTree, test } from "./fixtures";
|
||||
|
||||
test("the line separator menu has a heading and keeps the current choice visible", async ({ workbench: page }) => {
|
||||
await openFromTree(page, "build.gradle.kts");
|
||||
const status = page.locator('[data-status-item="editor.lineEnding"]').getByRole("button");
|
||||
const menu = page.getByRole("menu", { name: /^Line Separator$/i });
|
||||
const windows = "Windows (\\r\\n)";
|
||||
const unix = "Unix and macOS (\\n)";
|
||||
const classic = "Classic Mac OS (\\r)";
|
||||
await expect(status).toHaveText("LF");
|
||||
await status.click();
|
||||
const heading = menu.locator("..").getByText("Line Separator", { exact: true });
|
||||
expect(await heading.count()).toBe(1);
|
||||
await expect(heading).toHaveCSS("font-size", "13px");
|
||||
await expect(menu.locator('[role^="menuitem"]')).toHaveText([windows, unix, classic]);
|
||||
|
||||
await page.setViewportSize({ width: 540, height: 540 });
|
||||
await expect(heading).toBeInViewport({ ratio: 1 });
|
||||
await expect(menu.getByRole("menuitemcheckbox", { name: unix, checked: true })).toBeInViewport({ ratio: 1 });
|
||||
await expect(menu.getByRole("menuitem", { name: windows })).toBeFocused();
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(status).toHaveText("CRLF");
|
||||
|
||||
await status.click();
|
||||
await expect(menu.getByRole("menuitemcheckbox", { name: windows, checked: true })).toBeFocused();
|
||||
await page.keyboard.press("ArrowDown");
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(status).toHaveText("LF");
|
||||
|
||||
await page.evaluate(async () => {
|
||||
const path = "/src/platform/i18n.ts";
|
||||
await (await import(/* @vite-ignore */ path)).setLocale("zh");
|
||||
});
|
||||
await status.click();
|
||||
const translated = page.getByRole("menu", { name: "行分隔符", exact: true });
|
||||
await expect(translated.getByRole("menuitem", { name: "Windows 换行 (\\r\\n)", exact: true })).toBeVisible();
|
||||
});
|
||||
|
||||
test("status bar uses its row height and widget insets in both densities", async ({ workbench: page }) => {
|
||||
const editor = await openFromTree(page, "build.gradle.kts");
|
||||
const bar = page.locator('footer[aria-label="Status bar"]');
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import { expect, stubDesktop, test } from "./fixtures";
|
||||
|
||||
async function setEditorMetrics(page: Page, fontSize: number, lineHeight: number) {
|
||||
await page.evaluate(
|
||||
async ({ fontSize, lineHeight }) => {
|
||||
const projectModule = "/src/platform/project.ts";
|
||||
const { useProject } = await import(/* @vite-ignore */ projectModule);
|
||||
const { settings, project } = useProject.getState();
|
||||
const current = settings ?? project?.settings;
|
||||
if (!current) throw new Error("Expected project settings");
|
||||
useProject.setState({ settings: { ...current, editor: { ...current.editor, fontSize, lineHeight } } });
|
||||
},
|
||||
{ fontSize, lineHeight },
|
||||
);
|
||||
}
|
||||
|
||||
async function openResults(page: Page) {
|
||||
await page.setViewportSize({ width: 1120, height: 720 });
|
||||
await stubDesktop(page);
|
||||
await setEditorMetrics(page, 20, 34);
|
||||
await page.evaluate(async () => {
|
||||
const lines = Array.from({ length: 1240 }, () => "");
|
||||
lines[1233] = " record(orderTotal);";
|
||||
lines[1237] = " return orderTotal;";
|
||||
window.__ipc.handlers.fs_read_text = () => lines.join("\n");
|
||||
const actionsModule = "/src/platform/actions.ts";
|
||||
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
|
||||
await executeAction("find.showUsageResults", {
|
||||
symbol: "orderTotal",
|
||||
locations: [
|
||||
{
|
||||
path: "/dev/acme-api/src/orderTotals.ts",
|
||||
range: { start: { line: 1233, col: 9 }, end: { line: 1233, col: 19 } },
|
||||
},
|
||||
{
|
||||
path: "/dev/acme-api/src/orderTotals.ts",
|
||||
range: { start: { line: 1237, col: 9 }, end: { line: 1237, col: 19 } },
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
const view = page.getByRole("region", { name: "Find Usages", exact: true });
|
||||
await view.getByRole("treeitem").filter({ hasText: "1234" }).click();
|
||||
const preview = view.getByRole("region", { name: "Preview", exact: true });
|
||||
await expect(preview.locator("mark")).toHaveCount(2);
|
||||
return { view, preview };
|
||||
}
|
||||
|
||||
test("Find Usages preview follows editor line height and fits long line numbers", async ({ workbench: page }) => {
|
||||
const { preview } = await openResults(page);
|
||||
await expect(preview).toHaveCSS("font-size", "20px");
|
||||
await expect(preview).toHaveCSS("line-height", "34px");
|
||||
|
||||
const number = preview.getByText("1234", { exact: true });
|
||||
const gutter = await number.evaluate((element) => {
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(element);
|
||||
const text = range.getBoundingClientRect();
|
||||
const box = element.getBoundingClientRect();
|
||||
return { textInset: text.left - box.left, width: box.width };
|
||||
});
|
||||
expect(gutter.textInset).toBeGreaterThanOrEqual(1);
|
||||
await expect(number).toBeInViewport({ ratio: 0.98 });
|
||||
expect((await preview.getByText("999", { exact: true }).boundingBox())!.width).toBeCloseTo(gutter.width, 0);
|
||||
|
||||
await page.setViewportSize({ width: 560, height: 720 });
|
||||
await setEditorMetrics(page, 20, 39);
|
||||
await expect(preview).toHaveCSS("line-height", "39px");
|
||||
await expect(number).toBeInViewport({ ratio: 0.98 });
|
||||
});
|
||||
|
||||
test("Find Usages starts with equal panes and keeps a separate saved size for each orientation", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
const { view } = await openResults(page);
|
||||
const divider = view.locator('[id="usages-preview-split"]').getByRole("separator");
|
||||
await expect(divider).toHaveAttribute("aria-valuenow", "50");
|
||||
await divider.press("ArrowRight");
|
||||
await expect(divider).not.toHaveAttribute("aria-valuenow", "50");
|
||||
const horizontal = (await divider.getAttribute("aria-valuenow"))!;
|
||||
|
||||
await page.setViewportSize({ width: 560, height: 720 });
|
||||
await expect(divider).toHaveAttribute("aria-orientation", "horizontal");
|
||||
await expect(divider).toHaveAttribute("aria-valuenow", "50");
|
||||
await divider.press("ArrowDown");
|
||||
await expect(divider).not.toHaveAttribute("aria-valuenow", "50");
|
||||
const vertical = (await divider.getAttribute("aria-valuenow"))!;
|
||||
|
||||
await page.setViewportSize({ width: 1120, height: 720 });
|
||||
await expect(divider).toHaveAttribute("aria-orientation", "vertical");
|
||||
await expect(divider).toHaveAttribute("aria-valuenow", horizontal);
|
||||
await page.setViewportSize({ width: 560, height: 720 });
|
||||
await expect(divider).toHaveAttribute("aria-valuenow", vertical);
|
||||
});
|
||||
@@ -0,0 +1,3 @@
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
@@ -0,0 +1,113 @@
|
||||
# Self-Hosted GitHub Actions Runners
|
||||
|
||||
Runs _N_ persistent, isolated GitHub Actions runners via Docker Compose on a single Docker named volume (`runner-persist`) without requiring repository admin Personal Access Tokens.
|
||||
|
||||
In `.github/workflows/ci.yml`, the Linux leg of `Rust (${{ matrix.os }})` routes to `["self-hosted", "openidea-selfhosted"]` on trusted events (`push`, `merge_group`, `workflow_dispatch`, and same-repo pull requests) while the `SELFHOSTED_RUNNERS` repository variable is `true`. Fork pull requests, and every run while the variable is unset, use GitHub-hosted runners.
|
||||
|
||||
> **Availability requirement:** GitHub Actions `runs-on` cannot fall back to GitHub-hosted runners when no matching self-hosted runner is online; jobs stay queued until one connects. Set `SELFHOSTED_RUNNERS=true` (**Settings → Secrets and variables → Actions → Variables**) only once the runners are up, and delete it before taking the host down.
|
||||
|
||||
## Security Constraints
|
||||
|
||||
Because this repository is public and these runners retain persistent build caches and credentials across runs, workflows and runner hosts must follow these rules:
|
||||
|
||||
- **Trusted events only:** Route jobs to `openidea-selfhosted` only for `push`, `merge_group`, `workflow_dispatch`, or `pull_request` events where `github.event.pull_request.head.repo.full_name == github.repository`. Fork pull requests must stay on GitHub-hosted runners so untrusted code never reaches persistent caches or runner credentials.
|
||||
- **Read-only `GITHUB_TOKEN`:** Jobs targeting `openidea-selfhosted` must set `permissions: { contents: read }` (least privilege).
|
||||
- **No secret-bearing jobs:** Never pass repository or organization `secrets.*` to jobs running on `openidea-selfhosted`.
|
||||
- **Never feed releases:** Artifacts or outputs from `openidea-selfhosted` runners must never be uploaded for consumption by release or nightly workflows.
|
||||
- **Container isolation:** Jobs run as the `runner` user (`RUN_AS_ROOT=false`) from a pinned image tag and digest, but the image grants that user passwordless `sudo` (CI needs it for `apt-get`), so a job can become root inside its container. The container is the isolation boundary: never mount `/var/run/docker.sock` or host directories into it, and never run it `--privileged`.
|
||||
- **Shared build state:** Same-repo pull requests and `main` share each slot's Cargo target directory, so only collaborators you trust with `main`'s build should push branches to this repository.
|
||||
- **Network isolation:** Run the Docker host on an isolated network segment away from sensitive devices or internal services.
|
||||
|
||||
## How It Works
|
||||
|
||||
On startup, each container replica acquires an exclusive `flock` on a numeric slot (`1..N`) before dropping privileges to the `runner` user, isolating its persistent state under `/persist/slot-<N>/`:
|
||||
|
||||
| Path | Purpose |
|
||||
| --------------- | ----------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `runner-data/` | Saved `.runner` and `.credentials` reused across container restarts (`CONFIGURED_ACTIONS_RUNNER_FILES_DIR`) |
|
||||
| `work/` | Runner workspace and repository checkouts (`RUNNER_WORKDIR`) |
|
||||
| `cargo-target/` | Pre-compiled Rust build artifacts (`CARGO_TARGET_DIR`), kept outside checkouts so `actions/checkout` cleanup does not wipe it |
|
||||
| `cargo/` | Cargo crate registry and git cache (`CARGO_HOME`) |
|
||||
| `rustup/` | Installed Rust toolchains (`RUSTUP_HOME`) |
|
||||
| `pnpm-store/` | Content-addressable `pnpm` store on the same filesystem as `work/` for fast hardlinks into `node_modules` |
|
||||
| `toolcache/` | Tools cached by `actions/setup-*` (`/opt/hostedtoolcache`) |
|
||||
| `cache/` | General `/home/runner/.cache` directory |
|
||||
|
||||
All slots also share `/persist/shared/npm-cache` for downloaded npm tarballs.
|
||||
|
||||
## Prerequisites (First-Time Registration Only)
|
||||
|
||||
Ask a repository admin to generate **one** 1-hour registration token from:
|
||||
|
||||
> **GitHub Repository → Settings → Actions → Runners → New self-hosted runner**
|
||||
|
||||
A single registration token can register multiple runner slots within its 1-hour validity window. Once registered, each slot saves its own runner credentials and reconnects across restarts without needing a token again.
|
||||
|
||||
## Quick Start
|
||||
|
||||
Run all commands from `scripts/selfhost-runner/`:
|
||||
|
||||
1. **Initial registration** (registers slots `1..4` and saves credentials):
|
||||
|
||||
```bash
|
||||
RUNNER_TOKEN=<one-time-token> docker compose up -d
|
||||
```
|
||||
|
||||
2. **Normal start, restart, or recreate** (no token needed once slots are registered):
|
||||
|
||||
```bash
|
||||
docker compose up -d
|
||||
docker compose restart
|
||||
```
|
||||
|
||||
3. **Scale down** (for example `4` → `2`):
|
||||
|
||||
```bash
|
||||
RUNNER_COUNT=2 docker compose up -d
|
||||
```
|
||||
|
||||
Docker Compose does not guarantee which container replicas it removes, so scaling `4` → `2` may leave slots `3` and `4` running rather than `1` and `2`. Stopped slots keep their saved credentials and caches on disk and will be reclaimed on the next restart or scale-up.
|
||||
|
||||
4. **Scale up** (for example `4` → `6`):
|
||||
|
||||
- If slots `5..6` were previously registered:
|
||||
|
||||
```bash
|
||||
RUNNER_COUNT=6 docker compose up -d
|
||||
```
|
||||
|
||||
- If slots `5..6` have never been registered:
|
||||
|
||||
```bash
|
||||
RUNNER_COUNT=6 RUNNER_TOKEN=<new-token> docker compose up -d
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
You can pass variables on the command line or place them in a local `.env` file in this directory (git-ignored):
|
||||
|
||||
| Variable | Default | Description |
|
||||
| -------------------- | ------------------------------------- | ---------------------------------------------------------------------- |
|
||||
| `RUNNER_COUNT` | `4` | Number of concurrent runner replicas |
|
||||
| `RUNNER_NAME_PREFIX` | `openidea-runner` | Runner name prefix; registers as `<prefix>-1`, `<prefix>-2`, … |
|
||||
| `RUNNER_LABELS` | `openidea-selfhosted` | Comma-separated labels attached to each runner |
|
||||
| `REPO_URL` | `https://github.com/l0ng-ai/openidea` | Target GitHub repository URL |
|
||||
| `RUNNER_TOKEN` | _(empty)_ | One-time registration token (required only when registering new slots) |
|
||||
|
||||
## Troubleshooting & Tips
|
||||
|
||||
- **Offline expiry (> 14 days) or deleted runner:** GitHub automatically removes runners that stay offline for more than 14 days. To clear a stale slot `<N>` and re-register it:
|
||||
|
||||
```bash
|
||||
docker compose run --rm --entrypoint /bin/bash github-runner \
|
||||
-c "rm -rf /persist/slot-<N>/runner-data/*"
|
||||
RUNNER_TOKEN=<new-token> docker compose up -d
|
||||
```
|
||||
|
||||
- **Full reset** (wipes all saved runner credentials and cached build artifacts):
|
||||
|
||||
```bash
|
||||
docker compose down -v
|
||||
```
|
||||
|
||||
- **Workflow caching tips:** `CARGO_TARGET_DIR` persists automatically across runs; CI enables incremental compilation on these runners and clears a slot's target directory once it exceeds 40 GB. To also preserve in-repo `node_modules/` across runs without re-linking, pass `clean: false` to `actions/checkout` (otherwise `pnpm install` quickly re-hardlinks packages from `pnpm-store/`).
|
||||
@@ -0,0 +1,70 @@
|
||||
# Self-hosted GitHub Actions runners (persistent & scalable).
|
||||
# See README.md in this directory for setup, security constraints, scaling, and troubleshooting.
|
||||
|
||||
services:
|
||||
github-runner:
|
||||
image: myoung34/github-runner:2.338.2-ubuntu-jammy@sha256:9944eb7fe15cff8f31ce6389a1cd39f5fb32627f56bdfa8a21fb27e56e99fa1a
|
||||
restart: unless-stopped
|
||||
deploy:
|
||||
replicas: ${RUNNER_COUNT:-4}
|
||||
|
||||
environment:
|
||||
RUNNER_SCOPE: repo
|
||||
REPO_URL: ${REPO_URL:-https://github.com/l0ng-ai/openidea}
|
||||
# Only needed the first time a new slot registers; registered slots reuse saved credentials.
|
||||
RUNNER_TOKEN: ${RUNNER_TOKEN:-}
|
||||
RUNNER_NAME_PREFIX: ${RUNNER_NAME_PREFIX:-openidea-runner}
|
||||
LABELS: ${RUNNER_LABELS:-openidea-selfhosted}
|
||||
DISABLE_AUTOMATIC_DEREGISTRATION: "true"
|
||||
RUN_AS_ROOT: "false"
|
||||
|
||||
# Claim an exclusive numeric slot (1..N) via flock so each replica gets its own
|
||||
# persistent runner credentials, workspace, Cargo target/home, rustup, pnpm store, and toolcache.
|
||||
entrypoint:
|
||||
- /bin/bash
|
||||
- -ec
|
||||
- |
|
||||
mkdir -p /persist/slots /persist/shared/npm-cache /home/runner
|
||||
SLOT=1
|
||||
while true; do
|
||||
exec 99>"/persist/slots/slot-$${SLOT}.lock"
|
||||
if flock -n 99; then break; fi
|
||||
SLOT=$$((SLOT + 1))
|
||||
done
|
||||
SLOT_DIR="/persist/slot-$${SLOT}"
|
||||
mkdir -p "$${SLOT_DIR}"/{runner-data,work,cargo,cargo-target,rustup,pnpm-store,cache,toolcache}
|
||||
if [[ ! -f "$${SLOT_DIR}/runner-data/.runner" && -z "$${RUNNER_TOKEN:-}" ]]; then
|
||||
echo "ERROR: Slot $${SLOT} ($${RUNNER_NAME_PREFIX:-openidea-runner}-$${SLOT}) is not registered yet; set RUNNER_TOKEN to register it." >&2
|
||||
exit 1
|
||||
fi
|
||||
RUNNER_UID="$$(id -u runner)"
|
||||
RUNNER_GID="$$(id -g runner)"
|
||||
if [[ "$$(stat -c '%u' /persist/shared/npm-cache)" != "$${RUNNER_UID}" ]]; then
|
||||
chown -R "$${RUNNER_UID}:$${RUNNER_GID}" /persist/shared/npm-cache
|
||||
fi
|
||||
if [[ "$$(stat -c '%u' "$${SLOT_DIR}")" != "$${RUNNER_UID}" ]]; then
|
||||
chown -R "$${RUNNER_UID}:$${RUNNER_GID}" "$${SLOT_DIR}"
|
||||
fi
|
||||
chown "$${RUNNER_UID}:$${RUNNER_GID}" /persist/shared "$${SLOT_DIR}" "$${SLOT_DIR}"/{runner-data,work,cargo,cargo-target,rustup,pnpm-store,cache,toolcache}
|
||||
rm -rf /opt/hostedtoolcache /home/runner/.cache
|
||||
ln -s "$${SLOT_DIR}/toolcache" /opt/hostedtoolcache
|
||||
ln -s "$${SLOT_DIR}/cache" /home/runner/.cache
|
||||
chown -h "$${RUNNER_UID}:$${RUNNER_GID}" /opt/hostedtoolcache /home/runner/.cache
|
||||
export CONFIGURED_ACTIONS_RUNNER_FILES_DIR="$${SLOT_DIR}/runner-data"
|
||||
export RUNNER_NAME="$${RUNNER_NAME_PREFIX:-openidea-runner}-$${SLOT}"
|
||||
export RUNNER_WORKDIR="$${SLOT_DIR}/work"
|
||||
export CARGO_HOME="$${SLOT_DIR}/cargo"
|
||||
export RUSTUP_HOME="$${SLOT_DIR}/rustup"
|
||||
export CARGO_TARGET_DIR="$${SLOT_DIR}/cargo-target"
|
||||
export npm_config_store_dir="$${SLOT_DIR}/pnpm-store"
|
||||
export npm_config_cache="/persist/shared/npm-cache"
|
||||
export PATH="$${CARGO_HOME}/bin:$${PATH}"
|
||||
exec /entrypoint.sh "$$@"
|
||||
- --
|
||||
command: ["./bin/Runner.Listener", "run", "--startuptype", "service"]
|
||||
|
||||
volumes:
|
||||
- runner-persist:/persist
|
||||
|
||||
volumes:
|
||||
runner-persist:
|
||||
@@ -346,6 +346,21 @@ pub(crate) fn project_current(window: Window) -> Option<ProjectInfo> {
|
||||
state.project(window.label()).ok().filter(|p| !p.light).map(|p| project_info(&p))
|
||||
}
|
||||
|
||||
// Off the IPC thread: each member's `for_project().layer(Project)` re-parses both settings layers
|
||||
// and validates the merge against the whole `Settings` type, which a debug build's stack-heavy
|
||||
// recursion can overflow from the WebView2 callback (see the `settings_set` note above).
|
||||
pub(crate) fn project_workspace_members(window: Window) -> IdeResult<Vec<ide_host::ops::project::WorkspaceMember>> {
|
||||
let state = window.state::<AppState>();
|
||||
state.note_ipc();
|
||||
ide_host::ops::project::project_workspace_members(&state.host, window.label())
|
||||
}
|
||||
|
||||
pub(crate) fn project_workspace_member_set(window: Window, root: PathBuf, key: String, value: String) -> IdeResult<()> {
|
||||
let state = window.state::<AppState>();
|
||||
state.note_ipc();
|
||||
ide_host::ops::project::project_workspace_member_set(&state.host, window.label(), root, key, value)
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum LogLevel {
|
||||
|
||||
@@ -44,8 +44,8 @@ use std::sync::LazyLock;
|
||||
// Desktop bodies of project-host commands (`#[command(desktop_body = …)]`), which their derived
|
||||
// adapters call.
|
||||
use app::{
|
||||
close_project, open_project, project_current, project_trust_remove_location, project_trust_set, settings_get,
|
||||
settings_removed_theme, settings_set,
|
||||
close_project, open_project, project_current, project_trust_remove_location, project_trust_set,
|
||||
project_workspace_member_set, project_workspace_members, settings_get, settings_removed_theme, settings_set,
|
||||
};
|
||||
use doc::doc_edit;
|
||||
use plugin::plugin_event_kinds;
|
||||
|
||||
@@ -9,11 +9,11 @@ use tauri::{State, Window};
|
||||
#[desktop_command(trust = trusted)]
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn spring_route_sources(
|
||||
pub async fn spring_route_sources(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
) -> IdeResult<Vec<ide_host::ops::routes::RouteSource>> {
|
||||
ide_host::ops::routes::spring_route_sources(&state.host, window.label())
|
||||
ide_host::ops::routes::spring_route_sources(&state.host, window.label()).await
|
||||
}
|
||||
|
||||
/// Cucumber feature files and step definition files, for step navigation.
|
||||
|
||||
@@ -568,21 +568,27 @@ pub struct PluginSecretState {
|
||||
#[desktop_command(trust = trusted)]
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn plugin_secrets(state: State<'_, AppState>, plugin_id: String) -> IdeResult<Vec<PluginSecretState>> {
|
||||
Ok(state.plugins.secrets(&plugin_id)?.into_iter().map(|(name, set)| PluginSecretState { name, set }).collect())
|
||||
pub async fn plugin_secrets(state: State<'_, AppState>, plugin_id: String) -> IdeResult<Vec<PluginSecretState>> {
|
||||
let host = state.plugins.clone();
|
||||
blocking(move || {
|
||||
Ok(host.secrets(&plugin_id)?.into_iter().map(|(name, set)| PluginSecretState { name, set }).collect())
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Stores a plugin secret (`None` or empty deletes it). The value never goes back to the UI or the plugin.
|
||||
/// The keychain call takes up to hundreds of milliseconds, so it runs on the blocking pool.
|
||||
#[desktop_command(trust = trusted)]
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn plugin_set_secret(
|
||||
pub async fn plugin_set_secret(
|
||||
state: State<'_, AppState>,
|
||||
plugin_id: String,
|
||||
name: String,
|
||||
value: Option<String>,
|
||||
) -> IdeResult<()> {
|
||||
state.plugins.set_secret(&plugin_id, &name, value.as_deref())
|
||||
let host = state.plugins.clone();
|
||||
blocking(move || host.set_secret(&plugin_id, &name, value.as_deref())).await
|
||||
}
|
||||
|
||||
/// Plugin secrets in the login keychain (service `ai.l0ng.openidea.plugin.<id>`).
|
||||
|
||||
@@ -4,9 +4,13 @@
|
||||
use ide_host::catalogue::Mode;
|
||||
|
||||
/// Commands that read or write project files, Local History or `.env` files, diff two
|
||||
/// arbitrary texts, or scan the project index in parallel: they must do that work off the
|
||||
/// main thread.
|
||||
/// arbitrary texts, scan the project index or tree, read agent registries and transcripts, or
|
||||
/// call the OS keychain: they must do that work off the main thread. Commands that parse and
|
||||
/// validate another project's settings recurse deeply enough to overflow the main thread's stack
|
||||
/// in a debug build on Windows.
|
||||
const OFF_MAIN_THREAD: &[&str] = &[
|
||||
"project_workspace_members",
|
||||
"project_workspace_member_set",
|
||||
"history_list",
|
||||
"history_content",
|
||||
"find_files",
|
||||
@@ -24,6 +28,11 @@ const OFF_MAIN_THREAD: &[&str] = &[
|
||||
"run_import_sources",
|
||||
"run_import_configs",
|
||||
"run_env_files",
|
||||
"agent_entries",
|
||||
"agent_providers",
|
||||
"plugin_secrets",
|
||||
"plugin_set_secret",
|
||||
"spring_route_sources",
|
||||
];
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -15,7 +15,7 @@ agent_custom_import trusted desktop bin
|
||||
agent_custom_remove trusted desktop bindings sync
|
||||
agent_custom_save trusted desktop bindings sync
|
||||
agent_delete trusted project_host bindings async
|
||||
agent_entries always project_host bindings sync
|
||||
agent_entries always project_host bindings async
|
||||
agent_external_sessions trusted project_host bindings async
|
||||
agent_fork trusted project_host bindings async
|
||||
agent_grouped_changes trusted project_host bindings async
|
||||
@@ -32,7 +32,7 @@ agent_mcp_set_enabled always project_host bin
|
||||
agent_mcp_test trusted project_host bindings async
|
||||
agent_probe trusted project_host bindings async
|
||||
agent_prompt trusted project_host bindings async
|
||||
agent_providers trusted project_host bindings sync
|
||||
agent_providers trusted project_host bindings async
|
||||
agent_refresh_models trusted project_host bindings sync
|
||||
agent_registry_install always project_host bindings async
|
||||
agent_registry_list always project_host bindings async
|
||||
@@ -476,7 +476,7 @@ plugin_roll_back outside_restricted desktop bin
|
||||
plugin_run_command trusted project_host bindings async
|
||||
plugin_run_targets trusted project_host bindings async
|
||||
plugin_search trusted project_host bindings async
|
||||
plugin_secrets trusted desktop bindings sync
|
||||
plugin_secrets trusted desktop bindings async
|
||||
plugin_select_tests trusted project_host bindings async
|
||||
plugin_service_detail trusted project_host bindings async
|
||||
plugin_service_log trusted project_host bindings async
|
||||
@@ -484,7 +484,7 @@ plugin_set_active_file always project_host bin
|
||||
plugin_set_capability outside_restricted desktop bindings async
|
||||
plugin_set_enabled outside_restricted desktop bindings async
|
||||
plugin_set_market_url always desktop bindings sync
|
||||
plugin_set_secret trusted desktop bindings sync
|
||||
plugin_set_secret trusted desktop bindings async
|
||||
plugin_set_theme always desktop bindings sync
|
||||
plugin_set_theme_frame always desktop bindings sync
|
||||
plugin_set_ui_locale always project_host bindings async
|
||||
@@ -514,8 +514,8 @@ project_trust_list always project_host bin
|
||||
project_trust_remove_location always project_host bindings async
|
||||
project_trust_set always project_host bindings async
|
||||
project_trust_status always project_host bindings sync
|
||||
project_workspace_member_set always project_host bindings sync
|
||||
project_workspace_members always project_host bindings sync
|
||||
project_workspace_member_set always project_host bindings spawn
|
||||
project_workspace_members always project_host bindings spawn
|
||||
proxy_check_connection always desktop bindings async
|
||||
python_requirements trusted project_host bindings async
|
||||
recent_files always project_host bindings sync
|
||||
@@ -615,7 +615,7 @@ settings_set always project_host bin
|
||||
show_system_notification trusted desktop bindings sync
|
||||
spell_check always project_host bindings async
|
||||
spell_suggest always project_host bindings async
|
||||
spring_route_sources trusted desktop bindings sync
|
||||
spring_route_sources trusted desktop bindings async
|
||||
ssh_askpass_answer always desktop bindings sync
|
||||
ssh_connected always project_host bindings sync
|
||||
ssh_disconnect always project_host bindings sync
|
||||
|
||||
+20
-4
@@ -55,7 +55,10 @@ export const commands = {
|
||||
*/
|
||||
agentCustomSave: (input: CustomAgentInput) => typedError<null, IdeError>(__TAURI_INVOKE("agent_custom_save", { input })),
|
||||
agentDelete: (task: string, removeWorktree: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("agent_delete", { task, removeWorktree })),
|
||||
/** Entries of `task`'s conversation, or of its subagent `subagent`'s. */
|
||||
/**
|
||||
* Entries of `task`'s conversation, or of its subagent `subagent`'s. Async so a long
|
||||
* conversation is cloned and serialised off the main thread.
|
||||
*/
|
||||
agentEntries: (task: string, subagent: string | null) => typedError<AgentEntry[], IdeError>(__TAURI_INVOKE("agent_entries", { task, subagent })),
|
||||
/** Sessions of the project on this machine that no task holds yet, newest first. */
|
||||
agentExternalSessions: () => typedError<ExternalSession[], IdeError>(__TAURI_INVOKE("agent_external_sessions")),
|
||||
@@ -95,6 +98,10 @@ export const commands = {
|
||||
agentProbe: (provider: string, refresh: boolean) => typedError<AgentProbe, IdeError>(__TAURI_INVOKE("agent_probe", { provider, refresh })),
|
||||
/** Sends a message; while the agent works it is queued, or with `now` it interrupts the turn. */
|
||||
agentPrompt: (task: string, prompt: AgentPrompt, now: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("agent_prompt", { task, prompt, now })),
|
||||
/**
|
||||
* Reads the ACP registry's install state for every provider from disk, so it runs on the
|
||||
* blocking pool.
|
||||
*/
|
||||
agentProviders: () => typedError<AgentProvider[], IdeError>(__TAURI_INVOKE("agent_providers")),
|
||||
/** Refreshes the model catalog; force bypasses freshness, not the cooldown. */
|
||||
agentRefreshModels: (provider: string, force: boolean, model: string | null) => typedError<AgentModelCatalog, IdeError>(__TAURI_INVOKE("agent_refresh_models", { provider, force, model })),
|
||||
@@ -1256,7 +1263,10 @@ export const commands = {
|
||||
pluginSetEnabled: (id: string, enabled: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("plugin_set_enabled", { id, enabled })),
|
||||
/** Sets the marketplace index URL (an `https://…/index.json` or a local path; `None` for the default). */
|
||||
pluginSetMarketUrl: (url: string | null) => __TAURI_INVOKE<void>("plugin_set_market_url", { url }),
|
||||
/** Stores a plugin secret (`None` or empty deletes it). The value never goes back to the UI or the plugin. */
|
||||
/**
|
||||
* Stores a plugin secret (`None` or empty deletes it). The value never goes back to the UI or the plugin.
|
||||
* The keychain call takes up to hundreds of milliseconds, so it runs on the blocking pool.
|
||||
*/
|
||||
pluginSetSecret: (pluginId: string, name: string, value: string | null) => typedError<null, IdeError>(__TAURI_INVOKE("plugin_set_secret", { pluginId, name, value })),
|
||||
/** Selects a plugin theme; both `None` restores the built-in theme. */
|
||||
pluginSetTheme: (pluginId: string | null, themeId: string | null) => typedError<{
|
||||
@@ -1355,9 +1365,15 @@ export const commands = {
|
||||
/**
|
||||
* Sets a `projectStructure.*` key in the settings of `root`, a project attached to the window's
|
||||
* project (Mark Directory as there). Every open window holding that project follows.
|
||||
* Like `project_workspace_members`, its `for_project` settings re-parse runs off the IPC thread.
|
||||
*/
|
||||
projectWorkspaceMemberSet: (root: string, key: string, value: string) => typedError<null, IdeError>(__TAURI_INVOKE("project_workspace_member_set", { root, key, value })),
|
||||
/** The workspace projects outside the window's project folder, for Mark Directory as there. */
|
||||
/**
|
||||
* The workspace projects outside the window's project folder, for Mark Directory as there.
|
||||
* Each member's `for_project().layer(Project)` re-parses both settings layers and validates the
|
||||
* merged tree against `Settings`; that stack-hungry work must not run on the IPC (main) thread,
|
||||
* whose 1 MiB stack overflows on project open (STATUS_STACK_OVERFLOW).
|
||||
*/
|
||||
projectWorkspaceMembers: () => typedError<WorkspaceMember[], IdeError>(__TAURI_INVOKE("project_workspace_members")),
|
||||
/**
|
||||
* System Settings › HTTP Proxy › Check connection: GETs `url` through `proxy` as
|
||||
@@ -6537,7 +6553,7 @@ report?: PushReport | null } |
|
||||
{ type: "amendConflict"; commit: string };
|
||||
|
||||
export type ErrorKind = "notFound" | "alreadyExists" | "permissionDenied" | "invalidInput" |
|
||||
/** Document version mismatch; the UI must resync the full text. */
|
||||
/** The requested state is stale; the UI must use the current snapshot. */
|
||||
"outOfSync" | "cancelled" | "timedOut" |
|
||||
/** A required external tool (language server, git, debugger) is unavailable. */
|
||||
"unavailable" | "io" | "protocol" | "internal";
|
||||
|
||||
@@ -25,6 +25,7 @@ import { languages as languageData } from "@codemirror/language-data";
|
||||
import type { DocBackend, LanguageInfo } from "../backend";
|
||||
import type { BracketSyntax } from "./rainbowBrackets";
|
||||
import { _languageMode, editorsFor } from "@/editor/api";
|
||||
import { wildcardMatch } from "@/platform/fileTypes";
|
||||
import { JS_TAGS } from "./jsTags";
|
||||
import { docCommentTags } from "./docCommentTags";
|
||||
import type { FencedCodeMode } from "./markdown";
|
||||
@@ -97,6 +98,45 @@ export function uiModeForPath(path: string): string | null | undefined {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
let namesOf: {
|
||||
infos: Map<string, LanguageInfo>;
|
||||
byExtension: Map<string, LanguageInfo[]>;
|
||||
byName: Map<string, LanguageInfo[]>;
|
||||
patterns: Array<{ pattern: string; info: LanguageInfo }>;
|
||||
} | null = null;
|
||||
|
||||
/**
|
||||
* The backend languages whose definition claims `path`'s file name (an `extension`, longest first, or
|
||||
* a `filenames` entry); empty when none does, `undefined` while the languages are not loaded. Settings
|
||||
* › File Types and the file's first line are not consulted.
|
||||
*/
|
||||
export function languagesForPath(path: string): readonly LanguageInfo[] | undefined {
|
||||
if (!infos) return undefined;
|
||||
if (namesOf?.infos !== infos) {
|
||||
namesOf = { infos, byExtension: new Map(), byName: new Map(), patterns: [] };
|
||||
const add = (m: Map<string, LanguageInfo[]>, key: string, info: LanguageInfo) =>
|
||||
m.set(key, [...(m.get(key) ?? []), info]);
|
||||
for (const info of infos.values()) {
|
||||
for (const ext of info.extensions) add(namesOf.byExtension, ext.toLowerCase(), info);
|
||||
for (const name of info.filenames ?? []) {
|
||||
if (/[*?]/.test(name)) namesOf.patterns.push({ pattern: name.toLowerCase(), info });
|
||||
else add(namesOf.byName, name.toLowerCase(), info);
|
||||
}
|
||||
}
|
||||
}
|
||||
const name = path.slice(path.lastIndexOf("/") + 1).toLowerCase();
|
||||
const found = new Set(namesOf.byName.get(name));
|
||||
for (const { pattern, info } of namesOf.patterns) if (wildcardMatch(pattern, name)) found.add(info);
|
||||
for (let rest = name, dot = rest.indexOf("."); dot >= 0; dot = rest.indexOf(".")) {
|
||||
rest = rest.slice(dot + 1);
|
||||
const claimed = namesOf.byExtension.get(rest);
|
||||
if (!claimed) continue;
|
||||
for (const info of claimed) found.add(info);
|
||||
break;
|
||||
}
|
||||
return [...found];
|
||||
}
|
||||
|
||||
const supports = new Map<string, Promise<LanguageSupport | null>>();
|
||||
|
||||
/** Frontend modes that extend or replace the bundled parsers. */
|
||||
|
||||
@@ -417,6 +417,11 @@ export function CaretStatus() {
|
||||
}
|
||||
|
||||
const EOL_LABEL: Record<LineEnding, string> = { lf: "LF", crLf: "CRLF", cr: "CR" };
|
||||
const EOL_CHOICES: { id: LineEnding; label: string }[] = [
|
||||
{ id: "crLf", label: "Windows (\\r\\n)" },
|
||||
{ id: "lf", label: "Unix and macOS (\\n)" },
|
||||
{ id: "cr", label: "Classic Mac OS (\\r)" },
|
||||
];
|
||||
|
||||
export function LineEndingStatus() {
|
||||
const meta = useActiveMeta();
|
||||
@@ -454,12 +459,12 @@ export function LineEndingStatus() {
|
||||
onClose={() => setOpen(false)}
|
||||
anchor={ref}
|
||||
placement="top-end"
|
||||
aria-label="Line separator"
|
||||
items={(["lf", "crLf", "cr"] as LineEnding[]).map((le) => ({
|
||||
id: le,
|
||||
label: `${EOL_LABEL[le]} – ${le === "lf" ? "Unix and macOS (\\n)" : le === "crLf" ? "Windows (\\r\\n)" : "Classic Mac OS (\\r)"}`,
|
||||
checked: meta.lineEnding === le ? true : undefined,
|
||||
run: () => choose(le),
|
||||
title="Line Separator"
|
||||
items={EOL_CHOICES.map(({ id, label }) => ({
|
||||
id,
|
||||
label,
|
||||
checked: meta.lineEnding === id ? true : undefined,
|
||||
run: () => choose(id),
|
||||
}))}
|
||||
/>
|
||||
</>
|
||||
|
||||
@@ -37,6 +37,7 @@ const { lspDoc } = await import("./lsp");
|
||||
const { useProject } = await import("@/platform/project");
|
||||
const { emitLocalIdeEvent } = await import("@/platform/ipc");
|
||||
const { useProjectRoots } = await import("@/platform/projectRoots");
|
||||
const { _resetLanguages, loadLanguageInfos } = await import("@/editor/core/cm/languages");
|
||||
|
||||
const ctx = { doc: 7, path: "/p/a.rs", language: "rust", uiMode: "Rust", readOnly: false };
|
||||
const views: EditorView[] = [];
|
||||
@@ -81,6 +82,7 @@ beforeEach(() => {
|
||||
|
||||
afterEach(() => {
|
||||
views.splice(0).forEach((v) => v.destroy());
|
||||
_resetLanguages();
|
||||
useProject.setState({ settings: null });
|
||||
vi.useRealTimers();
|
||||
});
|
||||
@@ -488,3 +490,86 @@ describe("recounting when the project's documents change", () => {
|
||||
expect(titles(view)).toEqual(["4 usages"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("file changes on disk", () => {
|
||||
const language = (id: string, extensions: string[], languageServers: string[], filenames: string[] = []) =>
|
||||
({ id, name: id, extensions, filenames, languageServers, uiMode: null }) as never;
|
||||
const fsChanged = (modified: string[], ignoreRules: string[] = []) =>
|
||||
emitLocalIdeEvent({ type: "fsChanged", created: [], modified, removed: [], ignoreRules });
|
||||
|
||||
async function settledEditors(views: number) {
|
||||
await loadLanguageInfos({
|
||||
languages: async () => [
|
||||
language("rust", ["rs"], ["rust-analyzer"]),
|
||||
language("log", ["log"], []),
|
||||
language("dockerfile", [], ["docker-langserver"], ["Dockerfile.*"]),
|
||||
],
|
||||
} as never);
|
||||
ipc.docOutline.mockResolvedValue(ok(Array.from({ length: 60 }, (_, i) => item(`f${i}`, "function", i))));
|
||||
for (let i = 0; i < views; i++) editor(60);
|
||||
await settle();
|
||||
const first = ipc.lspReferences.mock.calls.length;
|
||||
expect(first).toBe(40 * views);
|
||||
return first;
|
||||
}
|
||||
|
||||
it.each([1, 4])("asks no new counts for events that no source file caused (%i views)", async (n) => {
|
||||
const first = await settledEditors(n);
|
||||
for (let i = 0; i < 10; i++) {
|
||||
fsChanged(["/p/logo.png"]);
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
}
|
||||
fsChanged([], ["/p"]);
|
||||
fsChanged(["/p/debug.log", "/p/Cargo.lock"]);
|
||||
emitLocalIdeEvent({ type: "fsChanged", created: [], modified: [], removed: [] });
|
||||
await settle();
|
||||
expect(ipc.lspReferences).toHaveBeenCalledTimes(first);
|
||||
});
|
||||
|
||||
it("recounts once when a source file is among the changed paths", async () => {
|
||||
const first = await settledEditors(1);
|
||||
for (let i = 0; i < 5; i++) fsChanged(["/p/logo.png", "/p/b.rs", "/p/debug.log"]);
|
||||
await settle();
|
||||
expect(ipc.lspReferences).toHaveBeenCalledTimes(2 * first);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["a created source file", { created: ["/p/new.rs"], modified: [], removed: [] }],
|
||||
["a removed source file", { created: [], modified: [], removed: ["/p/old.RS"] }],
|
||||
["a file the registry matches by name", { created: [], modified: ["/p/Dockerfile.dev"], removed: [] }],
|
||||
[
|
||||
"a path without an extension (a folder, or a script found by its first line)",
|
||||
{ created: [], modified: [], removed: ["/p/src/gen"] },
|
||||
],
|
||||
])("recounts for %s", async (_, paths) => {
|
||||
const first = await settledEditors(1);
|
||||
emitLocalIdeEvent({ type: "fsChanged", ...paths });
|
||||
await settle();
|
||||
expect(ipc.lspReferences).toHaveBeenCalledTimes(2 * first);
|
||||
});
|
||||
|
||||
it("recounts for a file Settings › File Types assigns to a language with a server", async () => {
|
||||
useProject.setState({
|
||||
settings: {
|
||||
editor: { inlay: { codeVisionUsages: true, codeVisionAuthor: false } },
|
||||
files: { fileTypes: { rust: { patterns: ["*.tpl"] } }, fileTypeOverrides: { "/p/x.log": "rust" } },
|
||||
} as never,
|
||||
});
|
||||
const first = await settledEditors(1);
|
||||
fsChanged(["/p/page.tpl"]);
|
||||
await settle();
|
||||
expect(ipc.lspReferences).toHaveBeenCalledTimes(2 * first);
|
||||
fsChanged(["/p/x.log"]);
|
||||
await settle();
|
||||
expect(ipc.lspReferences).toHaveBeenCalledTimes(3 * first);
|
||||
});
|
||||
|
||||
it("recounts for any path while the languages are not loaded", async () => {
|
||||
ipc.docOutline.mockResolvedValue(ok(Array.from({ length: 60 }, (_, i) => item(`f${i}`, "function", i))));
|
||||
editor(60);
|
||||
await settle();
|
||||
fsChanged(["/p/logo.png"]);
|
||||
await settle();
|
||||
expect(ipc.lspReferences).toHaveBeenCalledTimes(80);
|
||||
});
|
||||
});
|
||||
@@ -24,6 +24,8 @@ import { featureBackoff, onLspRefresh, onServerSettled } from "./availability";
|
||||
import { editorPrefs } from "@/platform/editorSettings";
|
||||
import { authorLabel, authorSummary, authorTooltip, blameFor, onBlameInvalidated } from "./authorLens";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { languageInfo, languagesForPath } from "@/editor/core/cm/languages";
|
||||
import { overrideKey, userFileType, validateFileTypeOverrides, validateFileTypes } from "@/platform/fileTypes";
|
||||
|
||||
const LENS_KINDS = new Set<SymbolKind>([
|
||||
"class",
|
||||
@@ -50,6 +52,32 @@ const MARGIN_LINES = 10;
|
||||
const INCOMPLETE_RETRIES = 3;
|
||||
const usagesBackoff = featureBackoff();
|
||||
|
||||
/**
|
||||
* Whether a change on disk can alter a reference count: some changed path is a file a language
|
||||
* server analyses. A path no language claims counts too when it has no extension (a folder, or a
|
||||
* script told by its first line), and so does any path while the languages are not loaded: a
|
||||
* missed recount leaves a stale number, an extra one only repeats a pass.
|
||||
*/
|
||||
function touchesSource(e: { created: string[]; modified: string[]; removed: string[] }): boolean {
|
||||
const { settings, project } = useProject.getState();
|
||||
const assoc = validateFileTypes(settings?.files?.fileTypes);
|
||||
const overrides = validateFileTypeOverrides(settings?.files?.fileTypeOverrides);
|
||||
const root = project?.root ?? null;
|
||||
const served = (l: { languageServers?: string[] }) => !!l.languageServers?.length;
|
||||
const isSource = (path: string) => {
|
||||
const name = path.slice(path.lastIndexOf("/") + 1);
|
||||
const assigned = overrides[overrideKey(path, root)] ?? userFileType(assoc, name);
|
||||
if (assigned) {
|
||||
const info = languageInfo(assigned);
|
||||
return !info || served(info);
|
||||
}
|
||||
const languages = languagesForPath(path);
|
||||
if (!languages) return true;
|
||||
return languages.length ? languages.some(served) : name.lastIndexOf(".") <= 0;
|
||||
};
|
||||
return e.created.some(isSource) || e.modified.some(isSource) || e.removed.some(isSource);
|
||||
}
|
||||
|
||||
export interface LensTarget {
|
||||
name: string;
|
||||
/** 0-based line / UTF-16 col of the identifier. */
|
||||
@@ -172,7 +200,9 @@ class UsagesLensPlugin {
|
||||
});
|
||||
const offBackend = [
|
||||
onIdeEvent("workspaceEditApplied", () => this.invalidate()),
|
||||
onIdeEvent("fsChanged", () => this.invalidate()),
|
||||
onIdeEvent("fsChanged", (e) => {
|
||||
if (touchesSource(e)) this.invalidate();
|
||||
}),
|
||||
onNavigationProvidersChanged(() => this.invalidate()),
|
||||
];
|
||||
this.offChanges = () => {
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
imageFromDataUrl,
|
||||
mainOptions,
|
||||
matchCommands,
|
||||
hasMention,
|
||||
mentionOf,
|
||||
modeIcon,
|
||||
nextValue,
|
||||
@@ -257,6 +258,10 @@ describe("agent composer", () => {
|
||||
images: [],
|
||||
});
|
||||
expect(mentionOf("a.rs", { from: 3, to: 3 })).toBe("@a.rs:3");
|
||||
expect(hasMention("see @a.rs:3 and", "@a.rs:3")).toBe(true);
|
||||
expect(hasMention("see @a.rs:3-4", "@a.rs:3")).toBe(false);
|
||||
expect(hasMention("see @a.rs:3", "@a.rs")).toBe(false);
|
||||
expect(hasMention("@src/a.rs", "@a.rs")).toBe(false);
|
||||
// A folder counts while `@src/` is left as typed, not once a file inside it was picked.
|
||||
const folder = { path: "/w/src", rel: "src/" };
|
||||
expect(toPrompt({ text: "explain @src/ please", files: [folder], images: [] }).files).toEqual(["/w/src"]);
|
||||
|
||||
@@ -373,6 +373,10 @@ export function mentionOf(rel: string, lines?: { from: number; to: number }): st
|
||||
return lines.from === lines.to ? `@${rel}:${lines.from}` : `@${rel}:${lines.from}-${lines.to}`;
|
||||
}
|
||||
|
||||
/** Whether `text` holds exactly `mention` (as made by {@link mentionOf}): same file, same lines. */
|
||||
export const hasMention = (text: string, mention: string) =>
|
||||
new RegExp(`(?:^|\\s)${escapeRe(mention)}(?=\\s|$)`).test(text);
|
||||
|
||||
/** Whether `text` still holds the `@rel` mention, with or without a line range. */
|
||||
export const isMentioned = (text: string, rel: string) =>
|
||||
new RegExp(`@${escapeRe(rel)}(?![\\w./-])|@${escapeRe(rel)}:`).test(text);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
|
||||
import type { AgentProvider, AgentTask, ProjectInfo } from "@/bindings";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { HomeEditor } from "./HomeEditor";
|
||||
@@ -23,6 +23,9 @@ const backend = vi.hoisted(() => ({
|
||||
tauri: false,
|
||||
create: vi.fn(),
|
||||
prompt: vi.fn(),
|
||||
unqueue: vi.fn(),
|
||||
sendQueued: vi.fn(),
|
||||
notify: vi.fn(),
|
||||
open: vi.fn(),
|
||||
close: vi.fn(),
|
||||
}));
|
||||
@@ -38,6 +41,8 @@ vi.mock("@/platform/ipc", async (original) => ({
|
||||
commands: {
|
||||
agentCreate: backend.create,
|
||||
agentPrompt: backend.prompt,
|
||||
agentUnqueue: backend.unqueue,
|
||||
agentSendQueuedNow: backend.sendQueued,
|
||||
agentSubscribe: async () => ({ status: "ok", data: [] }),
|
||||
agentProviders: async () => ({ status: "ok", data: [provider] }),
|
||||
agentRefreshModels: async (id: string) => ({
|
||||
@@ -64,6 +69,7 @@ vi.mock("@/workbench/contributions", async (original) => ({
|
||||
editorService: () => ({ openInput: backend.open, closeInput: backend.close }),
|
||||
maybeEditorService: () => ({ activePath: () => null }),
|
||||
toolWindowService: () => ({ show: vi.fn() }),
|
||||
notifications: () => ({ notify: backend.notify }),
|
||||
}));
|
||||
|
||||
const ok = <T,>(data: T) => ({ status: "ok" as const, data });
|
||||
@@ -353,6 +359,50 @@ describe.each(paths)("$name acknowledgement", (path) => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("queued message actions", () => {
|
||||
const item = (id: string) => ({ id, prompt: { text: id, files: [], images: [] } });
|
||||
function showQueue() {
|
||||
useAgents.setState({ tasks: new Map([["A", { ...task("A"), queue: [item("first"), item("second")] }]]) });
|
||||
updateComposer("A", { text: "unsent draft" });
|
||||
render(<SessionEditor input={{ kind: SESSION_KIND, key: sessionKey("A"), data: { task: "A" } }} />);
|
||||
return within(screen.getByLabelText("Queued messages"));
|
||||
}
|
||||
|
||||
it("locks only the pending row and leaves the draft alone when another turn takes it", async () => {
|
||||
const response = deferred();
|
||||
backend.unqueue.mockReturnValue(response.promise);
|
||||
const queue = showQueue();
|
||||
fireEvent.click(queue.getAllByRole("button", { name: "Edit" })[0]!);
|
||||
for (const name of ["Send now", "Edit", "Remove"]) {
|
||||
const [first, second] = queue.getAllByRole("button", { name });
|
||||
expect(first).toBeDisabled();
|
||||
expect(second).toBeEnabled();
|
||||
fireEvent.click(first!);
|
||||
}
|
||||
expect(backend.unqueue).toHaveBeenCalledTimes(1);
|
||||
expect(backend.sendQueued).not.toHaveBeenCalled();
|
||||
await act(async () => {
|
||||
useAgents.setState({ tasks: new Map([["A", { ...task("A"), queue: [item("second")] }]]) });
|
||||
response.resolve({ status: "error", error: { kind: "outOfSync", message: "Message is no longer queued" } });
|
||||
});
|
||||
expect(queue.queryByText("first")).not.toBeInTheDocument();
|
||||
expect(composerDraft("A").text).toBe("unsent draft");
|
||||
expect(backend.notify).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("still reports a missing task and allows another action after a real failure", async () => {
|
||||
backend.sendQueued.mockResolvedValue({ status: "error", error: { kind: "notFound", message: "missing task" } });
|
||||
const queue = showQueue();
|
||||
fireEvent.click(queue.getAllByRole("button", { name: "Send now" })[0]!);
|
||||
await waitFor(() =>
|
||||
expect(backend.notify).toHaveBeenCalledWith(expect.objectContaining({ body: "IpcError: missing task" })),
|
||||
);
|
||||
backend.unqueue.mockResolvedValue(ok(item("first")));
|
||||
fireEvent.click(queue.getAllByRole("button", { name: "Edit" })[0]!);
|
||||
await waitFor(() => expect(composerDraft("A").text).toBe("first\nunsent draft"));
|
||||
});
|
||||
});
|
||||
|
||||
describe("composer UI during submission", () => {
|
||||
it("keeps typing and attachments in the session after Send completes", async () => {
|
||||
const response = deferred();
|
||||
|
||||
@@ -155,6 +155,24 @@ describe("Send to Agent from the editor", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("sending the same file or lines again does not reference them twice (#5296)", () => {
|
||||
setup({});
|
||||
openEditor(`${BACK}/pom.xml`);
|
||||
expect(sendSelection()).toBe(true);
|
||||
expect(sendSelection()).toBe(true);
|
||||
expect(sent()).toEqual({ text: "@pom.xml", files: [["pom.xml", `${BACK}/pom.xml`]] });
|
||||
|
||||
// Other lines of the same file are a reference of their own; the same lines again are not.
|
||||
openEditor(`${BACK}/pom.xml`, 2, 3);
|
||||
sendSelection();
|
||||
sendSelection();
|
||||
expect(sent()).toEqual({ text: "@pom.xml @pom.xml:2", files: [["pom.xml", `${BACK}/pom.xml`]] });
|
||||
|
||||
// Files from the Project view: only the ones not in the message yet are added.
|
||||
sendPaths([`${BACK}/pom.xml`, `${BACK}/src/`, `${BACK}/src/`]);
|
||||
expect(sent().text).toBe("@pom.xml @pom.xml:2 @src/");
|
||||
});
|
||||
|
||||
it("the whole file without a selection; a file outside the projects shows the notice", () => {
|
||||
setup({ members: [BACK, FRONT], homeRoot: BACK });
|
||||
openEditor(`${BACK}/pom.xml`);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { AgentChange, AgentCommit, AgentConfigOption, AgentEntry, AgentTask } from "@/bindings";
|
||||
import type { AgentChange, AgentCommit, AgentConfigOption, AgentEntry, AgentQueued, AgentTask } from "@/bindings";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { tx, useTx } from "@/platform/i18n";
|
||||
import { isErrorKind } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { Icon, IconButton, T, type IconName } from "@/ui";
|
||||
import { notifications, useEditorShown } from "@/workbench/contributions";
|
||||
@@ -429,25 +430,39 @@ function BackgroundTasks({ task }: { task: AgentTask }) {
|
||||
}
|
||||
|
||||
function Queue({ task }: { task: AgentTask }) {
|
||||
const fail = (e: unknown) =>
|
||||
notifications().notify({
|
||||
level: "error",
|
||||
title: "Couldn't update the queue",
|
||||
body: String(e),
|
||||
});
|
||||
return (
|
||||
<div className={styles.queue} aria-label={tx("Queued messages")}>
|
||||
{task.queue.map((q) => (
|
||||
<div key={q.id} className={styles.queued}>
|
||||
<Icon name="pause" size={12} className={styles.muted} />
|
||||
<span className={styles.queuedText} title={q.prompt.text}>
|
||||
{q.prompt.text || <T>Image</T>}
|
||||
</span>
|
||||
<IconButton icon="arrow-up" title="Send now" onClick={() => void sendQueuedNow(task.id, q.id).catch(fail)} />
|
||||
<IconButton icon="edit" title="Edit" onClick={() => void editQueued(task.id, q.id).catch(fail)} />
|
||||
<IconButton icon="close" title="Remove" onClick={() => void removeQueued(task.id, q.id).catch(fail)} />
|
||||
</div>
|
||||
<QueueRow key={q.id} task={task.id} item={q} />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function QueueRow({ task, item }: { task: string; item: AgentQueued }) {
|
||||
const [pending, setPending] = useState(false);
|
||||
async function run(action: (task: string, queued: string) => Promise<unknown>) {
|
||||
if (pending) return;
|
||||
setPending(true);
|
||||
try {
|
||||
await action(task, item.id);
|
||||
} catch (e) {
|
||||
// The backend already published the current queue when it found the item gone.
|
||||
if (!isErrorKind(e, "outOfSync"))
|
||||
notifications().notify({ level: "error", title: "Couldn't update the queue", body: String(e) });
|
||||
} finally {
|
||||
setPending(false);
|
||||
}
|
||||
}
|
||||
return (
|
||||
<div className={styles.queued}>
|
||||
<Icon name="pause" size={12} className={styles.muted} />
|
||||
<span className={styles.queuedText} title={item.prompt.text}>
|
||||
{item.prompt.text || <T>Image</T>}
|
||||
</span>
|
||||
<IconButton icon="arrow-up" title="Send now" disabled={pending} onClick={() => void run(sendQueuedNow)} />
|
||||
<IconButton icon="edit" title="Edit" disabled={pending} onClick={() => void run(editQueued)} />
|
||||
<IconButton icon="close" title="Remove" disabled={pending} onClick={() => void run(removeQueued)} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
|
||||
import { registerActions } from "@/platform/actions";
|
||||
import { emitLocalIdeEvent } from "@/platform/ipc";
|
||||
import { commands, emitLocalIdeEvent } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { deferred } from "@/test/deferred";
|
||||
import { EditorShownProvider } from "@/workbench/contributions";
|
||||
import { hideContextMenu, useContextMenuStore } from "@/ui";
|
||||
import type { AgentChange, AgentCommit, AgentEntry, AgentTask } from "@/bindings";
|
||||
@@ -11,11 +12,15 @@ import { SessionEditor } from "./SessionEditor";
|
||||
import { conversationRows } from "./session/conversationRows";
|
||||
import { entriesKey, SESSION_KIND, sessionKey, type SubagentEntry } from "./model";
|
||||
import {
|
||||
acceptChanges,
|
||||
disconnect,
|
||||
hideImportSessions,
|
||||
importExternalSessions,
|
||||
refreshChanges,
|
||||
refreshExternalSessions,
|
||||
releaseClosedTaskCache,
|
||||
rollbackChanges,
|
||||
scheduleChanges,
|
||||
showImportSessions,
|
||||
useAgents,
|
||||
} from "./store";
|
||||
@@ -2830,6 +2835,92 @@ describe("import sessions dialog", () => {
|
||||
});
|
||||
|
||||
describe("changes refresh", () => {
|
||||
it("coalesces a burst of six edits without losing the final revision", async () => {
|
||||
vi.useFakeTimers();
|
||||
useAgents.setState({ docked: "A" });
|
||||
let revision = 0;
|
||||
let active = 0;
|
||||
let peak = 0;
|
||||
const reads = vi.spyOn(commands, "agentChanges").mockImplementation(async () => {
|
||||
const added = revision;
|
||||
peak = Math.max(peak, ++active);
|
||||
// The oldest snapshot arrives last if the reads overlap.
|
||||
await new Promise((done) => setTimeout(done, added === 1 ? 6000 : 3000));
|
||||
active--;
|
||||
return {
|
||||
status: "ok",
|
||||
data: [{ path: "/project/a", relPath: "a", kind: "modified", added, removed: 0, oldPath: null, repo: null }],
|
||||
};
|
||||
});
|
||||
for (let i = 0; i < 6; i++) {
|
||||
revision++;
|
||||
scheduleChanges("A");
|
||||
await vi.advanceTimersByTimeAsync(500);
|
||||
}
|
||||
await vi.runAllTimersAsync();
|
||||
const finalRevision = useAgents.getState().changes.get("A")?.[0]?.added;
|
||||
expect({ starts: reads.mock.calls.length, peak, finalRevision }).toEqual({ starts: 2, peak: 1, finalRevision: 6 });
|
||||
});
|
||||
|
||||
it("accept and rollback await their trailing read, not an earlier read or the next burst", async () => {
|
||||
vi.useFakeTimers();
|
||||
useAgents.setState({ docked: "A" });
|
||||
const reads = vi.spyOn(commands, "agentChanges").mockImplementation(async () => {
|
||||
const data = backend.changes;
|
||||
await new Promise((done) => setTimeout(done, 1000));
|
||||
return { status: "ok", data };
|
||||
});
|
||||
void refreshChanges("A");
|
||||
const accepted = vi.fn();
|
||||
const rolledBack = vi.fn();
|
||||
void acceptChanges("A", null).then(accepted);
|
||||
void rollbackChanges("A", null).then(rolledBack);
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
expect(reads).toHaveBeenCalledTimes(2);
|
||||
expect(accepted).not.toHaveBeenCalled();
|
||||
expect(rolledBack).not.toHaveBeenCalled();
|
||||
|
||||
backend.changes = [
|
||||
{ path: "/project/b", relPath: "b", kind: "deleted", added: 0, removed: 1, oldPath: null, repo: null },
|
||||
];
|
||||
scheduleChanges("A"); // Fresh demand during the trailing read needs another pass.
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
expect(reads).toHaveBeenCalledTimes(3);
|
||||
expect(accepted).toHaveBeenCalledOnce();
|
||||
expect(rolledBack).toHaveBeenCalledOnce();
|
||||
await vi.runAllTimersAsync();
|
||||
expect(useAgents.getState().changes.get("A")).toEqual(backend.changes);
|
||||
});
|
||||
|
||||
it("waits for both change views, samples options on rerun, and doesn't block another task", async () => {
|
||||
vi.useFakeTimers();
|
||||
useAgents.setState((s) => ({ tasks: new Map(s.tasks).set("A", { ...task("A"), isolation: "worktree" }) }));
|
||||
useChangesOptions.setState({ groupByCommit: true, scope: "turn" });
|
||||
const lastTurn = deferred<Awaited<ReturnType<typeof commands.agentChanges>>>();
|
||||
const flat = vi.spyOn(commands, "agentChanges").mockImplementationOnce(() => lastTurn.promise);
|
||||
const grouped = vi.spyOn(commands, "agentGroupedChanges");
|
||||
scheduleChanges("A"); // Already covered by the manual read below.
|
||||
const first = refreshChanges("A");
|
||||
const next = refreshChanges("A");
|
||||
useChangesOptions.setState({ scope: "task" });
|
||||
await refreshChanges("B");
|
||||
expect(grouped.mock.calls).toEqual([["A"]]);
|
||||
expect(flat.mock.calls).toEqual([
|
||||
["A", "lastTurn"],
|
||||
["B", null],
|
||||
]);
|
||||
expect(useAgents.getState().changes.has("B")).toBe(true);
|
||||
|
||||
useChangesOptions.setState({ groupByCommit: false });
|
||||
lastTurn.resolve({ status: "ok", data: [] });
|
||||
await Promise.all([first, next]);
|
||||
await vi.runAllTimersAsync();
|
||||
expect(flat.mock.calls.slice(2)).toEqual([["A", null]]);
|
||||
expect(useAgents.getState().changes.has("A")).toBe(true);
|
||||
expect(useAgents.getState().turnChanges.has("A")).toBe(true);
|
||||
expect(useAgents.getState().groupedChanges.has("A")).toBe(true);
|
||||
});
|
||||
|
||||
it("re-reads the changes only when the task's own checkout changes", async () => {
|
||||
vi.useFakeTimers();
|
||||
render(<SessionEditor input={input("A")} />);
|
||||
|
||||
@@ -40,6 +40,7 @@ import {
|
||||
shellCommand,
|
||||
cursorModelDefaults,
|
||||
emptyDraft,
|
||||
hasMention,
|
||||
isMentioned,
|
||||
isPerModelOption,
|
||||
mentionOf,
|
||||
@@ -531,6 +532,7 @@ async function refreshProviderModels(
|
||||
export async function connect(): Promise<void> {
|
||||
if (!isTauri()) return;
|
||||
const gen = ++generation;
|
||||
clearChangeRefreshes();
|
||||
const channel = new Channel<AgentEvent>();
|
||||
channel.onmessage = (e) => {
|
||||
if (gen === generation) onEvent(e);
|
||||
@@ -616,8 +618,6 @@ const CACHED_CLOSED_TASKS = 5;
|
||||
|
||||
/** Recent closed-task ids kept in memory so reopening a just-closed tab avoids refetching. */
|
||||
const closedTaskMru: string[] = [];
|
||||
/** Bumped when a task's cache is dropped, so a fetch started before that doesn't refill it. */
|
||||
const cacheDrops = new Map<string, number>();
|
||||
|
||||
function isTaskKey(key: string, taskId: string): boolean {
|
||||
return key === taskId || key.startsWith(`${taskId}/`);
|
||||
@@ -639,11 +639,9 @@ function clearTaskMaps(taskId: string, clearStreaming = false) {
|
||||
if (isTaskKey(key, taskId)) positions.delete(key);
|
||||
}
|
||||
if (clearStreaming) streamingReply.delete(taskId);
|
||||
const timer = pendingChanges.get(taskId);
|
||||
if (timer !== undefined) {
|
||||
clearTimeout(timer);
|
||||
pendingChanges.delete(taskId);
|
||||
}
|
||||
cancelScheduledChanges(taskId);
|
||||
const last = changeRefreshes.get(taskId);
|
||||
if (last) last.cache.dropped = true;
|
||||
}
|
||||
|
||||
function withoutTaskCache(s: AgentsState, taskId: string): Partial<AgentsState> | null {
|
||||
@@ -682,8 +680,6 @@ function withoutTaskCache(s: AgentsState, taskId: string): Partial<AgentsState>
|
||||
|
||||
function dropTaskCache(taskId: string) {
|
||||
clearTaskMaps(taskId);
|
||||
// A deleted task needs no marker: fetches already discard results for tasks that are gone.
|
||||
if (useAgents.getState().tasks.has(taskId)) cacheDrops.set(taskId, (cacheDrops.get(taskId) ?? 0) + 1);
|
||||
useAgents.setState((s) => withoutTaskCache(s, taskId) ?? s);
|
||||
}
|
||||
|
||||
@@ -726,9 +722,7 @@ export function disconnect() {
|
||||
streamingReply.clear();
|
||||
modelFlights.clear();
|
||||
closedTaskMru.length = 0;
|
||||
cacheDrops.clear();
|
||||
for (const timer of pendingChanges.values()) clearTimeout(timer);
|
||||
pendingChanges.clear();
|
||||
clearChangeRefreshes();
|
||||
resetAllAgentFontZoom();
|
||||
useAgents.setState({
|
||||
loaded: false,
|
||||
@@ -780,7 +774,6 @@ function onEvent(e: AgentEvent) {
|
||||
}
|
||||
case "removed": {
|
||||
clearTaskMaps(e.id, true);
|
||||
cacheDrops.delete(e.id);
|
||||
const tasks = new Map(s.tasks);
|
||||
tasks.delete(e.id);
|
||||
const composers = new Map(s.composers);
|
||||
@@ -921,17 +914,49 @@ 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 pendingChanges = new Map<string, ReturnType<typeof setTimeout>>();
|
||||
/** Last pass for each task. The active and trailing pass share a cache lifetime until eviction. */
|
||||
const changeRefreshes = new Map<string, { done: Promise<void>; started: boolean; cache: { dropped: boolean } }>();
|
||||
|
||||
function cancelScheduledChanges(task: string) {
|
||||
clearTimeout(pendingChanges.get(task));
|
||||
pendingChanges.delete(task);
|
||||
}
|
||||
|
||||
function clearChangeRefreshes() {
|
||||
for (const timer of pendingChanges.values()) clearTimeout(timer);
|
||||
pendingChanges.clear();
|
||||
changeRefreshes.clear();
|
||||
}
|
||||
|
||||
/** Waits for the first read that starts after this request, not for the queue to go idle. */
|
||||
export function refreshChanges(task: string): Promise<void> {
|
||||
if (!useAgents.getState().tasks.has(task)) return Promise.resolve();
|
||||
const last = changeRefreshes.get(task);
|
||||
const current = last && !last.cache.dropped ? last : undefined;
|
||||
if (current && !current.started) return current.done;
|
||||
|
||||
const gen = generation;
|
||||
const drops = cacheDrops.get(task);
|
||||
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),
|
||||
]);
|
||||
const pass = { done: Promise.resolve(), started: false, cache: current?.cache ?? { dropped: false } };
|
||||
const stillWanted = () => gen === generation && !pass.cache.dropped && useAgents.getState().tasks.has(task);
|
||||
const read = async () => {
|
||||
pass.started = true;
|
||||
try {
|
||||
if (!stillWanted()) return;
|
||||
cancelScheduledChanges(task); // This read covers notifications still waiting on the timer.
|
||||
// The session summary needs the whole task even when the pane shows just its last turn.
|
||||
await Promise.all([
|
||||
refreshTaskChanges(task, stillWanted),
|
||||
useChangesOptions.getState().scope === "turn" && refreshTurnChanges(task, stillWanted),
|
||||
]);
|
||||
} finally {
|
||||
if (changeRefreshes.get(task) === pass) changeRefreshes.delete(task);
|
||||
}
|
||||
};
|
||||
changeRefreshes.set(task, pass);
|
||||
// A reopened tab can't cancel the obsolete IPC either; wait for it before starting a fresh read.
|
||||
pass.done = last ? last.done.then(read, read) : read();
|
||||
return pass.done;
|
||||
}
|
||||
|
||||
async function refreshTurnChanges(task: string, stillWanted: () => boolean): Promise<void> {
|
||||
@@ -995,7 +1020,6 @@ export async function acceptChanges(task: string, relPaths: string[] | null): Pr
|
||||
}
|
||||
}
|
||||
|
||||
const pendingChanges = new Map<string, ReturnType<typeof setTimeout>>();
|
||||
/** Reloads the task's changes after a short pause (tool diffs, commits landing). */
|
||||
export function scheduleChanges(task: string) {
|
||||
if (pendingChanges.has(task)) return;
|
||||
@@ -1674,16 +1698,20 @@ export interface ReferenceTarget {
|
||||
* how many were added; a path outside every project shows a notice.
|
||||
*/
|
||||
export function addReferences(targets: readonly ReferenceTarget[]): number {
|
||||
return appendToComposer((mentions) => mentions.join(" "), targets);
|
||||
// A reference the message already holds (same file, same lines) is not added a second time.
|
||||
return appendToComposer(
|
||||
(mentions, text) => mentions.filter((m, i) => !hasMention(text, m) && mentions.indexOf(m) === i).join(" "),
|
||||
targets,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Appends text to the agent message typed last (a task's or New Task's) and opens it; nothing is
|
||||
* sent. `compose` gets the `@` mentions of `targets` (those inside this window's projects, which
|
||||
* also become chips). Returns how many targets were referenced.
|
||||
* also become chips) and the message's current text. Returns how many targets were referenced.
|
||||
*/
|
||||
export function appendToComposer(
|
||||
compose: (mentions: readonly string[]) => string,
|
||||
compose: (mentions: readonly string[], text: string) => string,
|
||||
targets: readonly ReferenceTarget[] = [],
|
||||
): number {
|
||||
const s = useAgents.getState();
|
||||
@@ -1709,15 +1737,26 @@ export function appendToComposer(
|
||||
}
|
||||
if (files.length < targets.length)
|
||||
notifications().notify({ level: "info", title: tx("Only files of this window's projects can be referenced") });
|
||||
const joined = compose(mentions);
|
||||
if (!joined) return 0;
|
||||
const joined = compose(mentions, current.text);
|
||||
if (!joined) {
|
||||
// Every reference is already in the message: show it rather than doing nothing.
|
||||
if (!files.length) return 0;
|
||||
if (task) openTask(task.id);
|
||||
else openHome();
|
||||
return files.length;
|
||||
}
|
||||
// A block of several lines (a test failure) goes in a paragraph of its own.
|
||||
const text = joined.includes("\n")
|
||||
? `${current.text.trimEnd() ? `${current.text.trimEnd()}\n\n` : ""}${joined}\n`
|
||||
: current.text && !/\s$/.test(current.text)
|
||||
? `${current.text} ${joined} `
|
||||
: `${current.text}${joined} `;
|
||||
updateComposer(key, { text, files: [...current.files, ...files] });
|
||||
const added = files.filter(
|
||||
(f, i) =>
|
||||
!current.files.some((c) => c.path === f.path && c.rel === f.rel) &&
|
||||
files.findIndex((o) => o.path === f.path && o.rel === f.rel) === i,
|
||||
);
|
||||
updateComposer(key, { text, files: [...current.files, ...added] });
|
||||
if (task) openTask(task.id);
|
||||
else openHome();
|
||||
return files.length;
|
||||
|
||||
@@ -13,6 +13,8 @@ import { AgentsStatus } from "./AgentsStatus";
|
||||
import { activate } from "./index";
|
||||
import { openChangeDiff } from "./session/ChangesPane";
|
||||
import * as actions from "@/platform/actions";
|
||||
import { commands } from "@/platform/ipc";
|
||||
import { deferred } from "@/test/deferred";
|
||||
import { SESSION_KIND, sessionKey, TASK_DRAG } from "./model";
|
||||
import {
|
||||
connect,
|
||||
@@ -22,6 +24,7 @@ import {
|
||||
markVisible,
|
||||
openHome,
|
||||
openTask,
|
||||
refreshChanges,
|
||||
setSessionLocation,
|
||||
undockTask,
|
||||
useAgents,
|
||||
@@ -147,6 +150,47 @@ describe("agent tab titles", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("in-flight change reads", () => {
|
||||
it.each(["project switch", "removal", "cache eviction"])(
|
||||
"drops stale results and queued reads on %s",
|
||||
async (why) => {
|
||||
const reply = deferred<Awaited<ReturnType<typeof commands.agentChanges>>>();
|
||||
const reads = vi.spyOn(commands, "agentChanges").mockImplementationOnce(() => reply.promise);
|
||||
const first = refreshChanges("one");
|
||||
const next = refreshChanges("one");
|
||||
if (why === "project switch") {
|
||||
disconnect();
|
||||
await connect(); // Same id in the new project.
|
||||
} else if (why === "removal") {
|
||||
emit({ type: "removed", id: "one" });
|
||||
emit({ type: "task", task: task("one") });
|
||||
} else {
|
||||
emit({ type: "task", task: task("one", "archived") }); // Not open: drops its cache.
|
||||
}
|
||||
reply.resolve({ status: "ok", data: [] });
|
||||
await Promise.all([first, next]);
|
||||
expect(reads).toHaveBeenCalledTimes(1);
|
||||
expect(useAgents.getState().changes.has("one")).toBe(false);
|
||||
await refreshChanges("one");
|
||||
expect(useAgents.getState().changes.has("one")).toBe(true);
|
||||
},
|
||||
);
|
||||
|
||||
it("honors a fresh request after eviction without overlapping the obsolete read", async () => {
|
||||
const stale = deferred<Awaited<ReturnType<typeof commands.agentChanges>>>();
|
||||
const reads = vi.spyOn(commands, "agentChanges").mockImplementationOnce(() => stale.promise);
|
||||
const first = refreshChanges("one");
|
||||
const abandoned = refreshChanges("one");
|
||||
emit({ type: "task", task: task("one", "archived") });
|
||||
const reopened = refreshChanges("one");
|
||||
expect(reads).toHaveBeenCalledTimes(1);
|
||||
stale.resolve({ status: "ok", data: [] });
|
||||
await Promise.all([first, abandoned, reopened]);
|
||||
expect(reads).toHaveBeenCalledTimes(2);
|
||||
expect(useAgents.getState().changes.has("one")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("agent unread activity", () => {
|
||||
it("does not mark historical tasks unread, but tracks replies even without loaded entries", () => {
|
||||
expect(useAgents.getState().unread.size).toBe(0);
|
||||
|
||||
@@ -161,34 +161,51 @@
|
||||
padding: 14px;
|
||||
}
|
||||
.scope {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-0-5);
|
||||
container: analysis-scope / inline-size;
|
||||
min-inline-size: 0;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
}
|
||||
.scopeOptions {
|
||||
display: grid;
|
||||
grid-template-columns: fit-content(45%) minmax(0, 1fr);
|
||||
align-items: center;
|
||||
gap: var(--space-0-5) var(--space-2);
|
||||
}
|
||||
.fieldLabel {
|
||||
padding: 0 0 4px;
|
||||
color: var(--fg-secondary);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
.radioRow {
|
||||
grid-column: 1 / -1;
|
||||
min-width: 0;
|
||||
padding-block: var(--space-0-5);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.scopeWithField {
|
||||
grid-column: 1;
|
||||
}
|
||||
.scopeControl {
|
||||
grid-column: 2;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
padding: 3px 0;
|
||||
color: var(--fg);
|
||||
cursor: default;
|
||||
}
|
||||
.radioRow input {
|
||||
margin: 0;
|
||||
accent-color: var(--accent);
|
||||
}
|
||||
.dirRow {
|
||||
display: flex;
|
||||
gap: var(--space-1-5);
|
||||
padding: 4px 0 0 22px;
|
||||
min-width: 0;
|
||||
}
|
||||
.scopeControl > button:last-child {
|
||||
flex: none;
|
||||
}
|
||||
@container analysis-scope (max-width: 336px) {
|
||||
.scopeOptions {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
.scopeControl {
|
||||
grid-column: 1;
|
||||
padding-inline-start: calc(16px + var(--space-2));
|
||||
margin-block-end: var(--space-1);
|
||||
}
|
||||
}
|
||||
.grow {
|
||||
flex: 1;
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
/** Dialog stack of the analysis feature and the shared "Specify Scope" fields. */
|
||||
import { Fragment, type ReactNode } from "react";
|
||||
import clsx from "clsx";
|
||||
import { create } from "zustand";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { isTauri } from "@/platform/ipc";
|
||||
import { EDIT_SCOPES_ACTION, useCustomScopeList } from "@/platform/search";
|
||||
import { Button, IconButton, Input, Select, T } from "@/ui";
|
||||
import { Button, IconButton, Input, Radio, Select, T } from "@/ui";
|
||||
import { SCOPE_LABELS, currentFile, type ScopeChoice, type ScopeKind } from "./scope";
|
||||
import styles from "./Analysis.module.css";
|
||||
|
||||
@@ -62,57 +63,69 @@ export function ScopeFields({
|
||||
}) {
|
||||
const file = currentFile();
|
||||
const scopes = useCustomScopeList();
|
||||
const custom = value.custom ?? scopes[0]?.name;
|
||||
return (
|
||||
<fieldset className={styles.scope}>
|
||||
<legend className={styles.fieldLabel}>
|
||||
<T>Scope</T>
|
||||
</legend>
|
||||
{kinds.map((kind) => (
|
||||
<label key={kind} className={styles.radioRow}>
|
||||
<input
|
||||
type="radio"
|
||||
name={name}
|
||||
checked={value.kind === kind}
|
||||
disabled={kind === "file" && !file}
|
||||
onChange={() =>
|
||||
onChange({ ...value, kind, custom: kind === "custom" ? (value.custom ?? scopes[0]?.name) : value.custom })
|
||||
}
|
||||
/>
|
||||
<span>{kind === "file" && file ? tx`File '${file.split("/").pop()}'` : tx(SCOPE_LABELS[kind])}</span>
|
||||
</label>
|
||||
))}
|
||||
{value.kind === "directory" && (
|
||||
<div className={styles.dirRow}>
|
||||
<Input
|
||||
aria-label="Directory"
|
||||
value={value.directory}
|
||||
onChange={(e) => onChange({ ...value, directory: e.target.value })}
|
||||
className={styles.grow}
|
||||
/>
|
||||
<Button
|
||||
onClick={() => void browseDirectory(value.directory).then((d) => d && onChange({ ...value, directory: d }))}
|
||||
>
|
||||
<T>Browse…</T>
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{value.kind === "custom" && (
|
||||
<div className={styles.dirRow}>
|
||||
<Select<string>
|
||||
className={styles.grow}
|
||||
value={value.custom ?? null}
|
||||
options={scopes.map((s) => ({ value: s.name, label: s.name, detail: s.pattern }))}
|
||||
placeholder="No custom scopes"
|
||||
onChange={(custom) => onChange({ ...value, custom })}
|
||||
aria-label="Custom scope"
|
||||
/>
|
||||
<IconButton
|
||||
icon="more-horizontal"
|
||||
title="Edit Scopes…"
|
||||
onClick={() => void executeAction(EDIT_SCOPES_ACTION, value.custom ? { select: value.custom } : undefined)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<div className={styles.scopeOptions}>
|
||||
{kinds.map((kind) => {
|
||||
const selected = value.kind === kind;
|
||||
return (
|
||||
<Fragment key={kind}>
|
||||
<Radio
|
||||
name={name}
|
||||
checked={selected}
|
||||
disabled={kind === "file" && !file}
|
||||
onChange={() => onChange({ ...value, kind, custom: kind === "custom" ? custom : value.custom })}
|
||||
label={
|
||||
kind === "file" && file ? <span>{tx`File '${file.split("/").pop()}'`}</span> : SCOPE_LABELS[kind]
|
||||
}
|
||||
className={clsx(styles.radioRow, (kind === "directory" || kind === "custom") && styles.scopeWithField)}
|
||||
/>
|
||||
{kind === "directory" && (
|
||||
<div className={styles.scopeControl}>
|
||||
<Input
|
||||
aria-label="Directory"
|
||||
value={value.directory}
|
||||
disabled={!selected}
|
||||
onChange={(e) => onChange({ ...value, directory: e.target.value })}
|
||||
className={styles.grow}
|
||||
/>
|
||||
<Button
|
||||
disabled={!selected}
|
||||
onClick={() =>
|
||||
void browseDirectory(value.directory).then((d) => d && onChange({ ...value, directory: d }))
|
||||
}
|
||||
>
|
||||
<T>Browse…</T>
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{kind === "custom" && (
|
||||
<div className={styles.scopeControl}>
|
||||
<Select<string>
|
||||
className={styles.grow}
|
||||
value={(selected ? value.custom : custom) ?? null}
|
||||
options={scopes.map((s) => ({ value: s.name, label: s.name, detail: s.pattern }))}
|
||||
placeholder={scopes.length ? "Choose a scope" : "No custom scopes"}
|
||||
disabled={!selected}
|
||||
onChange={(custom) => onChange({ ...value, custom })}
|
||||
aria-label="Custom scope"
|
||||
/>
|
||||
<IconButton
|
||||
icon="more-horizontal"
|
||||
title="Edit Scopes…"
|
||||
disabled={!selected}
|
||||
onClick={() => void executeAction(EDIT_SCOPES_ACTION, custom ? { select: custom } : undefined)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</Fragment>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</fieldset>
|
||||
);
|
||||
}
|
||||
@@ -31,6 +31,7 @@ import {
|
||||
mavenRoots,
|
||||
nodeIcon,
|
||||
nodeLabel,
|
||||
pluginCoordinates,
|
||||
profileChecked,
|
||||
withGradleOptions,
|
||||
gradleHasTestTask,
|
||||
@@ -310,6 +311,8 @@ function NodeRow({ node, state }: { node: BuildNode; state: TreeRowState }) {
|
||||
</span>
|
||||
);
|
||||
}
|
||||
const plugin = node.kind === "plugin" ? node.plugin : null;
|
||||
const coordinates = plugin && `(${pluginCoordinates(plugin)})`;
|
||||
const detail =
|
||||
node.kind === "profiles" && node.projectRoot
|
||||
? node.projectRoot.split("/").pop()
|
||||
@@ -317,18 +320,28 @@ function NodeRow({ node, state }: { node: BuildNode; state: TreeRowState }) {
|
||||
? `(${node.dependency.scope}${node.dependency.optional ? ", optional" : ""})`
|
||||
: node.kind === "dependency" && node.dependency.optional
|
||||
? "(optional)"
|
||||
: node.kind === "task"
|
||||
? node.task.description
|
||||
: null;
|
||||
: null;
|
||||
const skipped =
|
||||
(mavenSkipTests && node.kind === "phase" && node.phase === "test") ||
|
||||
(gradleSkipTests && node.kind === "task" && node.task.name === "test");
|
||||
const label = (
|
||||
<span className={clsx(styles.label, state.selected && styles.selectedLabel, skipped && styles.skippedGoal)}>
|
||||
{plugin?.prefix ?? nodeLabel(node)}
|
||||
</span>
|
||||
);
|
||||
return (
|
||||
<span className={styles.row} title={node.kind === "task" ? (node.task.description ?? undefined) : undefined}>
|
||||
<span className={styles.row}>
|
||||
<Icon name={nodeIcon(node)} size={16} className={styles.icon} />
|
||||
<span className={clsx(styles.label, state.selected && styles.selectedLabel, skipped && styles.skippedGoal)}>
|
||||
{nodeLabel(node)}
|
||||
</span>
|
||||
{coordinates ? (
|
||||
<span className={styles.pluginText}>
|
||||
{label}
|
||||
<span className={styles.detail} title={coordinates}>
|
||||
{coordinates}
|
||||
</span>
|
||||
</span>
|
||||
) : (
|
||||
label
|
||||
)}
|
||||
{detail && <span className={styles.detail}>{detail}</span>}
|
||||
</span>
|
||||
);
|
||||
@@ -475,6 +488,7 @@ function BuildToolView({ tool }: { tool: BuildTool }) {
|
||||
roots={roots}
|
||||
getKey={(n) => n.key}
|
||||
getLabel={nodeLabel}
|
||||
getTooltip={(n) => (n.kind === "task" ? (n.task.description ?? undefined) : undefined)}
|
||||
getChildren={getChildren}
|
||||
isExpandable={(n) => !!getChildren(n)?.length}
|
||||
expanded={expanded}
|
||||
|
||||
@@ -96,6 +96,18 @@
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.pluginText {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
.pluginText > .label {
|
||||
flex: none;
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
}
|
||||
.profile {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
@@ -99,8 +99,8 @@ export function dependencyLabel(d: MavenDependency): string {
|
||||
return parts.join(":");
|
||||
}
|
||||
|
||||
export function pluginLabel(p: MavenPlugin): string {
|
||||
return `${p.prefix} (${p.groupId}:${p.artifactId}${p.version ? `:${p.version}` : ""})`;
|
||||
export function pluginCoordinates(p: MavenPlugin): string {
|
||||
return `${p.groupId}:${p.artifactId}${p.version ? `:${p.version}` : ""}`;
|
||||
}
|
||||
|
||||
/** Profile choices in different workspace members are independent. */
|
||||
@@ -363,7 +363,7 @@ export function nodeLabel(node: BuildNode): string {
|
||||
case "plugins":
|
||||
return tx("Plugins");
|
||||
case "plugin":
|
||||
return pluginLabel(node.plugin);
|
||||
return `${node.plugin.prefix} (${pluginCoordinates(node.plugin)})`;
|
||||
case "goal":
|
||||
return `${node.plugin.prefix}:${node.goal}`;
|
||||
case "dependencies":
|
||||
|
||||
@@ -159,7 +159,7 @@
|
||||
flex-direction: column;
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--fs-code);
|
||||
line-height: 1.45;
|
||||
line-height: var(--lh-code);
|
||||
}
|
||||
.sourcePreview .sourceText[role="region"] {
|
||||
font: inherit;
|
||||
|
||||
@@ -406,6 +406,8 @@ export function useUsagesHeaderMenu(): MenuItem[] {
|
||||
];
|
||||
}
|
||||
|
||||
const DEFAULT_PREVIEW_LAYOUT = { usages: 50, preview: 50 };
|
||||
|
||||
function UsagesSplit({ preview, children }: { preview: ReactNode; children: ReactNode }) {
|
||||
const show = useUsagesOptions((s) => s.preview);
|
||||
const frame = useRef<HTMLDivElement>(null);
|
||||
@@ -427,12 +429,13 @@ function UsagesSplit({ preview, children }: { preview: ReactNode; children: Reac
|
||||
orientation={stacked ? "vertical" : "horizontal"}
|
||||
id="usages-preview-split"
|
||||
storageKey={stacked ? "openidea.usages.previewSplit.vertical" : "openidea.usages.previewSplit"}
|
||||
defaultLayout={DEFAULT_PREVIEW_LAYOUT}
|
||||
>
|
||||
<SplitPanel id="usages" minSize={stacked ? "30%" : 160} className={styles.panel}>
|
||||
{children}
|
||||
</SplitPanel>
|
||||
<SplitHandle />
|
||||
<SplitPanel id="preview" minSize={stacked ? "30%" : 160} defaultSize="45%" className={styles.panel}>
|
||||
<SplitPanel id="preview" minSize={stacked ? "30%" : 160} className={styles.panel}>
|
||||
{preview}
|
||||
</SplitPanel>
|
||||
</SplitGroup>
|
||||
@@ -455,13 +458,21 @@ function UsagesPreview({ node }: { node: Node | null }) {
|
||||
return (group?.usages ?? []).map((u) => ({ line: u.line, ranges: [[u.col, u.endCol] as const] }));
|
||||
}, [usage, search?.groups]);
|
||||
return (
|
||||
<div className={styles.sourcePreview} style={{ fontFamily, fontSize: settings?.fontSize ?? undefined }}>
|
||||
<div
|
||||
className={styles.sourcePreview}
|
||||
style={{
|
||||
fontFamily,
|
||||
fontSize: settings?.fontSize ?? undefined,
|
||||
lineHeight: settings?.lineHeight != null ? `${settings.lineHeight}px` : undefined,
|
||||
}}
|
||||
>
|
||||
<SourcePreview
|
||||
path={usage?.path ?? null}
|
||||
line={usage?.line ?? 0}
|
||||
highlights={highlights}
|
||||
load={previewText}
|
||||
colorize={previewColors}
|
||||
editorLayout
|
||||
className={styles.sourceText}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -21,7 +21,8 @@ export function reportProblems(): () => void {
|
||||
if (!reset) for (const path of reported.keys()) if (!map.has(path)) files.push({ path, items: [] });
|
||||
if (!files.length && !reset) return;
|
||||
const wasReset = reset;
|
||||
reported = map;
|
||||
// The store updates its map in place; keep our own copy to diff the next flush against.
|
||||
reported = new Map(map);
|
||||
reset = false;
|
||||
void call(commands.mcpReportProblems(wasReset, files)).catch(() => {
|
||||
reset = true;
|
||||
|
||||
@@ -76,6 +76,74 @@ describe("store + decorations", () => {
|
||||
});
|
||||
});
|
||||
|
||||
/** Entries copied by every `new Map(...)` constructed while `run` executes. */
|
||||
function entriesCopied(run: () => void): number {
|
||||
const Original = globalThis.Map;
|
||||
let copied = 0;
|
||||
class Counting<K, V> extends Original<K, V> {
|
||||
constructor(entries?: Iterable<readonly [K, V]> | null) {
|
||||
super(entries);
|
||||
copied += this.size;
|
||||
}
|
||||
}
|
||||
globalThis.Map = Counting as MapConstructor;
|
||||
try {
|
||||
run();
|
||||
} finally {
|
||||
globalThis.Map = Original;
|
||||
}
|
||||
return copied;
|
||||
}
|
||||
|
||||
describe("diagnostics storm", () => {
|
||||
beforeEach(() => clearProblems());
|
||||
const FILES = 2000;
|
||||
const path = (i: number) => `/p/src/File${i}.ts`;
|
||||
|
||||
it("applies an event without copying the files already in the store", () => {
|
||||
// Copying every file's entry per event is FILES^2 / 2 = 2,000,000 entries; the bound is
|
||||
// a few entries per event (the touched file's sources).
|
||||
const copied = entriesCopied(() => {
|
||||
for (let i = 0; i < FILES; i++) applyDiagnosticsEvent(path(i), "lsp", [d(i % 50), d(1, "warning")]);
|
||||
});
|
||||
expect(copied).toBeLessThan(FILES * 4);
|
||||
const { map, raw, counts } = useProblems.getState();
|
||||
expect(map.size).toBe(FILES);
|
||||
expect(raw.size).toBe(FILES);
|
||||
expect(counts).toEqual({ error: FILES, warning: FILES, info: 0, hint: 0 });
|
||||
});
|
||||
|
||||
it("rebuilds the profiled map without copying it per file", () => {
|
||||
for (let i = 0; i < FILES; i++) applyDiagnosticsEvent(path(i), "lsp", [d(i % 50)]);
|
||||
const { raw } = useProblems.getState();
|
||||
let out: ReturnType<typeof profiledProblems> | undefined;
|
||||
const copied = entriesCopied(() => {
|
||||
out = profiledProblems(raw, { "lsp:lsp": { severity: "weakWarning" } });
|
||||
});
|
||||
expect(copied).toBeLessThan(FILES * 4);
|
||||
expect(out!.size).toBe(FILES);
|
||||
});
|
||||
|
||||
it("publishes a new map exactly when the content changed", () => {
|
||||
applyDiagnosticsEvent(path(1), "lsp", [d(1)]);
|
||||
const first = useProblems.getState();
|
||||
applyDiagnosticsEvent(path(1), "other", []); // nothing to clear
|
||||
expect(useProblems.getState()).toBe(first);
|
||||
|
||||
applyDiagnosticsEvent(path(2), "lsp", [d(1)]);
|
||||
const second = useProblems.getState();
|
||||
expect(second.map).not.toBe(first.map);
|
||||
expect(second.raw).not.toBe(first.raw);
|
||||
expect(second.map.get(path(1))).toBe(first.map.get(path(1))); // untouched file keeps its sources
|
||||
|
||||
applyDiagnosticsEvent(path(2), "lsp", []);
|
||||
const third = useProblems.getState();
|
||||
expect(third.map).not.toBe(second.map);
|
||||
expect(third.map.has(path(2))).toBe(false);
|
||||
expect(third.counts).toEqual({ error: 1, warning: 0, info: 0, hint: 0 });
|
||||
});
|
||||
});
|
||||
|
||||
describe("profiledProblems", () => {
|
||||
it("applies the inspection profile per producer", () => {
|
||||
let raw = mergeDiagnostics(new Map(), "/a", "ra", [d(1), d(2, "warning")]);
|
||||
|
||||
@@ -25,16 +25,12 @@ export interface SeverityCounts {
|
||||
hint: number;
|
||||
}
|
||||
|
||||
/** Replaces `source`'s diagnostics for `path`; returns the same map when nothing changed. */
|
||||
export function mergeDiagnostics(
|
||||
map: ProblemsMap,
|
||||
path: string,
|
||||
source: string,
|
||||
items: readonly Diagnostic[],
|
||||
): ProblemsMap {
|
||||
const prev = map.get(path);
|
||||
if (!items.length && !prev?.has(source)) return map;
|
||||
const next = new Map(map);
|
||||
/**
|
||||
* `prev` (one file's sources) with `source`'s diagnostics replaced; undefined when nothing
|
||||
* changes. An empty result means the file has no problems left.
|
||||
*/
|
||||
function replaceSource(prev: FileDiagnostics | undefined, source: string, items: readonly Diagnostic[]) {
|
||||
if (!items.length && !prev?.has(source)) return undefined;
|
||||
const sources = new Map(prev ?? []);
|
||||
if (items.length)
|
||||
sources.set(
|
||||
@@ -42,8 +38,25 @@ export function mergeDiagnostics(
|
||||
items.map((d) => (d.source ? d : { ...d, source })),
|
||||
);
|
||||
else sources.delete(source);
|
||||
if (sources.size) next.set(path, sources);
|
||||
else next.delete(path);
|
||||
return sources;
|
||||
}
|
||||
|
||||
function putSources(map: Map<string, FileDiagnostics>, path: string, sources: FileDiagnostics) {
|
||||
if (sources.size) map.set(path, sources);
|
||||
else map.delete(path);
|
||||
}
|
||||
|
||||
/** Replaces `source`'s diagnostics for `path`; returns the same map when nothing changed. */
|
||||
export function mergeDiagnostics(
|
||||
map: ProblemsMap,
|
||||
path: string,
|
||||
source: string,
|
||||
items: readonly Diagnostic[],
|
||||
): ProblemsMap {
|
||||
const sources = replaceSource(map.get(path), source, items);
|
||||
if (!sources) return map;
|
||||
const next = new Map(map);
|
||||
putSources(next, path, sources);
|
||||
return next;
|
||||
}
|
||||
|
||||
@@ -151,28 +164,69 @@ export function worstSeverity(diags: Iterable<Diagnostic>): Severity | null {
|
||||
}
|
||||
|
||||
/** `raw` under the inspection profile: disabled inspections dropped, severities remapped. */
|
||||
export function profiledProblems(raw: ProblemsMap, profile: ProfileOverrides): ProblemsMap {
|
||||
let out: ProblemsMap = new Map();
|
||||
export function profiledProblems(raw: ProblemsMap, profile: ProfileOverrides): Map<string, FileDiagnostics> {
|
||||
const out = new Map<string, FileDiagnostics>();
|
||||
for (const [path, sources] of raw) {
|
||||
for (const [source, items] of sources) {
|
||||
out = mergeDiagnostics(out, path, source, applyProfile(profile, source, items));
|
||||
const next = replaceSource(out.get(path), source, applyProfile(profile, source, items));
|
||||
if (next) putSources(out, path, next);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* A problems map the store updates in place, so applying an event costs the size of the event,
|
||||
* not the number of files. Each change publishes a new facade object: subscribers still see a new
|
||||
* `map`/`raw` identity exactly when the content changed, but an older facade reads the current
|
||||
* content, so keep a copy (`new Map(map)`) to compare against later, never the facade itself.
|
||||
*/
|
||||
class ProblemsSnapshot implements ProblemsMap {
|
||||
constructor(readonly data: Map<string, FileDiagnostics>) {}
|
||||
get size() {
|
||||
return this.data.size;
|
||||
}
|
||||
get(path: string) {
|
||||
return this.data.get(path);
|
||||
}
|
||||
has(path: string) {
|
||||
return this.data.has(path);
|
||||
}
|
||||
keys() {
|
||||
return this.data.keys();
|
||||
}
|
||||
values() {
|
||||
return this.data.values();
|
||||
}
|
||||
entries() {
|
||||
return this.data.entries();
|
||||
}
|
||||
forEach(fn: (value: FileDiagnostics, path: string, map: ProblemsMap) => void) {
|
||||
for (const [path, sources] of this.data) fn(sources, path, this);
|
||||
}
|
||||
[Symbol.iterator]() {
|
||||
return this.data[Symbol.iterator]();
|
||||
}
|
||||
}
|
||||
|
||||
interface ProblemsState {
|
||||
/** As reported, before the inspection profile. */
|
||||
raw: ProblemsMap;
|
||||
raw: ProblemsSnapshot;
|
||||
/** What the views show. */
|
||||
map: ProblemsMap;
|
||||
map: ProblemsSnapshot;
|
||||
/** `projectCounts(map)`, kept up to date per event. */
|
||||
counts: SeverityCounts;
|
||||
}
|
||||
|
||||
const NO_COUNTS: SeverityCounts = { error: 0, warning: 0, info: 0, hint: 0 };
|
||||
|
||||
export const useProblems = create<ProblemsState>(() => ({ raw: new Map(), map: new Map(), counts: NO_COUNTS }));
|
||||
const emptyProblems = (): ProblemsState => ({
|
||||
raw: new ProblemsSnapshot(new Map()),
|
||||
map: new ProblemsSnapshot(new Map()),
|
||||
counts: NO_COUNTS,
|
||||
});
|
||||
|
||||
export const useProblems = create<ProblemsState>(emptyProblems);
|
||||
|
||||
function recount(counts: SeverityCounts, removed: readonly Diagnostic[], added: readonly Diagnostic[]) {
|
||||
const c = { ...counts };
|
||||
@@ -181,19 +235,27 @@ function recount(counts: SeverityCounts, removed: readonly Diagnostic[], added:
|
||||
return c;
|
||||
}
|
||||
|
||||
/** Replaces `source`'s diagnostics for `path` in `snapshot`'s data; the new facade, or null when nothing changed. */
|
||||
function applyTo(snapshot: ProblemsSnapshot, path: string, source: string, items: readonly Diagnostic[]) {
|
||||
const sources = replaceSource(snapshot.data.get(path), source, items);
|
||||
if (!sources) return null;
|
||||
putSources(snapshot.data, path, sources);
|
||||
return new ProblemsSnapshot(snapshot.data);
|
||||
}
|
||||
|
||||
export function applyDiagnosticsEvent(path: string, source: string, items: readonly Diagnostic[]) {
|
||||
useProblems.setState((s) => {
|
||||
const raw = mergeDiagnostics(s.raw, path, source, items);
|
||||
if (raw === s.raw) return s;
|
||||
const map = mergeDiagnostics(s.map, path, source, applyProfile(inspectionProfile(), source, items));
|
||||
if (map === s.map) return { raw };
|
||||
const before = s.map.get(path)?.get(source) ?? [];
|
||||
const raw = applyTo(s.raw, path, source, items);
|
||||
if (!raw) return s;
|
||||
const map = applyTo(s.map, path, source, applyProfile(inspectionProfile(), source, items));
|
||||
if (!map) return { raw };
|
||||
return { raw, map, counts: recount(s.counts, before, map.get(path)?.get(source) ?? []) };
|
||||
});
|
||||
}
|
||||
|
||||
export function clearProblems() {
|
||||
useProblems.setState({ raw: new Map(), map: new Map(), counts: NO_COUNTS });
|
||||
useProblems.setState(emptyProblems());
|
||||
}
|
||||
|
||||
export function installProblemsEvents(): () => void {
|
||||
@@ -202,7 +264,7 @@ export function installProblemsEvents(): () => void {
|
||||
const offLocal = onLocalDiagnostics(applyDiagnosticsEvent);
|
||||
const offProfile = subscribeInspectionProfile(() =>
|
||||
useProblems.setState((s) => {
|
||||
const map = profiledProblems(s.raw, inspectionProfile());
|
||||
const map = new ProblemsSnapshot(profiledProblems(s.raw, inspectionProfile()));
|
||||
return { map, counts: projectCounts(map) };
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -241,7 +241,8 @@ describe("MemoryView", () => {
|
||||
expect(screen.getByRole("button", { name: "刷新内存视图" }).getAttribute("data-tooltip")).toBe("刷新内存视图");
|
||||
const filter = screen.getByRole("textbox", { name: "筛选类" });
|
||||
expect(filter.getAttribute("placeholder")).toBe("筛选类");
|
||||
expect(screen.getByRole("checkbox", { name: "仅显示有变化的" })).toBeTruthy();
|
||||
fireEvent.click(screen.getByRole("button", { name: "视图选项" }));
|
||||
expect(screen.getByRole("menuitemcheckbox", { name: "仅显示有变化的" })).toBeInTheDocument();
|
||||
} finally {
|
||||
await setLocale("en");
|
||||
}
|
||||
@@ -299,10 +300,15 @@ describe("MemoryView", () => {
|
||||
expect(screen.getByText("Cache$Entry")).toBeTruthy();
|
||||
|
||||
fireEvent.change(screen.getByRole("textbox", { name: "Filter classes" }), { target: { value: "" } });
|
||||
fireEvent.click(screen.getByRole("checkbox", { name: "Changed only" }));
|
||||
const options = screen.getByRole("button", { name: "View Options" });
|
||||
fireEvent.click(options);
|
||||
fireEvent.click(screen.getByRole("menuitemcheckbox", { name: "Changed only", checked: false }));
|
||||
expect(screen.getByText("Heap$Live")).toBeTruthy();
|
||||
expect(screen.queryByText("Cache$Entry")).toBeNull();
|
||||
expect(screen.queryByText("Dup")).toBeNull();
|
||||
expect(options).toHaveAttribute("aria-pressed", "true");
|
||||
fireEvent.click(options);
|
||||
expect(screen.getByRole("menuitemcheckbox", { name: "Changed only", checked: true })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("sorts by the clicked column and reports it with aria-sort", async () => {
|
||||
|
||||
@@ -6,8 +6,13 @@ import { sessionTabs } from "../ui/sessionTabs";
|
||||
const node = { ...browserLaunch("dev", "http://localhost:5173", "chrome", "/p"), extraJson: '{"type":"pwa-node"}' };
|
||||
const page = browserLaunch("localhost:5173", "http://localhost:5173", "chrome", "/p");
|
||||
|
||||
function session(id: number, parent: number | null, launch: DebugSession["launch"] = null): DebugSession {
|
||||
return { id, name: `s${id}`, parent, launch } as DebugSession;
|
||||
function session(
|
||||
id: number,
|
||||
parent: number | null,
|
||||
launch: DebugSession["launch"] = null,
|
||||
tabOrder = id,
|
||||
): DebugSession {
|
||||
return { id, name: `s${id}`, parent, launch, tabOrder } as DebugSession;
|
||||
}
|
||||
|
||||
const shown = (sessions: DebugSession[]) => sessionTabs(sessions).map((t) => [t.session.id, t.owner, t.child]);
|
||||
@@ -35,4 +40,27 @@ describe("debug session tabs", () => {
|
||||
[6, 6, true],
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps a reused slot instead of ordering tabs by session id", () => {
|
||||
expect(shown([session(2, null, null, 2), session(9, null, null, 1), session(5, null, null, 3)])).toEqual([
|
||||
[9, 9, false],
|
||||
[2, 2, false],
|
||||
[5, 5, false],
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps a child next to its parent when the parent took an older slot", () => {
|
||||
expect(shown([session(2, null, null, 2), session(3, null, null, 1), session(4, 3, null, 3)])).toEqual([
|
||||
[3, 3, false],
|
||||
[4, 4, true],
|
||||
[2, 2, false],
|
||||
]);
|
||||
});
|
||||
|
||||
it("puts a browser page in the slot of the launch it stands for", () => {
|
||||
expect(shown([session(21, 20, null, 20), session(30, null, null, 1), session(20, null, page, 2)])).toEqual([
|
||||
[30, 30, false],
|
||||
[21, 20, false],
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -6,8 +6,16 @@ import {
|
||||
removeAllBreakpoints,
|
||||
useBreakpoints,
|
||||
} from "../breakpoints/store";
|
||||
import { handleDebugEvent, pinSession, rerunSession, startPreparedSession, startSession, useDebug } from "../state";
|
||||
import type { LaunchConfig } from "@/platform/ipc";
|
||||
import {
|
||||
handleDebugEvent,
|
||||
pinSession,
|
||||
rerunSession,
|
||||
startPreparedSession,
|
||||
startSession,
|
||||
tabOrderOf,
|
||||
useDebug,
|
||||
} from "../state";
|
||||
import type { LaunchConfig, RunConfig } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import {
|
||||
provideNotificationService,
|
||||
@@ -18,6 +26,7 @@ import {
|
||||
const ipc = vi.hoisted(() => ({
|
||||
debugSetBreakpoints: vi.fn(),
|
||||
debugStart: vi.fn(async () => ({ status: "ok", data: 42 })),
|
||||
debugStop: vi.fn(async () => ({ status: "ok", data: null })),
|
||||
debugCapabilities: vi.fn(async () => ({ status: "ok", data: {} })),
|
||||
debugExceptionFilters: vi.fn(async () => ({ status: "ok", data: [] })),
|
||||
debugThreads: vi.fn(async () => ({ status: "ok", data: [] })),
|
||||
@@ -37,6 +46,12 @@ const config = (request: string): LaunchConfig => ({
|
||||
env: {},
|
||||
extraJson: null,
|
||||
});
|
||||
const runConfig = (id: string): RunConfig =>
|
||||
({ id, name: "Same", kind: "shell", command: "true", args: [], cwd: null, env: {} }) as unknown as RunConfig;
|
||||
const tabIds = () =>
|
||||
Object.values(useDebug.getState().sessions)
|
||||
.sort((a, b) => tabOrderOf(a) - tabOrderOf(b) || a.id - b.id)
|
||||
.map((s) => s.id);
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
vi.clearAllMocks();
|
||||
@@ -262,10 +277,7 @@ it("replaces only the finished tab of the same name; other finished tabs stay",
|
||||
handleDebugEvent(2, { kind: "terminated" });
|
||||
ipc.debugStart.mockResolvedValueOnce({ status: "ok", data: 3 });
|
||||
await startSession({ ...config("launch"), name: "Server" });
|
||||
expect(Object.values(useDebug.getState().sessions).map((s) => [s.name, s.status])).toEqual([
|
||||
["Client", "terminated"],
|
||||
["Server", "running"],
|
||||
]);
|
||||
expect(tabIds().map((id) => useDebug.getState().sessions[id]!.name)).toEqual(["Server", "Client"]);
|
||||
|
||||
ipc.debugStart.mockResolvedValueOnce({ status: "ok", data: 4 });
|
||||
const started = startPreparedSession({ id: "other", name: "Other" } as never, async () => ({
|
||||
@@ -273,9 +285,9 @@ it("replaces only the finished tab of the same name; other finished tabs stay",
|
||||
name: "Other",
|
||||
}));
|
||||
// No finished tab named "Other": the first finished one (Client) gives way.
|
||||
expect(Object.values(useDebug.getState().sessions).map((s) => s.name)).toEqual(["Server", "Other"]);
|
||||
expect(tabIds().map((id) => useDebug.getState().sessions[id]!.name)).toEqual(["Server", "Other"]);
|
||||
await started;
|
||||
expect(Object.values(useDebug.getState().sessions).map((s) => s.name)).toEqual(["Server", "Other"]);
|
||||
expect(tabIds().map((id) => useDebug.getState().sessions[id]!.name)).toEqual(["Server", "Other"]);
|
||||
});
|
||||
|
||||
it("keeps a pinned finished tab; Rerun on it takes its place and keeps it pinned", async () => {
|
||||
@@ -285,7 +297,11 @@ it("keeps a pinned finished tab; Rerun on it takes its place and keeps it pinned
|
||||
handleDebugEvent(1, { kind: "terminated" });
|
||||
ipc.debugStart.mockResolvedValueOnce({ status: "ok", data: 2 });
|
||||
await startSession({ ...config("launch"), name: "Server" });
|
||||
const tabs = () => Object.values(useDebug.getState().sessions).map((s) => [s.id, s.status, !!s.pinned]);
|
||||
const tabs = () =>
|
||||
tabIds().map((id) => {
|
||||
const s = useDebug.getState().sessions[id]!;
|
||||
return [s.id, s.status, !!s.pinned];
|
||||
});
|
||||
expect(tabs()).toEqual([
|
||||
[1, "terminated", true],
|
||||
[2, "running", false],
|
||||
@@ -295,7 +311,57 @@ it("keeps a pinned finished tab; Rerun on it takes its place and keeps it pinned
|
||||
ipc.debugStart.mockResolvedValueOnce({ status: "ok", data: 3 });
|
||||
await rerunSession(1);
|
||||
expect(tabs()).toEqual([
|
||||
[2, "terminated", false],
|
||||
[3, "running", true],
|
||||
[2, "terminated", false],
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps the reused slot while a prepared start builds", async () => {
|
||||
ipc.debugStart.mockResolvedValueOnce({ status: "ok", data: 1 }).mockResolvedValueOnce({ status: "ok", data: 2 });
|
||||
await startSession({ ...config("launch"), name: "Server" });
|
||||
await startSession({ ...config("launch"), name: "Client" });
|
||||
handleDebugEvent(2, { kind: "terminated" });
|
||||
|
||||
let finishBuild!: () => void;
|
||||
const build = new Promise<void>((resolve) => (finishBuild = resolve));
|
||||
ipc.debugStart.mockResolvedValueOnce({ status: "ok", data: 3 });
|
||||
const started = startPreparedSession({ id: "client", name: "Client" } as never, async () => {
|
||||
await build;
|
||||
return { ...config("launch"), name: "Client" };
|
||||
});
|
||||
expect(tabIds().map((id) => useDebug.getState().sessions[id]!.name)).toEqual(["Server", "Client"]);
|
||||
|
||||
finishBuild();
|
||||
await expect(started).resolves.toBe(3);
|
||||
expect(tabIds()).toEqual([1, 3]);
|
||||
});
|
||||
|
||||
it("keeps a live tab in place when Rerun stops and replaces it", async () => {
|
||||
ipc.debugStart
|
||||
.mockResolvedValueOnce({ status: "ok", data: 1 })
|
||||
.mockResolvedValueOnce({ status: "ok", data: 2 })
|
||||
.mockResolvedValueOnce({ status: "ok", data: 3 })
|
||||
.mockResolvedValueOnce({ status: "ok", data: 4 });
|
||||
await startSession({ ...config("launch"), name: "First" });
|
||||
await startSession({ ...config("launch"), name: "Second" });
|
||||
await startSession({ ...config("launch"), name: "Third" });
|
||||
|
||||
await rerunSession(2);
|
||||
expect(tabIds()).toEqual([1, 4, 3]);
|
||||
});
|
||||
|
||||
it("prefers the same configuration over another selected tab with the same name", async () => {
|
||||
ipc.debugStart
|
||||
.mockResolvedValueOnce({ status: "ok", data: 1 })
|
||||
.mockResolvedValueOnce({ status: "ok", data: 2 })
|
||||
.mockResolvedValueOnce({ status: "ok", data: 3 });
|
||||
await startSession({ ...config("launch"), name: "Same" }, { runConfig: runConfig("a") });
|
||||
await startSession({ ...config("launch"), name: "Same" }, { runConfig: runConfig("b") });
|
||||
handleDebugEvent(1, { kind: "terminated" });
|
||||
handleDebugEvent(2, { kind: "terminated" });
|
||||
useDebug.setState({ active: 1 });
|
||||
|
||||
await startSession({ ...config("launch"), name: "Same" }, { runConfig: runConfig("b") });
|
||||
expect(tabIds()).toEqual([1, 3]);
|
||||
expect(useDebug.getState().sessions[3]?.runConfig?.id).toBe("b");
|
||||
});
|
||||
@@ -18,8 +18,8 @@
|
||||
}
|
||||
|
||||
.filter {
|
||||
flex: 0 1 240px;
|
||||
min-width: 80px;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.banner,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/** Memory tab of the Debug tool window: live instance counts per class of the debugged JVM, and heap capture. */
|
||||
import { useEffect, useMemo } from "react";
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import clsx from "clsx";
|
||||
import { Checkbox, Icon, IconButton, Input, List, T } from "@/ui";
|
||||
import { Icon, IconButton, List, Menu, SearchField, T } from "@/ui";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { useTx } from "@/platform/i18n";
|
||||
import type { JvmClassRow, JvmMemorySnapshot } from "@/platform/ipc";
|
||||
@@ -112,6 +112,8 @@ export function MemoryView({ session }: { session: DebugSession }) {
|
||||
const id = session.id;
|
||||
const entry = useMemory((s) => s.bySession[id]);
|
||||
const query = entry?.query ?? DEFAULT_QUERY;
|
||||
const optionsButton = useRef<HTMLButtonElement>(null);
|
||||
const [optionsOpen, setOptionsOpen] = useState(false);
|
||||
const result = entry?.result ?? null;
|
||||
const snapshot = entry?.snapshot ?? null;
|
||||
const source = snapshot?.source ?? "histogram";
|
||||
@@ -161,17 +163,37 @@ export function MemoryView({ session }: { session: DebugSession }) {
|
||||
disabled={entry?.loading || !canRefresh}
|
||||
/>
|
||||
<HeapCaptureButton session={session} />
|
||||
<Input
|
||||
<SearchField
|
||||
className={styles.filter}
|
||||
value={query.filter}
|
||||
onChange={(e) => setMemoryQuery(id, { filter: e.target.value })}
|
||||
onChange={(filter) => setMemoryQuery(id, { filter })}
|
||||
placeholder="Filter classes"
|
||||
aria-label="Filter classes"
|
||||
/>
|
||||
<Checkbox
|
||||
checked={query.changedOnly}
|
||||
onChange={(changedOnly) => setMemoryQuery(id, { changedOnly })}
|
||||
label="Changed only"
|
||||
<IconButton
|
||||
ref={optionsButton}
|
||||
icon="settings"
|
||||
title="View Options"
|
||||
size="small"
|
||||
iconSize={16}
|
||||
pressed={query.changedOnly}
|
||||
aria-haspopup="menu"
|
||||
aria-expanded={optionsOpen}
|
||||
onClick={() => setOptionsOpen(!optionsOpen)}
|
||||
/>
|
||||
<Menu
|
||||
open={optionsOpen}
|
||||
onClose={() => setOptionsOpen(false)}
|
||||
anchor={optionsButton}
|
||||
placement="bottom-end"
|
||||
aria-label="View Options"
|
||||
items={[
|
||||
{
|
||||
label: "Changed only",
|
||||
checked: query.changedOnly,
|
||||
run: () => setMemoryQuery(id, { changedOnly: !query.changedOnly }),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
{backend && (
|
||||
|
||||
@@ -76,6 +76,8 @@ export interface DebugSession {
|
||||
programInput?: boolean;
|
||||
/** Process the session is attached to (a Run tab's build tool); stopped with the session. */
|
||||
process: RunId | null;
|
||||
/** Stable Debug-tab slot; a restarted session inherits it even though its backend id changes. */
|
||||
tabOrder?: number;
|
||||
/** Pinned tab (root sessions): once finished, a later session opens a new tab instead of taking its place. */
|
||||
pinned?: boolean;
|
||||
/** Started in place from the Services tool window (root sessions): its stops show it there, not in the Debug window. */
|
||||
@@ -155,6 +157,35 @@ export const useDebug = create<DebugState>(() => ({
|
||||
variablesEpoch: 0,
|
||||
}));
|
||||
|
||||
let tabOrderSeq = 0;
|
||||
|
||||
/** Allocates a Debug-tab slot that is independent of the backend's session ids. */
|
||||
function allocateTabOrder() {
|
||||
return ++tabOrderSeq;
|
||||
}
|
||||
|
||||
/** Visible order key; test fixtures without a slot retain their former id order. */
|
||||
export function tabOrderOf(s: Pick<DebugSession, "id" | "tabOrder">): number {
|
||||
return s.tabOrder ?? s.id;
|
||||
}
|
||||
|
||||
/** Sessions as their Debug tabs show: by their root's slot, so children stay next to their parent. */
|
||||
export function inTabOrder<T extends Pick<DebugSession, "id" | "parent" | "tabOrder">>(sessions: readonly T[]): T[] {
|
||||
const byId = new Map(sessions.map((s) => [s.id, s]));
|
||||
const root = (s: T) => {
|
||||
let cur = s;
|
||||
for (let p = byId.get(cur.parent!); cur.parent != null && p; p = byId.get(cur.parent!)) cur = p;
|
||||
return cur;
|
||||
};
|
||||
return [...sessions].sort(
|
||||
(a, b) => tabOrderOf(root(a)) - tabOrderOf(root(b)) || tabOrderOf(a) - tabOrderOf(b) || a.id - b.id,
|
||||
);
|
||||
}
|
||||
|
||||
function sessionsInTabOrder(sessions: Record<number, DebugSession>): DebugSession[] {
|
||||
return inTabOrder(Object.values(sessions));
|
||||
}
|
||||
|
||||
/** Execution point of the selected frame, plus the frame's locals for inline values. */
|
||||
interface ExecutionPoint {
|
||||
path: string | null;
|
||||
@@ -248,7 +279,7 @@ function patch(id: DebugSessionId, p: Partial<DebugSession>) {
|
||||
publishContext();
|
||||
}
|
||||
|
||||
function blank(id: DebugSessionId, p: Partial<DebugSession> = {}): DebugSession {
|
||||
function blank(id: DebugSessionId, { tabOrder = allocateTabOrder(), ...p }: Partial<DebugSession> = {}): DebugSession {
|
||||
return {
|
||||
id,
|
||||
name: "Debug",
|
||||
@@ -257,6 +288,7 @@ function blank(id: DebugSessionId, p: Partial<DebugSession> = {}): DebugSession
|
||||
parent: null,
|
||||
launch: null,
|
||||
process: null,
|
||||
tabOrder,
|
||||
status: "starting",
|
||||
stoppedThread: null,
|
||||
stopReason: null,
|
||||
@@ -349,27 +381,40 @@ function settleStart(id: DebugSessionId | null, discard = false) {
|
||||
/** The session being rerun: its tab is the one the new session takes, pinned or not. */
|
||||
let rerunOf: DebugSessionId | null = null;
|
||||
|
||||
interface ReplacedTab {
|
||||
pinned?: boolean;
|
||||
tabOrder?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* As IDEA reuses run content: a new session takes the place of one finished tab (with its
|
||||
* children) that isn't pinned, preferring one named like it, then the selected one; other
|
||||
* finished tabs stay. Returns whether the new tab is pinned: as the tab it replaced on a
|
||||
* rerun, else per the settings.
|
||||
* children) that isn't pinned, preferring the same configuration id, then its display name,
|
||||
* then the selected one; other finished tabs stay. The returned slot lets the new backend
|
||||
* session keep the tab where the replaced one was.
|
||||
*/
|
||||
function replaceFinished(name: string): boolean | undefined {
|
||||
function replaceFinished(name: string, configId?: string): ReplacedTab {
|
||||
const { sessions, active } = useDebug.getState();
|
||||
const own = rerunOf != null ? sessions[rerunOf] : undefined;
|
||||
rerunOf = null;
|
||||
if (own && !isLive(own)) {
|
||||
// Rerun's Stop waits for the adapter, even if this window has not handled its terminated event yet.
|
||||
if (own) {
|
||||
const tabOrder = tabOrderOf(own);
|
||||
removeSession(own.id);
|
||||
return own.pinned;
|
||||
return { pinned: own.pinned, tabOrder };
|
||||
}
|
||||
const finished = Object.values(sessions).filter((s) => s.parent == null && !isLive(s) && !s.pinned);
|
||||
const finished = sessionsInTabOrder(sessions).filter((s) => s.parent == null && !isLive(s) && !s.pinned);
|
||||
const selected = active != null ? sessions[active] : undefined;
|
||||
const ordered =
|
||||
selected && finished.includes(selected) ? [selected, ...finished.filter((s) => s !== selected)] : finished;
|
||||
const reused = ordered.find((s) => s.name === name) ?? ordered[0];
|
||||
if (reused) removeSession(reused.id);
|
||||
return workflowSettings().run.pinTabs || undefined;
|
||||
const reused =
|
||||
(configId == null ? undefined : ordered.find((s) => s.runConfig?.id === configId)) ??
|
||||
ordered.find((s) => s.name === name) ??
|
||||
ordered[0];
|
||||
const pinned = workflowSettings().run.pinTabs || undefined;
|
||||
if (!reused) return { pinned };
|
||||
const tabOrder = tabOrderOf(reused);
|
||||
removeSession(reused.id);
|
||||
return { pinned, tabOrder };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -388,7 +433,7 @@ export function justDetached(process: RunId | null | undefined): boolean {
|
||||
|
||||
export function publishContext() {
|
||||
const s = activeSession();
|
||||
const retained = Object.values(useDebug.getState().sessions);
|
||||
const retained = sessionsInTabOrder(useDebug.getState().sessions);
|
||||
useDebugRunSessions.setState({
|
||||
serviceSessions: retained.flatMap((session) => {
|
||||
if (session.parent != null || !session.runConfig) return [];
|
||||
@@ -414,7 +459,7 @@ export function publishContext() {
|
||||
},
|
||||
];
|
||||
}),
|
||||
sessions: Object.values(useDebug.getState().sessions)
|
||||
sessions: retained
|
||||
.filter((session) => session.parent == null && isLive(session))
|
||||
.map((session) => {
|
||||
const paused = Object.values(useDebug.getState().sessions).find(
|
||||
@@ -747,7 +792,7 @@ export async function startPreparedSession(
|
||||
const controller = new AbortController();
|
||||
preparations.set(id, controller);
|
||||
// The new tab takes the place of a finished one while its build runs, not once the adapter starts.
|
||||
const pinned = replaceFinished(config.name);
|
||||
const reused = replaceFinished(config.name, config.id);
|
||||
useDebug.setState((s) => ({
|
||||
sessions: {
|
||||
...s.sessions,
|
||||
@@ -755,7 +800,8 @@ export async function startPreparedSession(
|
||||
name: config.name,
|
||||
adapter: config.debugAdapter ?? "",
|
||||
runConfig: config,
|
||||
pinned,
|
||||
pinned: reused.pinned,
|
||||
...(reused.tabOrder == null ? {} : { tabOrder: reused.tabOrder }),
|
||||
inPlace: options.show === false,
|
||||
}),
|
||||
},
|
||||
@@ -810,7 +856,7 @@ export async function startSession(
|
||||
// Attaching to a JVM that may be gone: the finished session stays until the attach succeeds.
|
||||
const afterDetach = justDetached(options.process);
|
||||
const previousActive = useDebug.getState().active;
|
||||
let pinned = !afterDetach && !options.preparation ? replaceFinished(launch.name) : undefined;
|
||||
let replaced = !afterDetach && !options.preparation ? replaceFinished(launch.name, options.runConfig?.id) : undefined;
|
||||
try {
|
||||
if (options.show !== false && workflowSettings().run.showOnStart) toolWindowService().show("debug");
|
||||
} catch {
|
||||
@@ -825,7 +871,7 @@ export async function startSession(
|
||||
const id = await call(commands.debugStart(launch));
|
||||
console.info("Debug adapter started", { name: launch.name, ms: performance.now() - adapterStarted });
|
||||
owned.add(id);
|
||||
if (afterDetach && !options.preparation) pinned = replaceFinished(launch.name);
|
||||
if (afterDetach && !options.preparation) replaced = replaceFinished(launch.name, options.runConfig?.id);
|
||||
if (options.preparation?.signal.aborted) {
|
||||
await call(commands.debugStop(id)).catch(() => undefined);
|
||||
settleStart(id);
|
||||
@@ -857,7 +903,8 @@ export async function startSession(
|
||||
adapter: cur.adapter || launch.adapter,
|
||||
launch: options.rerunnable === false ? null : launch,
|
||||
process: options.process ?? null,
|
||||
pinned: preparation ? preparation.pinned : pinned,
|
||||
pinned: preparation ? preparation.pinned : replaced?.pinned,
|
||||
tabOrder: preparation?.tabOrder ?? replaced?.tabOrder ?? cur.tabOrder ?? allocateTabOrder(),
|
||||
inPlace: options.show === false,
|
||||
status: cur.status === "starting" ? "running" : cur.status,
|
||||
},
|
||||
@@ -989,16 +1036,16 @@ export function removeSession(id: DebugSessionId) {
|
||||
const gone = new Set<DebugSessionId>([id]);
|
||||
for (let added = true; added;) {
|
||||
added = false;
|
||||
for (const s of Object.values(st.sessions))
|
||||
for (const s of sessionsInTabOrder(st.sessions))
|
||||
if (s.parent != null && gone.has(s.parent) && !gone.has(s.id)) {
|
||||
gone.add(s.id);
|
||||
added = true;
|
||||
}
|
||||
}
|
||||
|
||||
const order = Object.values(st.sessions).map((s) => s.id);
|
||||
const order = sessionsInTabOrder(st.sessions).map((s) => s.id);
|
||||
const sessions: Record<number, DebugSession> = {};
|
||||
for (const s of Object.values(st.sessions)) if (!gone.has(s.id)) sessions[s.id] = s;
|
||||
for (const s of sessionsInTabOrder(st.sessions)) if (!gone.has(s.id)) sessions[s.id] = s;
|
||||
const console = { ...st.console };
|
||||
for (const goneId of gone) delete console[goneId];
|
||||
const at = order.indexOf(id);
|
||||
@@ -1090,7 +1137,7 @@ function markTerminated(id: DebugSessionId) {
|
||||
const st = useDebug.getState();
|
||||
if (st.active === id) {
|
||||
// Prefer another live session (e.g. the parent of a finished child).
|
||||
const other = Object.values(st.sessions).find(isLive);
|
||||
const other = sessionsInTabOrder(st.sessions).find(isLive);
|
||||
if (other) useDebug.setState({ active: other.id });
|
||||
}
|
||||
if (!Object.values(useDebug.getState().sessions).some(isLive)) {
|
||||
|
||||
@@ -12,11 +12,6 @@ export function isTableType(typeName: string | null | undefined): boolean {
|
||||
return !!typeName && TABLE_TYPES.has(typeName);
|
||||
}
|
||||
|
||||
/** Numbers are right-aligned, as in the database grid. */
|
||||
export function isNumericDtype(dtype: string | undefined): boolean {
|
||||
return !!dtype && /^(u?int|float|complex|Int|UInt|Float)\d*$/.test(dtype);
|
||||
}
|
||||
|
||||
export const ROW_PAGE = 100;
|
||||
export const COLUMN_PAGE = 30;
|
||||
|
||||
|
||||
@@ -1,39 +1,35 @@
|
||||
.dialog {
|
||||
height: clamp(320px, 60vh, 760px);
|
||||
height: 500px;
|
||||
}
|
||||
|
||||
/* The table scrolls under a fixed bar, not the whole dialog body. */
|
||||
/* Scroll only the grid between the toolbar and the expression field. */
|
||||
.content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
padding: var(--space-2) var(--space-3) 0;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.bar {
|
||||
flex: none;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-2);
|
||||
padding-bottom: var(--space-2);
|
||||
justify-content: space-between;
|
||||
gap: var(--space-1) var(--space-2);
|
||||
}
|
||||
|
||||
.expression {
|
||||
flex: 1 1 200px;
|
||||
min-width: 0;
|
||||
height: var(--h-list-row);
|
||||
padding: 0 6px;
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--fs-ui);
|
||||
color: var(--fg);
|
||||
background: var(--bg-input);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-small);
|
||||
flex: none;
|
||||
}
|
||||
|
||||
.expression:focus {
|
||||
outline: none;
|
||||
border-color: var(--focus-ring);
|
||||
.pagers {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-1) var(--space-2);
|
||||
}
|
||||
|
||||
.summary,
|
||||
@@ -59,7 +55,8 @@
|
||||
.table {
|
||||
border-collapse: separate;
|
||||
border-spacing: 0;
|
||||
font-family: var(--font-mono);
|
||||
min-width: 100%;
|
||||
font-family: var(--font-ui);
|
||||
font-size: var(--fs-ui);
|
||||
color: var(--fg);
|
||||
}
|
||||
@@ -77,7 +74,7 @@
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 1;
|
||||
text-align: left;
|
||||
text-align: center;
|
||||
font-weight: normal;
|
||||
color: var(--fg-secondary);
|
||||
background: var(--bg-island);
|
||||
@@ -86,7 +83,8 @@
|
||||
.table .index {
|
||||
position: sticky;
|
||||
left: 0;
|
||||
text-align: right;
|
||||
text-align: center;
|
||||
font-variant-numeric: tabular-nums;
|
||||
font-weight: normal;
|
||||
color: var(--fg-secondary);
|
||||
background: var(--bg-island);
|
||||
@@ -100,16 +98,22 @@
|
||||
background: var(--bg-hover);
|
||||
}
|
||||
|
||||
.numeric {
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.dtype {
|
||||
margin-left: var(--space-1);
|
||||
color: var(--fg-subtle);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
|
||||
.message {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
padding: var(--space-3) 0;
|
||||
color: var(--fg-secondary);
|
||||
}
|
||||
|
||||
.error {
|
||||
max-height: 5em;
|
||||
overflow: auto;
|
||||
overflow-wrap: anywhere;
|
||||
color: var(--danger);
|
||||
}
|
||||
@@ -1,19 +1,10 @@
|
||||
/** View as Table: a DataFrame / Series / ndarray of the paused frame, one page of rows and columns at a time. */
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import clsx from "clsx";
|
||||
import type { DebugSessionId } from "@/platform/ipc";
|
||||
import { Dialog, IconButton } from "@/ui";
|
||||
import { Dialog, IconButton, Input } from "@/ui";
|
||||
import { formatMessage, tx } from "@/platform/i18n";
|
||||
import { evaluate, useDebug } from "../state";
|
||||
import {
|
||||
COLUMN_PAGE,
|
||||
ROW_PAGE,
|
||||
clampWindow,
|
||||
isNumericDtype,
|
||||
parseTableResult,
|
||||
tableExpression,
|
||||
type TableResult,
|
||||
} from "../tableView";
|
||||
import { COLUMN_PAGE, ROW_PAGE, clampWindow, parseTableResult, tableExpression, type TableResult } from "../tableView";
|
||||
import styles from "./TableViewDialog.module.css";
|
||||
|
||||
export function TableViewDialog({
|
||||
@@ -63,7 +54,7 @@ export function TableViewDialog({
|
||||
};
|
||||
}, [expression, win, session, stops, frame, paused]);
|
||||
|
||||
const page = result && "page" in result ? result.page : null;
|
||||
const page = paused && result && "page" in result ? result.page : null;
|
||||
const error = !paused
|
||||
? tx("Values are available while the program is paused")
|
||||
: result && "error" in result
|
||||
@@ -114,54 +105,37 @@ export function TableViewDialog({
|
||||
open
|
||||
onClose={onClose}
|
||||
// An element, not a string: Dialog would translate a variable named like a catalog text ("tasks").
|
||||
title={<span>{initial}</span>}
|
||||
width="clamp(520px, 70vw, 1100px)"
|
||||
title={<span>{expression}</span>}
|
||||
width={700}
|
||||
minWidth={420}
|
||||
minHeight={260}
|
||||
resizable="both"
|
||||
aria-label={formatMessage(tx("Table view of {label}"), { label: initial })}
|
||||
aria-label={formatMessage(tx("Table view of {label}"), { label: expression })}
|
||||
buttons={[{ label: "Close", role: "cancel" }]}
|
||||
className={styles.dialog}
|
||||
>
|
||||
<div className={styles.content}>
|
||||
<div className={styles.bar}>
|
||||
<input
|
||||
className={styles.expression}
|
||||
value={draft}
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
aria-label={tx("Expression")}
|
||||
onChange={(e) => setDraft(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key !== "Enter" || !draft.trim()) return;
|
||||
e.preventDefault();
|
||||
setExpression(draft.trim());
|
||||
setWin({ row: 0, column: 0 });
|
||||
}}
|
||||
/>
|
||||
{page && (
|
||||
{page && (
|
||||
<div className={styles.bar}>
|
||||
<span className={styles.summary}>
|
||||
{formatMessage(tx("Shape ({shape})"), { shape: page.shape.join(", ") })}
|
||||
{page.kind !== "frame" ? ` · ${page.dtypes[0]}` : ""}
|
||||
</span>
|
||||
)}
|
||||
{page &&
|
||||
pager(win.row, ROW_PAGE, page.rows, (row) => setWin({ ...win, row }), {
|
||||
range: tx("Rows {from}–{to} of {total}"),
|
||||
previous: tx("Previous Rows"),
|
||||
next: tx("Next Rows"),
|
||||
})}
|
||||
{page &&
|
||||
pager(win.column, COLUMN_PAGE, page.columns, (column) => setWin({ ...win, column }), {
|
||||
range: tx("Columns {from}–{to} of {total}"),
|
||||
previous: tx("Previous Columns"),
|
||||
next: tx("Next Columns"),
|
||||
})}
|
||||
</div>
|
||||
{error ? (
|
||||
<div className={styles.message} role="alert">
|
||||
{error}
|
||||
<div className={styles.pagers}>
|
||||
{pager(win.row, ROW_PAGE, page.rows, (row) => setWin({ ...win, row }), {
|
||||
range: tx("Rows {from}–{to} of {total}"),
|
||||
previous: tx("Previous Rows"),
|
||||
next: tx("Next Rows"),
|
||||
})}
|
||||
{pager(win.column, COLUMN_PAGE, page.columns, (column) => setWin({ ...win, column }), {
|
||||
range: tx("Columns {from}–{to} of {total}"),
|
||||
previous: tx("Previous Columns"),
|
||||
next: tx("Next Columns"),
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
) : page ? (
|
||||
)}
|
||||
{page ? (
|
||||
<div className={styles.scroll} tabIndex={0} role="region" aria-label={tx("Table")}>
|
||||
<table className={styles.table}>
|
||||
<thead>
|
||||
@@ -182,14 +156,7 @@ export function TableViewDialog({
|
||||
{page.index[r]}
|
||||
</th>
|
||||
{row.map((cell, c) => (
|
||||
<td
|
||||
key={c}
|
||||
className={clsx(
|
||||
isNumericDtype(page.kind === "frame" ? page.dtypes[c] : page.dtypes[0]) && styles.numeric,
|
||||
)}
|
||||
>
|
||||
{cell}
|
||||
</td>
|
||||
<td key={c}>{cell}</td>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
@@ -197,7 +164,26 @@ export function TableViewDialog({
|
||||
</table>
|
||||
</div>
|
||||
) : (
|
||||
<div className={styles.message}>{tx("Loading…")}</div>
|
||||
<div className={styles.message}>{!error && tx("Loading…")}</div>
|
||||
)}
|
||||
<Input
|
||||
className={styles.expression}
|
||||
mono
|
||||
data-autofocus=""
|
||||
value={draft}
|
||||
aria-label="Expression"
|
||||
onChange={(e) => setDraft(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key !== "Enter" || !draft.trim()) return;
|
||||
e.preventDefault();
|
||||
setExpression(draft.trim());
|
||||
setWin({ row: 0, column: 0 });
|
||||
}}
|
||||
/>
|
||||
{error && (
|
||||
<div className={styles.error} role="alert">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</Dialog>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { isBrowserLaunch } from "../browser";
|
||||
import type { DebugSession } from "../state";
|
||||
import { inTabOrder, type DebugSession } from "../state";
|
||||
|
||||
export interface SessionTab {
|
||||
session: DebugSession;
|
||||
@@ -18,7 +18,8 @@ export function sessionTabs(sessions: readonly DebugSession[]): SessionTab[] {
|
||||
const launches = new Set(
|
||||
sessions.filter((s) => s.parent == null && isBrowserLaunch(s.launch) && parents.has(s.id)).map((s) => s.id),
|
||||
);
|
||||
return sessions
|
||||
// Ordered by the root's slot: a browser page takes the place of its hidden launch.
|
||||
return inTabOrder(sessions)
|
||||
.filter((s) => !launches.has(s.id))
|
||||
.map((s) => {
|
||||
const page = s.parent != null && launches.has(s.parent);
|
||||
|
||||
@@ -3,7 +3,7 @@ import { useState } from "react";
|
||||
import { create } from "zustand";
|
||||
import { executeAction, getAction } from "@/platform/actions";
|
||||
import { t, tx } from "@/platform/i18n";
|
||||
import { BarButton, Button, Dialog, Icon, List, T } from "@/ui";
|
||||
import { BarButton, Dialog, Icon, IconButton, List, SplitGroup, SplitHandle, SplitPanel, T } from "@/ui";
|
||||
import { confirm } from "@/workbench/messages";
|
||||
import { promptInput } from "@/workbench/inputDialogs";
|
||||
import { deleteMacro, describeStep, renameMacro, useMacros } from "./model";
|
||||
@@ -80,37 +80,55 @@ function EditMacrosDialog({ onClose }: { onClose: () => void }) {
|
||||
buttons={[{ label: t("common.close"), role: "cancel" }]}
|
||||
>
|
||||
<div className={styles.edit}>
|
||||
<div className={styles.column}>
|
||||
<List
|
||||
items={saved}
|
||||
getKey={(m) => m.name}
|
||||
activeIndex={Math.min(active, saved.length - 1)}
|
||||
onActiveChange={setActive}
|
||||
className={styles.list}
|
||||
aria-label="Macros"
|
||||
empty={
|
||||
<div className={styles.empty}>
|
||||
<T>No saved macros</T>
|
||||
</div>
|
||||
}
|
||||
renderItem={(m) => <div className={styles.row}>{m.name}</div>}
|
||||
/>
|
||||
<div className={styles.buttons}>
|
||||
<Button disabled={!macro} onClick={() => void rename()}>
|
||||
<T>Rename…</T>
|
||||
</Button>
|
||||
<Button disabled={!macro} onClick={() => void remove()}>
|
||||
<T>Delete</T>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<ol className={styles.steps} aria-label={tx("Recorded steps")}>
|
||||
{macro?.steps.map((step, i) => (
|
||||
<li key={i} className={styles.step}>
|
||||
{describeStep(step, actionTitle)}
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
<SplitGroup orientation="horizontal" storageKey="openidea.macros.split" className={styles.panes}>
|
||||
<SplitPanel id="macro-list" defaultSize="50%" minSize="25%">
|
||||
<div className={styles.toolbar} role="toolbar" aria-label={tx("Macros")}>
|
||||
<IconButton
|
||||
icon="minus"
|
||||
title="Delete Macro"
|
||||
size="small"
|
||||
disabled={!macro}
|
||||
onClick={() => void remove()}
|
||||
/>
|
||||
<IconButton
|
||||
icon="edit"
|
||||
title="Rename Macro"
|
||||
size="small"
|
||||
disabled={!macro}
|
||||
onClick={() => void rename()}
|
||||
/>
|
||||
</div>
|
||||
<List
|
||||
items={saved}
|
||||
getKey={(m) => m.name}
|
||||
activeIndex={Math.min(active, saved.length - 1)}
|
||||
onActiveChange={setActive}
|
||||
autoFocus
|
||||
className={styles.list}
|
||||
aria-label="Macros"
|
||||
empty={
|
||||
<div className={styles.empty}>
|
||||
<T>No saved macros</T>
|
||||
</div>
|
||||
}
|
||||
renderItem={(m) => (
|
||||
<div className={styles.row} title={m.name}>
|
||||
{m.name}
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
</SplitPanel>
|
||||
<SplitHandle aria-label={tx("Macros")} />
|
||||
<SplitPanel id="macro-steps" defaultSize="50%" minSize="25%">
|
||||
<ol className={styles.steps} aria-label={tx("Recorded steps")}>
|
||||
{macro?.steps.map((step, i) => (
|
||||
<li key={i} className={styles.step}>
|
||||
{describeStep(step, actionTitle)}
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</SplitPanel>
|
||||
</SplitGroup>
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
|
||||
@@ -8,23 +8,27 @@
|
||||
background: var(--danger);
|
||||
}
|
||||
.edit {
|
||||
display: grid;
|
||||
grid-template-columns: 220px 1fr;
|
||||
gap: var(--space-3);
|
||||
height: 300px;
|
||||
padding: 14px;
|
||||
}
|
||||
.column {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-2);
|
||||
min-height: 0;
|
||||
height: 300px;
|
||||
padding: var(--space-3);
|
||||
}
|
||||
.panes {
|
||||
flex: 1;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-control);
|
||||
}
|
||||
.toolbar {
|
||||
display: flex;
|
||||
flex: none;
|
||||
align-items: center;
|
||||
gap: var(--space-0-5);
|
||||
padding: var(--space-1) var(--space-2);
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.list {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-control);
|
||||
}
|
||||
.row {
|
||||
padding: 0 8px;
|
||||
@@ -32,27 +36,25 @@
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.buttons {
|
||||
display: flex;
|
||||
gap: var(--space-1-5);
|
||||
}
|
||||
.empty {
|
||||
padding: 6px 8px;
|
||||
color: var(--fg-subtle);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
.steps {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
margin: 0;
|
||||
padding: 6px 8px 6px 32px;
|
||||
padding: var(--space-2) var(--space-2) var(--space-2) 28px;
|
||||
overflow: auto;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-control);
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--fs-code);
|
||||
font-family: var(--font-ui);
|
||||
font-size: var(--fs-ui);
|
||||
color: var(--fg);
|
||||
}
|
||||
.step {
|
||||
line-height: 1.6;
|
||||
min-height: var(--h-row);
|
||||
padding-block: var(--space-0-5);
|
||||
line-height: 1.5;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
@@ -5,7 +5,7 @@
|
||||
*/
|
||||
import type { FileEntry, OutlineItem } from "@/bindings";
|
||||
import { isIgnoredName } from "@/platform/ignoredNames";
|
||||
import { ancestorsWithin, isInside, isSameOrInside, nameOf, parentOf, relativeTo } from "./paths";
|
||||
import { ancestorsWithin, insideAnyOf, isInside, isSameOrInside, nameOf, parentOf, relativeTo } from "./paths";
|
||||
|
||||
export interface TreeOptions {
|
||||
/** Applied only by the Unity pane, never persisted as a user preference. */
|
||||
@@ -596,8 +596,9 @@ export function planRefresh(
|
||||
const drop = new Set<string>();
|
||||
const loadedList = [...loaded];
|
||||
|
||||
const inRemoved = insideAnyOf(event.removed);
|
||||
for (const dir of loadedList) if (inRemoved(dir)) drop.add(dir);
|
||||
for (const p of event.removed) {
|
||||
for (const dir of loadedList) if (isSameOrInside(dir, p)) drop.add(dir);
|
||||
const parent = parentOf(p);
|
||||
if (loaded.has(parent)) reload.add(parent);
|
||||
}
|
||||
@@ -610,7 +611,8 @@ export function planRefresh(
|
||||
drop.delete(p);
|
||||
}
|
||||
}
|
||||
for (const dir of loadedList) if (event.ignoreRules?.some((root) => isSameOrInside(dir, root))) reload.add(dir);
|
||||
const inIgnoreRoot = insideAnyOf(event.ignoreRules ?? []);
|
||||
for (const dir of loadedList) if (inIgnoreRoot(dir)) reload.add(dir);
|
||||
for (const d of drop) reload.delete(d);
|
||||
// A reloaded parent may report the folder as present again; keep its descendants then.
|
||||
return { reload: [...reload], drop: [...drop] };
|
||||
@@ -649,5 +651,6 @@ export function mergeListing(prev: readonly FileEntry[] | undefined, next: reado
|
||||
/** Removes `dirs` and every loaded folder inside them. */
|
||||
export function dropListings(listings: Map<string, readonly FileEntry[]>, dirs: readonly string[]) {
|
||||
if (!dirs.length) return;
|
||||
for (const key of [...listings.keys()]) if (dirs.some((d) => isSameOrInside(key, d))) listings.delete(key);
|
||||
const dropped = insideAnyOf(dirs);
|
||||
for (const key of [...listings.keys()]) if (dropped(key)) listings.delete(key);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
/** POSIX path helpers for backend paths (the backend always reports `/`-separated absolute paths). */
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { isSameOrInside } from "@/platform/paths";
|
||||
import { ipcPath, isSameOrInside } from "@/platform/paths";
|
||||
export { isSameOrInside } from "@/platform/paths";
|
||||
|
||||
export function joinPath(dir: string, name: string): string {
|
||||
@@ -22,6 +22,27 @@ export function isInside(path: string, ancestor: string): boolean {
|
||||
return path !== ancestor && isSameOrInside(path, ancestor);
|
||||
}
|
||||
|
||||
/**
|
||||
* `path => ancestors.some((a) => isSameOrInside(path, a))`, answered by looking up the path and each
|
||||
* of its parent folders in a set instead of comparing against every ancestor.
|
||||
*/
|
||||
export function insideAnyOf(ancestors: readonly string[]): (path: string) => boolean {
|
||||
if (!ancestors.length) return () => false;
|
||||
const same = new Set<string>();
|
||||
const below = new Set<string>();
|
||||
for (const a of ancestors) {
|
||||
const n = ipcPath(a);
|
||||
same.add(n);
|
||||
below.add(n.endsWith("/") ? n : `${n}/`);
|
||||
}
|
||||
return (path) => {
|
||||
const n = ipcPath(path);
|
||||
if (same.has(n)) return true;
|
||||
for (let i = n.indexOf("/"); i >= 0; i = n.indexOf("/", i + 1)) if (below.has(n.slice(0, i + 1))) return true;
|
||||
return false;
|
||||
};
|
||||
}
|
||||
|
||||
/** Path relative to `root` (`""` for the root itself); `path` unchanged when outside. */
|
||||
export function relativeTo(root: string, path: string): string {
|
||||
if (path === root) return "";
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { FileEntry } from "@/bindings";
|
||||
import { dropListings, planRefresh } from "./model";
|
||||
import { isSameOrInside as realIsSameOrInside } from "@/platform/paths";
|
||||
|
||||
// Counts the path-helper calls `planRefresh` / `dropListings` make: the work they do must grow with
|
||||
// loaded folders + removed paths, not with their product.
|
||||
const calls = vi.hoisted(() => ({ n: 0 }));
|
||||
vi.mock("@/platform/paths", async (importOriginal) => {
|
||||
const real = await importOriginal<typeof import("@/platform/paths")>();
|
||||
return {
|
||||
...real,
|
||||
ipcPath: (p: string) => (calls.n++, real.ipcPath(p)),
|
||||
isSameOrInside: (p: string, a: string) => (calls.n++, real.isSameOrInside(p, a)),
|
||||
};
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
calls.n = 0;
|
||||
});
|
||||
|
||||
/** A balanced 8-ary tree of `count` folders under a deep project root, in breadth-first order. */
|
||||
function folderTree(count: number): string[] {
|
||||
const dirs = ["/Users/dev/workspace/projects/acme/monorepo"];
|
||||
for (let i = 1; i < count; i++) dirs.push(`${dirs[Math.floor((i - 1) / 8)]}/package-${i}`);
|
||||
return dirs;
|
||||
}
|
||||
|
||||
const D = 2000;
|
||||
const dirs = folderTree(D);
|
||||
const loaded = new Set(dirs);
|
||||
|
||||
describe("removed paths scale with loaded folders + removed paths", () => {
|
||||
// `rm -rf` of a loaded subtree: every folder below `dirs[1]` plus 5 files in each.
|
||||
const subtree = dirs.filter((d) => d === dirs[1] || d.startsWith(`${dirs[1]}/`));
|
||||
const loadedSubtree = subtree.flatMap((d) => [d, ...Array.from({ length: 5 }, (_, i) => `${d}/file-${i}.ts`)]);
|
||||
// The same size of removal below a folder the tree never loaded.
|
||||
const unloadedSubtree = Array.from(
|
||||
{ length: loadedSubtree.length },
|
||||
(_, i) => `/Users/dev/workspace/other/dir-${i % 300}/file-${i}.ts`,
|
||||
);
|
||||
|
||||
it.each([
|
||||
["a loaded subtree", loadedSubtree],
|
||||
["a subtree that was never loaded", unloadedSubtree],
|
||||
])("planRefresh handles %s without testing every removed path against every folder", (_name, removed) => {
|
||||
expect(removed.length).toBeGreaterThan(D / 2);
|
||||
const plan = planRefresh({ created: [], modified: [], removed }, loaded);
|
||||
expect(calls.n).toBeLessThan(10 * (D + removed.length));
|
||||
expect(plan.drop.length).toBe(removed === loadedSubtree ? subtree.length : 0);
|
||||
});
|
||||
|
||||
it("dropListings handles many dropped folders without a pairwise scan", () => {
|
||||
const listings = new Map<string, readonly FileEntry[]>(dirs.map((d) => [d, []]));
|
||||
dropListings(listings, subtree);
|
||||
expect(calls.n).toBeLessThan(10 * (D + subtree.length));
|
||||
expect(listings.size).toBe(D - subtree.length);
|
||||
});
|
||||
});
|
||||
|
||||
// The pairwise semantics `planRefresh` / `dropListings` had before: a differential reference.
|
||||
function referencePlan(
|
||||
event: { created: string[]; modified: string[]; removed: string[]; ignoreRules?: string[] },
|
||||
loaded: Set<string>,
|
||||
) {
|
||||
const parentOf = (p: string) => {
|
||||
const i = p.lastIndexOf("/");
|
||||
return i <= 0 ? "/" : p.slice(0, i);
|
||||
};
|
||||
const reload = new Set<string>();
|
||||
const drop = new Set<string>();
|
||||
for (const p of event.removed) {
|
||||
for (const dir of loaded) if (realIsSameOrInside(dir, p)) drop.add(dir);
|
||||
if (loaded.has(parentOf(p))) reload.add(parentOf(p));
|
||||
}
|
||||
for (const p of [...event.created, ...event.modified]) {
|
||||
if (loaded.has(parentOf(p))) reload.add(parentOf(p));
|
||||
if (loaded.has(p)) {
|
||||
reload.add(p);
|
||||
drop.delete(p);
|
||||
}
|
||||
}
|
||||
for (const dir of loaded) if (event.ignoreRules?.some((r) => realIsSameOrInside(dir, r))) reload.add(dir);
|
||||
for (const d of drop) reload.delete(d);
|
||||
return { reload: [...reload].sort(), drop: [...drop].sort() };
|
||||
}
|
||||
|
||||
describe("planRefresh / dropListings keep the pairwise semantics", () => {
|
||||
const names = ["a", "ab", "a b", "A", "src", "Src", "x.y"];
|
||||
const roots = [
|
||||
"/",
|
||||
"/r",
|
||||
"/r/",
|
||||
"/ab",
|
||||
"C:/w",
|
||||
"C:\\w",
|
||||
"c:/w",
|
||||
"\\\\?\\C:\\w",
|
||||
"//srv/share",
|
||||
"\\\\srv\\share",
|
||||
"//?/UNC/srv/share",
|
||||
];
|
||||
|
||||
// Small deterministic generator so failures replay.
|
||||
const rng = (seed: number) => () => (seed = (seed * 1664525 + 1013904223) >>> 0) / 2 ** 32;
|
||||
|
||||
function randomPath(next: () => number): string {
|
||||
const root = roots[Math.floor(next() * roots.length)]!;
|
||||
const sep = root.includes("\\") ? "\\" : "/";
|
||||
let p = root;
|
||||
for (let depth = Math.floor(next() * 4); depth > 0; depth--) {
|
||||
p += (p.endsWith("/") || p.endsWith("\\") ? "" : sep) + names[Math.floor(next() * names.length)]!;
|
||||
}
|
||||
return next() < 0.08 ? p + sep : p;
|
||||
}
|
||||
|
||||
it("agrees with the pairwise implementation on random trees and batches", () => {
|
||||
const next = rng(7);
|
||||
for (let round = 0; round < 300; round++) {
|
||||
const loaded = new Set(Array.from({ length: 1 + Math.floor(next() * 25) }, () => randomPath(next)));
|
||||
const pick = (n: number) =>
|
||||
Array.from({ length: Math.floor(next() * n) }, () =>
|
||||
next() < 0.4 ? [...loaded][Math.floor(next() * loaded.size)]! : randomPath(next),
|
||||
);
|
||||
const event = {
|
||||
created: pick(4),
|
||||
modified: pick(4),
|
||||
removed: pick(6),
|
||||
ignoreRules: next() < 0.3 ? pick(2) : undefined,
|
||||
};
|
||||
const plan = planRefresh(event, loaded);
|
||||
const want = referencePlan(event, loaded);
|
||||
expect(
|
||||
{ reload: [...plan.reload].sort(), drop: [...plan.drop].sort() },
|
||||
JSON.stringify([...loaded]) + JSON.stringify(event),
|
||||
).toEqual(want);
|
||||
|
||||
const listings = new Map<string, readonly FileEntry[]>([...loaded].map((d) => [d, []]));
|
||||
dropListings(listings, plan.drop);
|
||||
expect([...listings.keys()].sort()).toEqual(
|
||||
[...loaded].filter((d) => !plan.drop.some((x) => realIsSameOrInside(d, x))).sort(),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it("does not treat a sibling that shares a name prefix as inside", () => {
|
||||
const plan = planRefresh(
|
||||
{ created: [], modified: [], removed: ["/a/a"] },
|
||||
new Set(["/a", "/a/a", "/a/ab", "/a/a/b"]),
|
||||
);
|
||||
expect([...plan.drop].sort()).toEqual(["/a/a", "/a/a/b"]);
|
||||
expect(plan.reload).toEqual(["/a"]);
|
||||
});
|
||||
|
||||
it("drops everything when the filesystem root is removed", () => {
|
||||
const plan = planRefresh({ created: [], modified: [], removed: ["/"] }, new Set(["/", "/a", "/a/b"]));
|
||||
expect([...plan.drop].sort()).toEqual(["/", "/a", "/a/b"]);
|
||||
});
|
||||
|
||||
it("reads Windows spellings of one folder as the same folder", () => {
|
||||
const plan = planRefresh(
|
||||
{ created: [], modified: [], removed: ["C:\\w\\src"] },
|
||||
new Set(["C:/w", "C:/w/src", "C:/w/src/deep"]),
|
||||
);
|
||||
expect([...plan.drop].sort()).toEqual(["C:/w/src", "C:/w/src/deep"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,234 @@
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import type { FileEntry } from "@/bindings";
|
||||
import { setProjectFsForTests, type ProjectFs } from "./fs";
|
||||
import { applyFsChange, initProjectTree, loadDir, selectModel, setSelection, useProjectTree } from "./store";
|
||||
|
||||
const ROOT = "/p";
|
||||
const FILES = 3;
|
||||
const FANOUT = 4;
|
||||
|
||||
const dirPath = (k: number) => `${ROOT}/${k}`;
|
||||
const filePath = (k: number) => `${dirPath(k)}/f.txt`;
|
||||
|
||||
/** A tree of `count` folders (heap-numbered, `FANOUT` per folder) below the root; `f.txt` of each folder has a version. */
|
||||
class TreeFs {
|
||||
readonly versions = new Map<number, number>();
|
||||
readonly removed = new Set<number>();
|
||||
readonly failing = new Set<string>();
|
||||
readonly gates = new Map<string, Promise<void>>();
|
||||
readonly reads: string[] = [];
|
||||
running = 0;
|
||||
peak = 0;
|
||||
|
||||
constructor(readonly count: number) {}
|
||||
|
||||
list(path: string): FileEntry[] {
|
||||
const entry = (p: string, kind: FileEntry["kind"], mtimeMs: number): FileEntry => ({
|
||||
name: p.slice(p.lastIndexOf("/") + 1),
|
||||
path: p,
|
||||
kind,
|
||||
size: 1,
|
||||
mtimeMs,
|
||||
ignored: false,
|
||||
excluded: false,
|
||||
hidden: false,
|
||||
});
|
||||
if (path === ROOT) return [entry(dirPath(0), "dir", 0)];
|
||||
const k = Number(path.slice(ROOT.length + 1));
|
||||
const out: FileEntry[] = [];
|
||||
for (let c = FANOUT * k + 1; c <= FANOUT * k + FANOUT && c < this.count; c++)
|
||||
if (!this.removed.has(c)) out.push(entry(dirPath(c), "dir", 0));
|
||||
out.push(filePath(k).length ? entry(filePath(k), "file", this.versions.get(k) ?? 0) : out[0]!);
|
||||
for (let i = 1; i < FILES; i++) out.push(entry(`${dirPath(k)}/g${i}.txt`, "file", 0));
|
||||
return out;
|
||||
}
|
||||
|
||||
async readDir(path: string): Promise<FileEntry[]> {
|
||||
this.reads.push(path);
|
||||
this.running++;
|
||||
this.peak = Math.max(this.peak, this.running);
|
||||
const snapshot = this.list(path);
|
||||
try {
|
||||
await (this.gates.get(path) ?? new Promise<void>((r) => setTimeout(r, 0)));
|
||||
if (this.failing.has(path)) throw new Error("EIO");
|
||||
return snapshot;
|
||||
} finally {
|
||||
this.running--;
|
||||
}
|
||||
}
|
||||
|
||||
asProjectFs = () => ({ readDir: (p: string) => this.readDir(p) }) as ProjectFs;
|
||||
}
|
||||
|
||||
/** Starts a project with every folder loaded, as after the user expanded the whole tree. */
|
||||
function loadedTree(fs: TreeFs) {
|
||||
setProjectFsForTests(fs.asProjectFs(), ROOT);
|
||||
initProjectTree(ROOT, "proj");
|
||||
const listings = new Map<string, readonly FileEntry[]>([[ROOT, fs.list(ROOT)]]);
|
||||
for (let k = 0; k < fs.count; k++) listings.set(dirPath(k), fs.list(dirPath(k)));
|
||||
useProjectTree.setState({ listings });
|
||||
fs.reads.length = 0;
|
||||
fs.peak = 0;
|
||||
}
|
||||
|
||||
const modify = (fs: TreeFs, ks: number[]) => {
|
||||
for (const k of ks) fs.versions.set(k, (fs.versions.get(k) ?? 0) + 1);
|
||||
return { created: [], modified: ks.map(filePath), removed: [] };
|
||||
};
|
||||
|
||||
/** What a mounted ProjectView does: select the model on every store notification. */
|
||||
function watchModels() {
|
||||
let last = selectModel(useProjectTree.getState());
|
||||
let builds = 0;
|
||||
const unsubscribe = useProjectTree.subscribe((s) => {
|
||||
const model = selectModel(s);
|
||||
if (model !== last) {
|
||||
last = model;
|
||||
builds++;
|
||||
}
|
||||
});
|
||||
return { builds: () => builds, unsubscribe };
|
||||
}
|
||||
|
||||
const range = (n: number) => Array.from({ length: n }, (_, i) => i);
|
||||
const listingsOf = () => useProjectTree.getState().listings;
|
||||
|
||||
beforeEach(() => localStorage.clear());
|
||||
|
||||
afterEach(() => {
|
||||
setProjectFsForTests(null);
|
||||
initProjectTree(null);
|
||||
});
|
||||
|
||||
describe("applyFsChange reload of many folders", () => {
|
||||
it("builds the model once and caps the concurrent reads, however many folders changed", async () => {
|
||||
const fs = new TreeFs(300);
|
||||
loadedTree(fs);
|
||||
const view = watchModels();
|
||||
|
||||
await applyFsChange(modify(fs, range(300)));
|
||||
view.unsubscribe();
|
||||
|
||||
expect(fs.reads).toHaveLength(300);
|
||||
expect(view.builds()).toBeLessThanOrEqual(2);
|
||||
expect(fs.peak).toBeGreaterThan(1);
|
||||
expect(fs.peak).toBeLessThanOrEqual(16);
|
||||
expect(
|
||||
listingsOf()
|
||||
.get(dirPath(299))
|
||||
?.find((e) => e.name === "f.txt")?.mtimeMs,
|
||||
).toBe(1);
|
||||
});
|
||||
|
||||
it("leaves folders without changes untouched and does not notify when nothing differs", async () => {
|
||||
const fs = new TreeFs(20);
|
||||
loadedTree(fs);
|
||||
const before = listingsOf();
|
||||
const view = watchModels();
|
||||
let notified = 0;
|
||||
const unsubscribe = useProjectTree.subscribe(() => notified++);
|
||||
|
||||
await applyFsChange({ created: [], modified: [filePath(3), filePath(4)], removed: [] });
|
||||
expect(listingsOf()).toBe(before);
|
||||
expect(notified).toBe(0);
|
||||
|
||||
await applyFsChange(modify(fs, [3]));
|
||||
unsubscribe();
|
||||
view.unsubscribe();
|
||||
expect(listingsOf().get(dirPath(3))).not.toBe(before.get(dirPath(3)));
|
||||
for (const k of [0, 1, 2, 4, 5]) expect(listingsOf().get(dirPath(k))).toBe(before.get(dirPath(k)));
|
||||
});
|
||||
|
||||
it("keeps the old listing of a folder whose read fails", async () => {
|
||||
const fs = new TreeFs(10);
|
||||
loadedTree(fs);
|
||||
const before = listingsOf();
|
||||
fs.failing.add(dirPath(2));
|
||||
|
||||
await applyFsChange(modify(fs, [1, 2, 3]));
|
||||
|
||||
expect(listingsOf().get(dirPath(2))).toBe(before.get(dirPath(2)));
|
||||
expect(
|
||||
listingsOf()
|
||||
.get(dirPath(1))
|
||||
?.find((e) => e.name === "f.txt")?.mtimeMs,
|
||||
).toBe(1);
|
||||
expect(
|
||||
listingsOf()
|
||||
.get(dirPath(3))
|
||||
?.find((e) => e.name === "f.txt")?.mtimeMs,
|
||||
).toBe(1);
|
||||
});
|
||||
|
||||
it("drops a folder that vanished while the batch was reading and does not bring it back", async () => {
|
||||
const fs = new TreeFs(10);
|
||||
loadedTree(fs);
|
||||
|
||||
const first = applyFsChange(modify(fs, [1, 2, 3]));
|
||||
fs.removed.add(3);
|
||||
await applyFsChange({ created: [], modified: [], removed: [dirPath(3)] });
|
||||
await first;
|
||||
|
||||
expect(listingsOf().has(dirPath(3))).toBe(false);
|
||||
expect(listingsOf().has(dirPath(2))).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps a listing that a later event read while an earlier batch was still waiting for a slow folder", async () => {
|
||||
const fs = new TreeFs(10);
|
||||
loadedTree(fs);
|
||||
let release!: () => void;
|
||||
fs.gates.set(dirPath(9), new Promise<void>((r) => (release = r)));
|
||||
|
||||
const first = applyFsChange(modify(fs, [1, 9]));
|
||||
await new Promise((r) => setTimeout(r, 5));
|
||||
await applyFsChange(modify(fs, [1]));
|
||||
release();
|
||||
await first;
|
||||
|
||||
expect(
|
||||
listingsOf()
|
||||
.get(dirPath(1))
|
||||
?.find((e) => e.name === "f.txt")?.mtimeMs,
|
||||
).toBe(2);
|
||||
expect(
|
||||
listingsOf()
|
||||
.get(dirPath(9))
|
||||
?.find((e) => e.name === "f.txt")?.mtimeMs,
|
||||
).toBe(1);
|
||||
});
|
||||
|
||||
it("ends with the listings and selection that reloading each folder on its own gives", async () => {
|
||||
const changed = [1, 2, 5, 7];
|
||||
const run = async (reload: (fs: TreeFs) => Promise<void>) => {
|
||||
const fs = new TreeFs(12);
|
||||
loadedTree(fs);
|
||||
useProjectTree.setState({ expanded: new Set([ROOT, dirPath(0), dirPath(1)]) });
|
||||
setSelection(new Set([filePath(1), dirPath(2)]), filePath(1));
|
||||
const before = listingsOf();
|
||||
modify(fs, changed);
|
||||
await reload(fs);
|
||||
const s = useProjectTree.getState();
|
||||
return { before, listings: s.listings, expanded: s.expanded, selected: s.selected, lead: s.lead };
|
||||
};
|
||||
|
||||
const batched = await run((fs) =>
|
||||
applyFsChange({ created: [], modified: changed.map(filePath), removed: [] }).then(() => void fs),
|
||||
);
|
||||
const single = await run(async () => {
|
||||
for (const k of changed) await loadDir(dirPath(k), true);
|
||||
});
|
||||
|
||||
expect(batched.listings).toEqual(single.listings);
|
||||
expect(batched.expanded).toEqual(single.expanded);
|
||||
expect([...batched.selected].sort()).toEqual([...single.selected].sort());
|
||||
expect(batched.lead).toBe(single.lead);
|
||||
for (const [path, listing] of batched.listings) {
|
||||
for (const [i, e] of listing.entries()) {
|
||||
const old = batched.before.get(path)?.find((o) => o.path === e.path);
|
||||
if (old && old.mtimeMs === e.mtimeMs && old.kind === e.kind && batched.before.get(path)?.[i] === old)
|
||||
expect(e).toBe(old);
|
||||
}
|
||||
}
|
||||
expect([...batched.selected].sort()).toEqual([filePath(1), dirPath(2)]);
|
||||
});
|
||||
});
|
||||
@@ -46,7 +46,7 @@ import {
|
||||
type ProjectViewLead,
|
||||
type ProjectViewRootContribution,
|
||||
} from "@/workbench/contributions";
|
||||
import { ancestorsWithin, isInside, isSameOrInside, nameOf, type PackageKind } from "./paths";
|
||||
import { ancestorsWithin, insideAnyOf, isInside, isSameOrInside, nameOf, type PackageKind } from "./paths";
|
||||
|
||||
export interface ViewOptions extends TreeOptions {
|
||||
/** Select the active editor's file in the tree (IDEA: Always Select Opened File). */
|
||||
@@ -327,6 +327,8 @@ export const currentModel = () => selectModel(get());
|
||||
|
||||
let generation = 0;
|
||||
const inflight = new Map<string, Promise<void>>();
|
||||
/** Listings read by a batch and not applied yet; `reload` marks folders that were loaded when read. */
|
||||
const pending = new Map<string, { entries: readonly FileEntry[]; reload: boolean }>();
|
||||
let persistTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
|
||||
/** Resets the view for a newly opened project, restoring its expansion state. */
|
||||
@@ -338,6 +340,7 @@ export function initProjectTree(
|
||||
) {
|
||||
generation++;
|
||||
inflight.clear();
|
||||
pending.clear();
|
||||
outlineInflight.clear();
|
||||
clearTimeout(persistTimer);
|
||||
modeExpanded.clear();
|
||||
@@ -509,25 +512,73 @@ function putListing(path: string, entries: readonly FileEntry[]) {
|
||||
set({ listings: new Map(listings).set(path, merged) });
|
||||
}
|
||||
|
||||
/** Folder reads a batch runs at once; a checkout can change thousands of folders. */
|
||||
const READ_SLOTS = 8;
|
||||
let readsRunning = 0;
|
||||
const readQueue: (() => void)[] = [];
|
||||
|
||||
async function withReadSlot<T>(read: () => Promise<T>): Promise<T> {
|
||||
if (readsRunning < READ_SLOTS) readsRunning++;
|
||||
else await new Promise<void>((resolve) => readQueue.push(resolve));
|
||||
try {
|
||||
return await read();
|
||||
} finally {
|
||||
const next = readQueue.shift();
|
||||
if (next) next();
|
||||
else readsRunning--;
|
||||
}
|
||||
}
|
||||
|
||||
/** Applies the batched listings in one update, so the tree model is built once for all of them. */
|
||||
function flushPending() {
|
||||
const { listings } = get();
|
||||
let next: Map<string, readonly FileEntry[]> | undefined;
|
||||
for (const [path, { entries, reload }] of pending) {
|
||||
// A folder dropped while the batch was reading stays dropped.
|
||||
if (reload && !listings.has(path)) continue;
|
||||
const merged = mergeListing(listings.get(path), entries);
|
||||
if (merged !== listings.get(path)) (next ??= new Map(listings)).set(path, merged);
|
||||
}
|
||||
pending.clear();
|
||||
if (next) set({ listings: next });
|
||||
}
|
||||
|
||||
/** Loads (or reloads) one folder. Concurrent calls for the same folder share a request. */
|
||||
export function loadDir(path: string, force = false): Promise<void> {
|
||||
return load(path, force, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* With `batched`, the listing waits in `pending` for `flushPending` and the read takes one of `READ_SLOTS`;
|
||||
* a later read of the same folder replaces it, so a flush never applies a listing older than one already read.
|
||||
*/
|
||||
function load(path: string, force: boolean, batched: boolean): Promise<void> {
|
||||
const { root, listings } = get();
|
||||
if (!root || isGroupKey(path)) return Promise.resolve();
|
||||
if (!force && listings.has(path)) return Promise.resolve();
|
||||
const running = inflight.get(path);
|
||||
if (running) return running;
|
||||
const gen = generation;
|
||||
const reload = listings.has(path);
|
||||
const p = (async () => {
|
||||
try {
|
||||
const entries = await projectFs(root).readDir(path);
|
||||
const read = () => projectFs(root).readDir(path);
|
||||
const entries = await (batched ? withReadSlot(read) : read());
|
||||
if (gen !== generation) return;
|
||||
putListing(path, entries);
|
||||
if (batched) pending.set(path, { entries, reload });
|
||||
else {
|
||||
pending.delete(path);
|
||||
putListing(path, entries);
|
||||
}
|
||||
// Compact Middle Packages needs to look one level down a single-folder chain.
|
||||
const s = get();
|
||||
if (treeOptions(s).compact) {
|
||||
const visible = visibleEntries(entries, treeOptions(s));
|
||||
const only = visible.length === 1 ? visible[0]! : null;
|
||||
if (only && isDirEntry(only) && !only.ignored && !s.listings.has(only.path)) void loadDir(only.path);
|
||||
if (only && isDirEntry(only) && !only.ignored && !s.listings.has(only.path)) {
|
||||
const next = load(only.path, false, batched);
|
||||
if (batched) await next;
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
if (gen !== generation) return;
|
||||
@@ -550,6 +601,12 @@ export function loadDir(path: string, force = false): Promise<void> {
|
||||
return p;
|
||||
}
|
||||
|
||||
/** Re-reads `paths` as one batch: bounded concurrent reads, one update of the listings. */
|
||||
async function reloadDirs(paths: readonly string[]) {
|
||||
await Promise.all(paths.map((p) => load(p, true, true)));
|
||||
flushPending();
|
||||
}
|
||||
|
||||
/** Applies a backend `fsChanged` event: reloads affected loaded folders only. */
|
||||
export async function applyFsChange(event: {
|
||||
created: string[];
|
||||
@@ -563,7 +620,8 @@ export async function applyFsChange(event: {
|
||||
if (plan.drop.length) {
|
||||
const listings = new Map(s.listings);
|
||||
dropListings(listings, plan.drop);
|
||||
const gone = (k: string) => plan.drop.some((d) => isSameOrInside(pathOfKey(k), d));
|
||||
const dropped = insideAnyOf(plan.drop);
|
||||
const gone = (k: string) => dropped(pathOfKey(k));
|
||||
const selected = [...s.selected].filter((k) => !gone(k));
|
||||
set({
|
||||
listings,
|
||||
@@ -583,18 +641,18 @@ export async function applyFsChange(event: {
|
||||
});
|
||||
}
|
||||
}
|
||||
await Promise.all(plan.reload.map((p) => loadDir(p, true)));
|
||||
await reloadDirs(plan.reload);
|
||||
// Member rows go stale when the file changes on disk: drop and refetch.
|
||||
if (event.modified.length) dropOutlines(event.modified);
|
||||
if (event.removed.length) {
|
||||
const outlines = new Map(get().outlines);
|
||||
const inRemoved = insideAnyOf(event.removed);
|
||||
let changed = false;
|
||||
for (const p of event.removed)
|
||||
for (const key of [...outlines.keys()])
|
||||
if (isSameOrInside(key, p)) {
|
||||
outlines.delete(key);
|
||||
changed = true;
|
||||
}
|
||||
for (const key of [...outlines.keys()])
|
||||
if (inRemoved(key)) {
|
||||
outlines.delete(key);
|
||||
changed = true;
|
||||
}
|
||||
if (changed) set({ outlines });
|
||||
}
|
||||
}
|
||||
@@ -602,7 +660,7 @@ export async function applyFsChange(event: {
|
||||
/** Re-reads the folders among `dirs` the tree has loaded; the rest stay unread. */
|
||||
export async function reloadLoadedDirs(dirs: readonly string[]) {
|
||||
const { listings } = get();
|
||||
await Promise.all(dirs.filter((p) => listings.has(p)).map((p) => loadDir(p, true)));
|
||||
await reloadDirs(dirs.filter((p) => listings.has(p)));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -612,13 +670,13 @@ export async function reloadLoadedDirs(dirs: readonly string[]) {
|
||||
export async function reloadArchiveDirs() {
|
||||
const { listings } = get();
|
||||
const inArchive = (p: string) => p.endsWith("!") || p.includes("!/") || p.includes("!\\");
|
||||
await Promise.all([...listings.keys()].filter(inArchive).map((p) => loadDir(p, true)));
|
||||
await reloadDirs([...listings.keys()].filter(inArchive));
|
||||
}
|
||||
|
||||
/** Re-reads every loaded folder (View › Reload from Disk). */
|
||||
export async function reloadAll() {
|
||||
const { listings } = get();
|
||||
await Promise.all([...listings.keys()].map((p) => loadDir(p, true)));
|
||||
await reloadDirs([...listings.keys()]);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -126,6 +126,9 @@
|
||||
.stackedRadioBlock {
|
||||
margin-inline-end: 0;
|
||||
}
|
||||
.stackedRadioBlock > .radioLabel {
|
||||
white-space: normal;
|
||||
}
|
||||
.stackedRadios {
|
||||
max-width: 100%;
|
||||
}
|
||||
@@ -136,6 +139,11 @@
|
||||
.stackedRadioBlock .radioLabel + .stackedRadios {
|
||||
padding-inline-start: calc(var(--space-4) + var(--space-1));
|
||||
}
|
||||
.tabOverflowChoices {
|
||||
align-items: flex-start;
|
||||
gap: var(--space-1);
|
||||
max-width: 100%;
|
||||
}
|
||||
.radio {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
|
||||
@@ -9,7 +9,7 @@ import { useEffect, useId, useState } from "react";
|
||||
import clsx from "clsx";
|
||||
import { commands, isTauri } from "@/platform/ipc";
|
||||
import { Checkbox, Icon, Radio, type IconName } from "@/ui";
|
||||
import { SearchLabel, Select } from "../../components/Form";
|
||||
import { Row, SearchLabel, Select } from "../../components/Form";
|
||||
import { useLabelMatch, useSearchQuery, useSetting } from "../../components/context";
|
||||
import { labelMatches } from "../../model/pages";
|
||||
import { editorPage } from "./kit";
|
||||
@@ -581,6 +581,7 @@ const TABS = editorPage({
|
||||
t: "radio",
|
||||
key: `${P}.tabs.closingPolicy`,
|
||||
label: "When the tab limit is reached",
|
||||
layout: "stacked",
|
||||
options: [
|
||||
{ value: "unchanged", label: "Close non-modified files first" },
|
||||
{ value: "lru", label: "Close least recently used files" },
|
||||
@@ -590,6 +591,7 @@ const TABS = editorPage({
|
||||
t: "radio",
|
||||
key: `${P}.tabs.activateOnClose`,
|
||||
label: "When the current tab is closed, activate",
|
||||
layout: "stacked",
|
||||
options: [
|
||||
{ value: "left", label: "The tab on the left" },
|
||||
{ value: "right", label: "The tab on the right" },
|
||||
@@ -607,10 +609,11 @@ function TabRows() {
|
||||
const [overflow, setOverflow] = useSetting<string>(`${P}.tabs.oneRowOverflow`);
|
||||
const [placement] = useSetting<string>(`${P}.tabs.placement`);
|
||||
const matched = useLabelMatch("Show tabs in:");
|
||||
const name = useId();
|
||||
const rowsName = useId();
|
||||
const overflowName = useId();
|
||||
// Vertical (left / right) tabs always scroll in one column.
|
||||
const disabled = placement === "none" || placement === "left" || placement === "right";
|
||||
const radio = (label: string, checked: boolean, onChange: () => void, off = disabled) => (
|
||||
const radio = (name: string, label: string, checked: boolean, onChange: () => void, off = disabled) => (
|
||||
<label className={clsx(styles.radio, off && styles.dim)}>
|
||||
<input type="radio" name={name} checked={checked} disabled={off} onChange={onChange} />
|
||||
<SearchLabel text={label} />
|
||||
@@ -618,30 +621,36 @@ function TabRows() {
|
||||
);
|
||||
return (
|
||||
<div
|
||||
className={clsx(styles.radioBlock, matched && styles.matched)}
|
||||
className={clsx(styles.radioBlock, styles.stackedRadioBlock, matched && styles.matched)}
|
||||
role="radiogroup"
|
||||
aria-label={tx("Show tabs in")}
|
||||
>
|
||||
<div className={clsx(styles.radioLabel, disabled && styles.dim)}>
|
||||
<SearchLabel text="Show tabs in" />:
|
||||
</div>
|
||||
<div className={styles.radios}>
|
||||
{radio("One row, and if tabs don't fit:", !multiple, () => setMultiple(false))}
|
||||
<div className={styles.children} role="radiogroup" aria-label={tx("If tabs don't fit")}>
|
||||
<div className={clsx(styles.radios, styles.stackedRadios)}>
|
||||
{radio(rowsName, "One row, and if tabs don't fit:", !multiple, () => setMultiple(false))}
|
||||
<div
|
||||
className={clsx(styles.children, styles.tabOverflowChoices)}
|
||||
role="radiogroup"
|
||||
aria-label={tx("If tabs don't fit")}
|
||||
>
|
||||
{radio(
|
||||
overflowName,
|
||||
"Scroll the tabs panel",
|
||||
!multiple && overflow !== "squeeze",
|
||||
overflow !== "squeeze",
|
||||
() => setOverflow("scroll"),
|
||||
disabled || multiple,
|
||||
)}
|
||||
{radio(
|
||||
overflowName,
|
||||
"Squeeze tabs",
|
||||
!multiple && overflow === "squeeze",
|
||||
overflow === "squeeze",
|
||||
() => setOverflow("squeeze"),
|
||||
disabled || multiple,
|
||||
)}
|
||||
</div>
|
||||
{radio("Multiple rows", multiple, () => setMultiple(true))}
|
||||
{radio(rowsName, "Multiple rows", multiple, () => setMultiple(true))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
@@ -657,12 +666,8 @@ const CLOSE_POSITIONS = [
|
||||
function CloseButtonPosition() {
|
||||
const [show, setShow] = useSetting<boolean>(`${P}.tabs.showCloseButton`);
|
||||
const [position, setPosition] = useSetting<string>(`${P}.tabs.closeButtonPosition`);
|
||||
const matched = useLabelMatch("Close button position:");
|
||||
return (
|
||||
<div className={clsx(styles.check, matched && styles.matched)}>
|
||||
<span>
|
||||
<SearchLabel text="Close button position:" />
|
||||
</span>
|
||||
<Row label="Close button position">
|
||||
<Select
|
||||
value={show ? (position === "left" ? "left" : "right") : "none"}
|
||||
options={CLOSE_POSITIONS}
|
||||
@@ -672,7 +677,7 @@ function CloseButtonPosition() {
|
||||
if (v !== "none") setPosition(v);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</Row>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,22 +1,33 @@
|
||||
.page {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
color: var(--fg);
|
||||
display: grid;
|
||||
gap: var(--space-4);
|
||||
font-size: var(--fs-ui);
|
||||
}
|
||||
.section {
|
||||
|
||||
.heading {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
margin-top: 6px;
|
||||
min-height: var(--h-field);
|
||||
margin: 0 0 var(--space-1);
|
||||
color: var(--fg-strong);
|
||||
font-size: inherit;
|
||||
font-weight: 500;
|
||||
}
|
||||
.header {
|
||||
color: var(--fg-muted);
|
||||
|
||||
.heading::after {
|
||||
content: "";
|
||||
flex: 1;
|
||||
height: 1px;
|
||||
background: var(--border);
|
||||
}
|
||||
.columns {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-2);
|
||||
padding-left: 18px;
|
||||
|
||||
.options {
|
||||
display: grid;
|
||||
gap: var(--space-1);
|
||||
padding-inline-start: var(--space-4);
|
||||
}
|
||||
|
||||
.options > label {
|
||||
min-height: var(--h-field);
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
/** Settings › Version Control › Log: how the Git Log shows references, dates and columns. */
|
||||
import { useId, type ReactNode } from "react";
|
||||
import { Checkbox, T } from "@/ui";
|
||||
import { setLogOptions, useLogOptions, type LogOptions } from "./logOptions";
|
||||
import styles from "./LogSettingsPage.module.css";
|
||||
import { tx } from "@/platform/i18n";
|
||||
|
||||
type Flag = { [K in keyof LogOptions]: LogOptions[K] extends boolean ? K : never }[keyof LogOptions];
|
||||
|
||||
@@ -21,6 +21,18 @@ const COLUMNS: { key: Flag; label: string }[] = [
|
||||
{ key: "showGitHubChecks", label: "GitHub Commit Checks" },
|
||||
];
|
||||
|
||||
function OptionGroup({ title, children }: { title: string; children: ReactNode }) {
|
||||
const heading = useId();
|
||||
return (
|
||||
<section aria-labelledby={heading}>
|
||||
<h2 id={heading} className={styles.heading}>
|
||||
<T>{title}</T>
|
||||
</h2>
|
||||
<div className={styles.options}>{children}</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
export function LogSettingsPage() {
|
||||
const o = useLogOptions();
|
||||
// Display options only: the log needs no reload.
|
||||
@@ -29,13 +41,8 @@ export function LogSettingsPage() {
|
||||
);
|
||||
return (
|
||||
<div className={styles.page}>
|
||||
{OPTIONS.map(flag)}
|
||||
<section className={styles.section} aria-label={tx("Visible columns")}>
|
||||
<div className={styles.header}>
|
||||
<T>Visible columns:</T>
|
||||
</div>
|
||||
<div className={styles.columns}>{COLUMNS.map(flag)}</div>
|
||||
</section>
|
||||
<OptionGroup title="View Options">{OPTIONS.map(flag)}</OptionGroup>
|
||||
<OptionGroup title="Visible columns">{COLUMNS.map(flag)}</OptionGroup>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -68,3 +68,56 @@
|
||||
overflow-wrap: anywhere;
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
.editor {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.pathInput {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
width: 100%;
|
||||
padding: var(--space-2) var(--space-3);
|
||||
resize: none;
|
||||
border: 0;
|
||||
outline: none;
|
||||
background: var(--bg-editor);
|
||||
color: var(--fg-editor);
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--fs-code);
|
||||
line-height: var(--lh-code);
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.pathInput:focus-visible {
|
||||
box-shadow: inset 0 0 0 1px var(--focus-ring);
|
||||
}
|
||||
|
||||
.editorError {
|
||||
flex: none;
|
||||
padding: var(--space-1) var(--space-2);
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
.editorFooter {
|
||||
flex: none;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-1) var(--space-2);
|
||||
padding: var(--space-1) var(--space-2);
|
||||
border-top: 1px solid var(--border-popup);
|
||||
color: var(--fg-secondary);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
|
||||
.apply {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
margin-inline-start: auto;
|
||||
}
|
||||
@@ -1,11 +1,13 @@
|
||||
import { useState } from "react";
|
||||
import { Checkbox, Dialog, Icon, SearchField, Tree, fileIconName } from "@/ui";
|
||||
import { useId, useState } from "react";
|
||||
import { Button, Checkbox, Dialog, Icon, Popup, T, Tree, fileIconName } from "@/ui";
|
||||
import { projectFs } from "@/features/project-tree/fs";
|
||||
import { openDialog } from "./dialogs";
|
||||
import { dirName, relTo, stripSlash } from "./model";
|
||||
import { repoName, repoOf } from "./store";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { isImeKey } from "@/platform/ime";
|
||||
import { formatBinding, hasPrimaryModifier, isMacHost } from "@/platform/keymap";
|
||||
import { ipcPath, isSameOrInside } from "@/platform/paths";
|
||||
import styles from "./PathFilterDialog.module.css";
|
||||
|
||||
@@ -31,42 +33,33 @@ export function chooseLogPaths(roots: string[], initial: string[], readOnly = fa
|
||||
});
|
||||
}
|
||||
|
||||
export function editLogPaths(roots: string[], initial: string[]): Promise<string[] | null> {
|
||||
function commonRoot(roots: string[]): string | undefined {
|
||||
let base = roots[0];
|
||||
while (base && !roots.every((root) => isSameOrInside(root, base!))) {
|
||||
const parent = dirName(base);
|
||||
base = parent || (base.startsWith("/") && base !== "/" ? "/" : undefined);
|
||||
}
|
||||
return new Promise((resolve) => {
|
||||
const close = openDialog(() => (
|
||||
<LogPathsEditor
|
||||
roots={roots}
|
||||
initial={initial}
|
||||
base={base}
|
||||
onDone={(value) => {
|
||||
close();
|
||||
resolve(value);
|
||||
}}
|
||||
/>
|
||||
));
|
||||
});
|
||||
return base;
|
||||
}
|
||||
|
||||
function LogPathsEditor({
|
||||
export function LogPathsEditor({
|
||||
anchor,
|
||||
roots,
|
||||
initial,
|
||||
base,
|
||||
onDone,
|
||||
}: {
|
||||
anchor: HTMLElement;
|
||||
roots: string[];
|
||||
initial: string[];
|
||||
base?: string;
|
||||
onDone: (value: string[] | null) => void;
|
||||
}) {
|
||||
const [base] = useState(() => commonRoot(roots));
|
||||
const [text, setText] = useState(() =>
|
||||
initial.map((path) => (base ? (path === base ? "." : relTo(stripSlash(base), path)) : path)).join("\n"),
|
||||
);
|
||||
const [error, setError] = useState(false);
|
||||
const hint = useId();
|
||||
const shortcut = formatBinding(isMacHost() ? "Meta+Enter" : "Ctrl+Enter");
|
||||
const apply = () => {
|
||||
const paths = text
|
||||
.split("\n")
|
||||
@@ -88,30 +81,62 @@ function LogPathsEditor({
|
||||
onDone([...new Set(paths)]);
|
||||
};
|
||||
return (
|
||||
<Dialog
|
||||
<Popup
|
||||
open
|
||||
title="Filter by Paths"
|
||||
width={560}
|
||||
anchor={anchor}
|
||||
aria-label={tx("Filter by Paths")}
|
||||
className={styles.editor}
|
||||
initialSize={{ w: 432, h: 200 }}
|
||||
resizable="both"
|
||||
minWidth={200}
|
||||
minHeight={110}
|
||||
trapFocus
|
||||
onClose={() => onDone(null)}
|
||||
buttons={[
|
||||
{ label: "OK", role: "default", onClick: apply },
|
||||
{ label: "Cancel", role: "cancel" },
|
||||
]}
|
||||
>
|
||||
<SearchField
|
||||
<textarea
|
||||
data-autofocus
|
||||
multiline
|
||||
leadingIcon={null}
|
||||
className={styles.pathInput}
|
||||
spellCheck={false}
|
||||
value={text}
|
||||
onChange={(value) => {
|
||||
setText(value);
|
||||
onChange={(event) => {
|
||||
setText(event.target.value);
|
||||
setError(false);
|
||||
}}
|
||||
aria-label="Paths"
|
||||
placeholder="One path per line"
|
||||
onKeyDown={(event) => {
|
||||
if (
|
||||
event.key !== "Enter" ||
|
||||
!hasPrimaryModifier(event) ||
|
||||
event.shiftKey ||
|
||||
event.altKey ||
|
||||
isImeKey(event.nativeEvent)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
apply();
|
||||
}}
|
||||
aria-label={tx("Paths")}
|
||||
aria-describedby={hint}
|
||||
aria-invalid={error || undefined}
|
||||
/>
|
||||
{error && <div role="alert">{tx("Choose a path inside a repository.")}</div>}
|
||||
</Dialog>
|
||||
{error && (
|
||||
<div className={styles.editorError} role="alert">
|
||||
<T>Choose a path inside a repository.</T>
|
||||
</div>
|
||||
)}
|
||||
<div className={styles.editorFooter}>
|
||||
<span id={hint}>
|
||||
<T>One path per line</T>
|
||||
</span>
|
||||
<span className={styles.apply}>
|
||||
<kbd>{shortcut}</kbd>
|
||||
<Button onClick={apply} size="small" variant="primary">
|
||||
OK
|
||||
</Button>
|
||||
</span>
|
||||
</div>
|
||||
</Popup>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
/**
|
||||
* The dense-array lane layout `computeGraph` used before its lanes were kept sparsely, kept
|
||||
* verbatim as the oracle for the differential tests: it scans every slot number per row.
|
||||
*/
|
||||
import { emptyGraphState, graphLayout } from "../graph";
|
||||
import type { GraphCommit, GraphRow, GraphSegment, GraphState, EdgeKind } from "../graph";
|
||||
|
||||
interface Lane {
|
||||
id: string;
|
||||
source?: string;
|
||||
kind?: EdgeKind;
|
||||
color: number;
|
||||
dashed?: true;
|
||||
}
|
||||
|
||||
const firstFree = (lanes: Array<Lane | null>) => {
|
||||
const i = lanes.indexOf(null);
|
||||
return i < 0 ? lanes.length : i;
|
||||
};
|
||||
|
||||
const seg = (from: number, to: number, color: number, dashed?: boolean): GraphSegment =>
|
||||
dashed ? { from, to, color, dashed: true } : { from, to, color };
|
||||
|
||||
const laneOf = (id: string, color: number, dashed: boolean): Lane =>
|
||||
dashed ? { id, color, dashed: true } : { id, color };
|
||||
|
||||
/**
|
||||
* Lays out `commits` (continuing from `state`, so pages can be appended).
|
||||
* Each lane keeps its position while it lives; freed slots are reused.
|
||||
*/
|
||||
export function referenceComputeGraph(
|
||||
commits: ReadonlyArray<GraphCommit>,
|
||||
state: GraphState = emptyGraphState(),
|
||||
): { rows: GraphRow[]; state: GraphState } {
|
||||
const lanes = [...state.lanes];
|
||||
const track = commits.some((c) => c.refs !== undefined);
|
||||
const positions = new Map(commits.map((c, i) => [c.id, i]));
|
||||
const layout = graphLayout(commits);
|
||||
const refAware = commits.some((c) => c.refs?.length);
|
||||
const stableColor = (id: string, fallback: number) => {
|
||||
if (!refAware) return fallback;
|
||||
const index = positions.get(id);
|
||||
const owner = index == null ? id : layout.owners[index]!;
|
||||
let hash = 2166136261;
|
||||
for (const char of owner) hash = Math.imul(hash ^ char.charCodeAt(0), 16777619);
|
||||
return hash >>> 0;
|
||||
};
|
||||
const describe = (s: GraphSegment, lane: Lane) =>
|
||||
track ? { ...s, edge: `${lane.source ?? ""}\0${lane.id}`, source: lane.source, kind: lane.kind } : s;
|
||||
|
||||
let nextColor = state.nextColor;
|
||||
const rows: GraphRow[] = [];
|
||||
|
||||
for (const c of commits) {
|
||||
const matching: number[] = [];
|
||||
lanes.forEach((l, i) => {
|
||||
if (l?.id === c.id) matching.push(i);
|
||||
});
|
||||
let lane: number;
|
||||
let color: number;
|
||||
if (matching.length) {
|
||||
lane = matching[0]!;
|
||||
color = lanes[lane]!.color;
|
||||
} else {
|
||||
const preferred = refAware ? Math.max(0, layout.layout[positions.get(c.id)!]! - 1) : firstFree(lanes);
|
||||
lane = !lanes[preferred] ? preferred : firstFree(lanes);
|
||||
color = stableColor(c.id, nextColor++);
|
||||
}
|
||||
const widthBefore = lanes.length;
|
||||
|
||||
const up: GraphSegment[] = [];
|
||||
const upTargets: string[] = [];
|
||||
lanes.forEach((l, i) => {
|
||||
if (!l) return;
|
||||
up.push(describe(seg(i, l.id === c.id ? lane : i, l.color, l.dashed), l));
|
||||
upTargets.push(l.id);
|
||||
});
|
||||
for (const m of matching) lanes[m] = null;
|
||||
if (lane >= lanes.length) lanes.length = lane + 1;
|
||||
lanes[lane] = null;
|
||||
|
||||
const down: GraphSegment[] = [];
|
||||
const downTargets: string[] = [];
|
||||
lanes.forEach((l, i) => {
|
||||
if (l) {
|
||||
down.push(describe(seg(i, i, l.color, l.dashed), l));
|
||||
downTargets.push(l.id);
|
||||
}
|
||||
});
|
||||
|
||||
c.parents.forEach((p, k) => {
|
||||
const dashed = !!c.dashed?.[k];
|
||||
const kind = c.edgeTypes?.[k] ?? (dashed ? "filtered" : "normal");
|
||||
const info = {
|
||||
id: p,
|
||||
source: c.id,
|
||||
kind: !positions.has(p) && kind !== "shallow" ? ("unloaded" as const) : kind,
|
||||
};
|
||||
if (track && kind === "shallow") {
|
||||
down.push({
|
||||
...describe(seg(lane, lane, color, dashed), { ...info, color }),
|
||||
kind: kind === "shallow" ? "shallow" : "unloaded",
|
||||
arrow: "down",
|
||||
targetRow: -1,
|
||||
});
|
||||
downTargets.push(p);
|
||||
return;
|
||||
}
|
||||
// The first parent continues this lane even if another lane also leads to it
|
||||
// (both lines then converge at the parent's node, like `git log --graph`).
|
||||
if (k === 0) {
|
||||
lanes[lane] = { ...laneOf(p, color, dashed), ...info };
|
||||
down.push(describe(seg(lane, lane, color, dashed), { ...info, color }));
|
||||
downTargets.push(p);
|
||||
return;
|
||||
}
|
||||
const existing = lanes.findIndex((l) => l?.id === p);
|
||||
if (existing >= 0) {
|
||||
down.push(
|
||||
describe(seg(lane, existing, lanes[existing]!.color, dashed), { ...info, color: lanes[existing]!.color }),
|
||||
);
|
||||
downTargets.push(p);
|
||||
return;
|
||||
}
|
||||
const slot = firstFree(lanes);
|
||||
const col = stableColor(p, nextColor++);
|
||||
lanes[slot] = { ...laneOf(p, col, dashed), ...info };
|
||||
down.push(describe(seg(lane, slot, col, dashed), { ...info, color: col }));
|
||||
downTargets.push(p);
|
||||
});
|
||||
|
||||
while (lanes.length && lanes[lanes.length - 1] === null) lanes.pop();
|
||||
const widthAfter = down.reduce((width, segment) => Math.max(width, segment.to + 1), 0);
|
||||
rows.push({
|
||||
...(track ? { id: c.id } : {}),
|
||||
lane,
|
||||
color,
|
||||
up,
|
||||
down,
|
||||
upTargets,
|
||||
downTargets,
|
||||
width: Math.max(widthBefore, widthAfter, lane + 1),
|
||||
});
|
||||
}
|
||||
if (track && rows.length) {
|
||||
const last = rows.at(-1)!;
|
||||
last.down = last.down.map((s) => (s.kind === "unloaded" ? { ...s, arrow: "down", targetRow: -1 } : s));
|
||||
}
|
||||
return { rows, state: { lanes, nextColor } };
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
import type { Commit } from "@/bindings";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("../graph", async (original) => {
|
||||
const real = await original<typeof import("../graph")>();
|
||||
return { ...real, computeGraph: vi.fn(real.computeGraph) };
|
||||
});
|
||||
|
||||
import { computeGraph, type GraphCommit } from "../graph";
|
||||
import { presentLogGraph, type GraphOptions } from "../logPresentation";
|
||||
import { commitKey, graphCommit } from "../multiRoot";
|
||||
import { referenceComputeGraph } from "./graphReference";
|
||||
|
||||
const { computeGraph: real } = await vi.importActual<typeof import("../graph")>("../graph");
|
||||
|
||||
const id = (i: number) => `c${i.toString(16).padStart(6, "0")}`;
|
||||
|
||||
/**
|
||||
* A deterministic history in log order (children before parents): up to eight branches
|
||||
* that fork, merge (some with a filtered edge) and carry refs, cut off at `count` commits so
|
||||
* that the oldest ones lead to parents that are not loaded.
|
||||
*/
|
||||
function history(count: number, withRefs: boolean): Commit[] {
|
||||
let seed = 7;
|
||||
const rnd = () => (seed = (seed * 1103515245 + 12345) & 0x7fffffff) / 0x7fffffff;
|
||||
const total = count + 40;
|
||||
const tips: number[] = [0];
|
||||
const parents: number[][] = [[]];
|
||||
const dashed = new Map<number, boolean[]>();
|
||||
for (let i = 1; i < total; i++) {
|
||||
const r = rnd();
|
||||
const h = Math.floor(rnd() * tips.length);
|
||||
if (r < 0.06 && tips.length < 8) {
|
||||
parents.push([tips[h]!]);
|
||||
tips.push(i);
|
||||
} else if (r < 0.14 && tips.length > 1) {
|
||||
const other = (h + 1) % tips.length;
|
||||
parents.push([tips[h]!, tips[other]!]);
|
||||
if (rnd() < 0.3) dashed.set(i, [false, true]);
|
||||
tips[h] = i;
|
||||
tips.splice(other, 1);
|
||||
} else {
|
||||
parents.push([tips[h]!]);
|
||||
tips[h] = i;
|
||||
}
|
||||
}
|
||||
const commits: Commit[] = [];
|
||||
for (let i = total - 1; i >= 40; i--) {
|
||||
const refs: string[] = [];
|
||||
if (withRefs) {
|
||||
if (i === total - 1) refs.push("HEAD", "main");
|
||||
else if (i % 211 === 0) refs.push(`tag: v${i}`);
|
||||
else if (i % 97 === 0) refs.push(`feature-${i}`);
|
||||
else if (i % 151 === 0) refs.push(`origin/topic-${i}`);
|
||||
}
|
||||
commits.push({
|
||||
id: id(i),
|
||||
shortId: id(i),
|
||||
parents: parents[i]!.map(id),
|
||||
...(dashed.has(i) ? { dashed: dashed.get(i)! } : {}),
|
||||
author: "A",
|
||||
email: "[email protected]",
|
||||
summary: id(i),
|
||||
message: id(i),
|
||||
timeMs: i,
|
||||
refs,
|
||||
remoteNames: refs.filter((r) => r.startsWith("origin/")),
|
||||
} as Commit);
|
||||
}
|
||||
return commits;
|
||||
}
|
||||
|
||||
const noFragments = () => ({ expanded: new Set<string>(), collapsed: new Set<string>(), merges: new Set<string>() });
|
||||
|
||||
function fragmentVariants(commits: readonly Commit[]) {
|
||||
const linear = commits.filter((c) => c.parents.length === 1 && !c.refs.length).map((c) => c.id);
|
||||
const merges = commits.filter((c) => c.parents.length === 2).map((c) => c.id);
|
||||
const every = (ids: string[], n: number) => new Set(ids.filter((_, i) => i % n === 0));
|
||||
return {
|
||||
none: noFragments(),
|
||||
collapsed: { ...noFragments(), collapsed: every(linear, 7) },
|
||||
expandedLinear: { ...noFragments(), expanded: every(linear, 5), merges: every(merges, 3) },
|
||||
someMerges: { ...noFragments(), merges: every(merges, 2) },
|
||||
allMerges: { ...noFragments(), merges: new Set(["*"]) },
|
||||
};
|
||||
}
|
||||
|
||||
afterEach(() => vi.mocked(computeGraph).mockImplementation(real));
|
||||
|
||||
describe("computeGraph lane slots", () => {
|
||||
const pages = (commits: readonly Commit[], size: number) => {
|
||||
const source = commits.map(graphCommit);
|
||||
return Array.from({ length: Math.ceil(source.length / size) }, (_, i) => source.slice(i * size, (i + 1) * size));
|
||||
};
|
||||
|
||||
it.each([true, false])("lays out page by page exactly like the dense lane array (refs: %s)", (withRefs) => {
|
||||
let state = { lanes: [] as ReturnType<typeof computeGraph>["state"]["lanes"], nextColor: 0 };
|
||||
let expected = state;
|
||||
// Pages are laid out on their own, so the loaded part of the log is each page itself.
|
||||
for (const page of pages(history(2400, withRefs), 300)) {
|
||||
const got = real(page, state);
|
||||
const want = referenceComputeGraph(page, expected);
|
||||
expect(got.rows).toEqual(want.rows);
|
||||
expect(got.state).toEqual(want.state);
|
||||
expect(got.state.lanes.length).toBe(want.state.lanes.length);
|
||||
state = got.state;
|
||||
expected = want.state;
|
||||
}
|
||||
});
|
||||
|
||||
it("continues from a state with vacated, occupied and never-used slots", () => {
|
||||
const lanes: Array<{ id: string; color: number } | null> = [];
|
||||
lanes[1] = { id: "b", color: 3 };
|
||||
lanes[4] = null;
|
||||
lanes[6] = { id: "d", color: 5 };
|
||||
const commits: GraphCommit[] = [
|
||||
{ id: "a", parents: ["b", "e"] },
|
||||
{ id: "e", parents: ["d"] },
|
||||
{ id: "b", parents: ["d"] },
|
||||
{ id: "d", parents: [] },
|
||||
];
|
||||
const got = real(commits, { lanes: [...lanes], nextColor: 9 });
|
||||
const want = referenceComputeGraph(commits, { lanes: [...lanes], nextColor: 9 });
|
||||
expect(got).toEqual(want);
|
||||
});
|
||||
|
||||
it("scans a number of lane slots per row that does not depend on the highest slot number", () => {
|
||||
const chain = (rows: number): GraphCommit[] =>
|
||||
Array.from({ length: rows }, (_, i) => ({
|
||||
id: `n${i}`,
|
||||
parents: [i + 1 < rows ? `n${i + 1}` : "base"],
|
||||
refs: i === 0 ? ["main"] : [],
|
||||
}));
|
||||
/** Array elements the scans of one `computeGraph` call go over, with a lane at slot 30 000. */
|
||||
const scanned = (rows: number) => {
|
||||
const lanes: Array<{ id: string; color: number } | null> = [];
|
||||
lanes[30_000] = { id: "base", color: 1 };
|
||||
const names = ["forEach", "indexOf", "findIndex", "filter", "some", "map", "reduce", "includes"] as const;
|
||||
const original = new Map(names.map((n) => [n, Array.prototype[n]]));
|
||||
let visited = 0;
|
||||
for (const n of names)
|
||||
Object.defineProperty(Array.prototype, n, {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value(this: unknown[], ...args: unknown[]) {
|
||||
visited += this.length;
|
||||
return (original.get(n) as (...a: unknown[]) => unknown).apply(this, args);
|
||||
},
|
||||
});
|
||||
try {
|
||||
real(chain(rows), { lanes, nextColor: 0 });
|
||||
} finally {
|
||||
for (const n of names)
|
||||
Object.defineProperty(Array.prototype, n, { configurable: true, writable: true, value: original.get(n) });
|
||||
}
|
||||
return visited;
|
||||
};
|
||||
// Reading the given state costs once per call; each further row may only scan its live lanes.
|
||||
expect((scanned(400) - scanned(100)) / 300).toBeLessThan(100);
|
||||
});
|
||||
});
|
||||
|
||||
describe("presentLogGraph", () => {
|
||||
const optionCombinations: GraphOptions[] = [false, true].flatMap((collapseLinear) =>
|
||||
[false, true].flatMap((linearizeMerges) =>
|
||||
[false, true].map((longEdges) => ({ collapseLinear, linearizeMerges, longEdges })),
|
||||
),
|
||||
);
|
||||
|
||||
it.each([true, false])("keeps every option and fragment combination unchanged (refs: %s)", (withRefs) => {
|
||||
const commits = history(2400, withRefs);
|
||||
const head = new Set([commitKey(commits[0]!)]);
|
||||
const variants = fragmentVariants(commits);
|
||||
for (const options of optionCombinations)
|
||||
for (const [name, fragments] of Object.entries(variants)) {
|
||||
vi.mocked(computeGraph).mockImplementation(real);
|
||||
const got = presentLogGraph(commits, options, fragments, head);
|
||||
vi.mocked(computeGraph).mockImplementation(referenceComputeGraph);
|
||||
const want = presentLogGraph(commits, options, fragments, head);
|
||||
expect(got, `${JSON.stringify(options)} ${name}`).toEqual(want);
|
||||
}
|
||||
});
|
||||
});
|
||||
Loaded 100 of 117 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user