mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-22 23:56:05 -10:00
Compare commits
87
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4a9cf256bc | ||
|
|
a6a05caa2e | ||
|
|
4690463c53 | ||
|
|
8200ce8b5e | ||
|
|
b524f738e5 | ||
|
|
1f871dc1c2 | ||
|
|
ceb3cef1af | ||
|
|
735a0157c1 | ||
|
|
82f26202ed | ||
|
|
a90a9b20e3 | ||
|
|
aad701ba16 | ||
|
|
46d4036038 | ||
|
|
19859b4ae2 | ||
|
|
f3f05f8b15 | ||
|
|
b0417c83f4 | ||
|
|
4a5d90a91e | ||
|
|
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 | ||
|
|
4d1f51c607 | ||
|
|
2215239ecb | ||
|
|
43eeb080be | ||
|
|
03a19d4284 | ||
|
|
3aeee3fcfc | ||
|
|
471003a8c5 | ||
|
|
c109773d2a | ||
|
|
ed6b67faed | ||
|
|
ff7bfcaf1d | ||
|
|
91330a82d0 | ||
|
|
ce75c58a34 | ||
|
|
03b9070b9b | ||
|
|
f6f610516c | ||
|
|
cf49a91b66 | ||
|
|
e0a97e32f7 | ||
|
|
dd0eeeae29 | ||
|
|
4bb22df1fb | ||
|
|
aee087597a | ||
|
|
993a321dd0 | ||
|
|
381e66aca5 | ||
|
|
d7a05eea21 | ||
|
|
c61ddbff3d | ||
|
|
0c20d72cbf | ||
|
|
021f334c0c | ||
|
|
c61264cdf9 | ||
|
|
e4d6f50a0b | ||
|
|
0435e0330e | ||
|
|
13b5f9e575 | ||
|
|
dde4b28abd | ||
|
|
3817724637 | ||
|
|
26b5856ce0 | ||
|
|
6aeb733f20 | ||
|
|
29fcec6ab8 | ||
|
|
5d6c76cdda | ||
|
|
844c2f3145 |
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");
|
||||
}
|
||||
@@ -49,7 +49,7 @@ async fn external_maven_link_persists_reloads_and_unlink_keeps_files() {
|
||||
assert_eq!(b.pom, canonical);
|
||||
assert_eq!(dunce::canonicalize(root.join(&b.dir)).unwrap(), sibling);
|
||||
assert_eq!(host.project("main").unwrap().content_roots(), vec![sibling.clone()]);
|
||||
assert_eq!(host.project("main").unwrap().lsp.jdtls_import_roots(), vec![sibling.clone()]);
|
||||
assert_eq!(import_roots(&host, |roots| !roots.is_empty()).await, vec![sibling.clone()]);
|
||||
|
||||
let reloaded = ops::build::build_model(&host, "main").await.unwrap();
|
||||
assert_eq!(
|
||||
@@ -63,13 +63,27 @@ async fn external_maven_link_persists_reloads_and_unlink_keeps_files() {
|
||||
let gone = ops::build::build_model(&host, "main").await.unwrap();
|
||||
assert!(gone.maven.unwrap().projects.iter().all(|p| p.artifact_id != "b"));
|
||||
assert!(host.project("main").unwrap().content_roots().is_empty());
|
||||
assert!(host.project("main").unwrap().lsp.jdtls_import_roots().is_empty());
|
||||
assert!(import_roots(&host, |roots| roots.is_empty()).await.is_empty());
|
||||
assert_eq!(saved(), Vec::<String>::new());
|
||||
assert_eq!(std::fs::read_to_string(root.join("pom.xml")).unwrap(), a_pom);
|
||||
assert_eq!(std::fs::read_to_string(sibling.join("pom.xml")).unwrap(), b_pom);
|
||||
host.shutdown().await;
|
||||
}
|
||||
|
||||
/// The language server's Maven import roots once `ready` holds: a settings change refreshes them in
|
||||
/// 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..600 {
|
||||
let roots = host.project("main").unwrap().lsp.jdtls_import_roots();
|
||||
if ready(&roots) {
|
||||
return roots;
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_millis(25)).await;
|
||||
}
|
||||
host.project("main").unwrap().lsp.jdtls_import_roots()
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn reactor_module_beside_a_trusted_project_is_a_content_root_until_removed() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -646,7 +646,10 @@ impl LspManager {
|
||||
/// jdtls reports `ProjectStatus` when an import or project update ends (a POM
|
||||
/// change, a Maven sync, other Maven profiles), but does not check open documents
|
||||
/// again against the new classpath: their errors would stay until the next edit.
|
||||
/// Generated Maven sources are attached first, so that recheck sees them.
|
||||
/// Nor does it ask for a semantic tokens refresh: a file outside any project (its
|
||||
/// import failed, say on an unresolvable parent POM) gets no tokens, and would stay
|
||||
/// uncoloured after the import is fixed. Generated Maven sources are attached
|
||||
/// first, so the recheck and the new tokens see them.
|
||||
pub(crate) fn java_projects_updated(self: &Arc<Self>, server: Arc<Server>, generation: u64) {
|
||||
let uris: Vec<String> = self
|
||||
.docs
|
||||
@@ -663,6 +666,10 @@ impl LspManager {
|
||||
self.runtime.spawn(async move {
|
||||
let Some(run) = server.running_gen(generation) else { return };
|
||||
mgr.sync_generated_sources(&server, &run).await;
|
||||
mgr.sink().emit(ide_core::IdeEvent::LspRefresh {
|
||||
server: server.id,
|
||||
kind: ide_core::event::LspRefreshKind::SemanticTokens,
|
||||
});
|
||||
for uri in uris {
|
||||
let params =
|
||||
json!({ "command": "java.project.refreshDiagnostics", "arguments": [uri, "thisFile", false] });
|
||||
|
||||
@@ -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;
|
||||
@@ -3164,6 +3165,32 @@ async fn open_java_files_are_checked_again_after_a_project_update() {
|
||||
eventually(|| refreshed() == expected).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_project_update_refreshes_java_semantic_tokens() {
|
||||
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
|
||||
let _ = h.open("A.java", "class A { private String name; }");
|
||||
h.wait_status("jdtls", ServerStatus::Ready).await;
|
||||
let state = h.launcher.state("jdtls");
|
||||
let refreshes = || {
|
||||
h.events
|
||||
.lock()
|
||||
.iter()
|
||||
.filter(|e| matches!(e, IdeEvent::LspRefresh { kind: LspRefreshKind::SemanticTokens, .. }))
|
||||
.count()
|
||||
};
|
||||
state
|
||||
.peer()
|
||||
.notify("language/status", json!({ "type": "Message", "message": "Updating project configurations..." }))
|
||||
.unwrap();
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
assert_eq!(refreshes(), 0);
|
||||
|
||||
// jdtls answers with no tokens for a file outside any project and sends no
|
||||
// `workspace/semanticTokens/refresh` once a later import takes it in.
|
||||
state.peer().notify("language/status", json!({ "type": "ProjectStatus", "message": "OK" })).unwrap();
|
||||
eventually(|| refreshes() == 1).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_project_update_attaches_maven_generated_sources_before_rechecking() {
|
||||
let mut caps = incremental_caps();
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -1365,8 +1365,15 @@ pub fn configure_server(cfg: &mut LanguageServerConfig, root: &Path, server_root
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
// TypeScript 7 serves LSP itself: it replaces the tsserver-based server.
|
||||
let vue_command = s.tool_path(vue::SERVER).and_then(|p| setting_path(root, p));
|
||||
let vue_command = vue_command.as_deref().map_or(vue::SERVER.into(), Path::to_string_lossy);
|
||||
let vue_pkg = vue::server_package(&vue_command, &search_path());
|
||||
// TypeScript 7 serves LSP itself: it replaces the tsserver-based server, whose plugin
|
||||
// host goes away with it. The Vue language server's `@vue/typescript-plugin` loads into
|
||||
// that host, so a Vue project that has the server keeps the vtsls route and its `.vue`
|
||||
// support; elsewhere the native server still wins.
|
||||
if matches!(name, "vtsls" | "typescript-language-server")
|
||||
&& !(name == "vtsls" && vue_pkg.is_some() && (vue::vue_project(server_root) || vue::vue_project(root)))
|
||||
&& let Some(native) = native_tsdk(server_root, s).or_else(|| native_tsdk(root, s))
|
||||
{
|
||||
cfg.command = native.to_string_lossy().into_owned();
|
||||
@@ -1380,10 +1387,8 @@ pub fn configure_server(cfg: &mut LanguageServerConfig, root: &Path, server_root
|
||||
cfg.tsserver_project = false;
|
||||
return;
|
||||
}
|
||||
let vue_command = s.tool_path(vue::SERVER).and_then(|p| setting_path(root, p));
|
||||
let vue_command = vue_command.as_deref().map_or(vue::SERVER.into(), Path::to_string_lossy);
|
||||
if name == "vtsls"
|
||||
&& let Some(vue) = vue::server_package(&vue_command, &search_path())
|
||||
&& let Some(vue) = vue_pkg
|
||||
{
|
||||
let plugin = vue::tsserver_plugin(&vue);
|
||||
merge_init_options(cfg, json!({ "vtsls": { "tsserver": { "globalPlugins": [plugin] } } }));
|
||||
@@ -2453,6 +2458,56 @@ mod maven_linkage_tests {
|
||||
assert_eq!(options.pointer("/typescript/tsserver/maxTsServerMemory"), Some(&json!(6144)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typescript_7_keeps_vtsls_when_the_vue_server_is_installed() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
// The Vue server, as the hybrid block finds it through the tool's package dir.
|
||||
let bin = root.join("tools/node_modules/.bin/vue-language-server");
|
||||
let pkg = root.join("tools/node_modules/@vue/language-server/package.json");
|
||||
std::fs::create_dir_all(bin.parent().unwrap()).unwrap();
|
||||
std::fs::create_dir_all(pkg.parent().unwrap()).unwrap();
|
||||
std::fs::write(&bin, "#!/bin/sh\n").unwrap();
|
||||
std::fs::write(&pkg, "{}").unwrap();
|
||||
let mut s = Settings::default();
|
||||
s.tools
|
||||
.insert(vue::SERVER.into(), ide_core::settings::ToolSettings { path: bin.to_string_lossy().into_owned() });
|
||||
// A Vue project whose TypeScript is 7: the native executable would take over.
|
||||
std::fs::write(root.join("package.json"), r#"{"dependencies":{"vue":"^3.0.0"}}"#).unwrap();
|
||||
let modules = root.join("node_modules");
|
||||
let os = match std::env::consts::OS {
|
||||
"macos" => "darwin",
|
||||
"windows" => "win32",
|
||||
os => os,
|
||||
};
|
||||
let arch = match std::env::consts::ARCH {
|
||||
"aarch64" => "arm64",
|
||||
"x86_64" => "x64",
|
||||
arch => arch,
|
||||
};
|
||||
std::fs::create_dir_all(modules.join("typescript/lib")).unwrap();
|
||||
std::fs::write(modules.join("typescript/package.json"), r#"{"name":"typescript","version":"7.0.2"}"#).unwrap();
|
||||
let native = modules.join(format!("@typescript/typescript-{os}-{arch}/lib")).join(crate::exe("tsc"));
|
||||
std::fs::create_dir_all(native.parent().unwrap()).unwrap();
|
||||
std::fs::write(&native, "").unwrap();
|
||||
s.languages.typescript.version = "workspace".into();
|
||||
|
||||
// vtsls hosts the Vue plugin's tsserver; the native server cannot, so it loses.
|
||||
let mut cfg = crate::tests::server("vtsls");
|
||||
configure_server(&mut cfg, root, root, &s);
|
||||
assert_eq!(cfg.command, "vtsls");
|
||||
assert_eq!(
|
||||
serde_json::to_value(cfg.initialization_options).unwrap().pointer("/vtsls/tsserver/globalPlugins/0/name"),
|
||||
Some(&json!("@vue/typescript-plugin"))
|
||||
);
|
||||
assert_eq!(cfg.tsserver_project_extras.extensions, [vue::EXTENSION.to_string()]);
|
||||
|
||||
// typescript-language-server gets no plugin route: the native server still applies.
|
||||
let mut cfg = crate::tests::server("typescript-language-server");
|
||||
configure_server(&mut cfg, root, root, &s);
|
||||
assert_eq!(Path::new(&cfg.command), native);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hybrid_without_a_config_keeps_type_acquisition_and_plain_vtsls_stays_default() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -42,6 +42,16 @@ pub(crate) fn server_package(command: &str, path: &OsStr) -> Option<PathBuf> {
|
||||
package_dir(&find_command(command, path)?, PACKAGE)
|
||||
}
|
||||
|
||||
/// Whether `root`'s manifest depends on Vue or `@vue/cli-service`, i.e. it is a Vue project.
|
||||
/// The tsserver plugin host that `vtsls` carries cannot be loaded into the native TS7
|
||||
/// server, so this decides whether the tsserver route stays for a Vue project.
|
||||
pub(crate) fn vue_project(root: &Path) -> bool {
|
||||
let Ok(manifest) = std::fs::read_to_string(root.join("package.json")) else {
|
||||
return false;
|
||||
};
|
||||
package_dependencies(&manifest).iter().any(|d| d == "vue" || d == CLI_SERVICE)
|
||||
}
|
||||
|
||||
/// vtsls `globalPlugins` entry loading the Vue plugin shipped with `package`.
|
||||
pub(crate) fn tsserver_plugin(package: &Path) -> serde_json::Value {
|
||||
serde_json::json!({
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -81,6 +81,12 @@ fn npm_package(tool: &str) -> &str {
|
||||
}
|
||||
|
||||
impl Tools {
|
||||
/// The IDE's own installation of `tool` outside `node_modules` (Ruff's private virtualenv).
|
||||
fn managed_executable(&self, tool: &str) -> Option<PathBuf> {
|
||||
let spec = crate::registry::find(tool)?;
|
||||
self.exe_in(&crate::managed_bin_dir(&self.root, spec, self.platform)?, spec.commands[0])
|
||||
}
|
||||
|
||||
/// Explicit executable/script, then the nearest project package, then managed tools and PATH.
|
||||
pub fn formatter_command(&self, tool: &str, file: &Path, custom: Option<&Path>) -> IdeResult<Command> {
|
||||
self.resolve_formatter_command(tool, file, custom).map_err(|e| e.with_tool(tool))
|
||||
@@ -100,6 +106,8 @@ impl Tools {
|
||||
(package_bin(manifest.parent().unwrap(), tool)?, true)
|
||||
} else if self.root.join(&manifest).is_file() {
|
||||
(package_bin(&self.root.join(&package), tool)?, true)
|
||||
} else if let Some(path) = self.managed_executable(tool) {
|
||||
(path, false)
|
||||
} else {
|
||||
(self.which(tool).ok_or_else(|| IdeError::missing_tool(tool))?, false)
|
||||
};
|
||||
@@ -241,6 +249,20 @@ mod tests {
|
||||
assert_eq!(failure.data, Some(ErrorData::Tool { tool: "prettier".into(), missing: false }));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_formatter_the_ide_installed_in_its_virtualenv_is_found() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let tools = Tools::with_paths(dir.path().join("tools"), OsString::new(), crate::platform::Platform::current());
|
||||
let file = dir.path().join("main.py");
|
||||
assert!(tools.formatter_command("ruff", &file, None).is_err());
|
||||
let bin = dir.path().join("tools/ruff/venv/bin");
|
||||
std::fs::create_dir_all(&bin).unwrap();
|
||||
std::fs::write(bin.join("ruff"), "").unwrap();
|
||||
let command = tools.formatter_command("ruff", &file, None).unwrap();
|
||||
assert_eq!(Path::new(command.get_program()), bin.join("ruff"));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn stderr_is_preserved_verbatim_even_when_longer_than_four_thousand_characters() {
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -69,6 +69,7 @@ Long operations (pull, prune, Compose) show progress at the top with a **Cancel*
|
||||
|
||||
Selecting an item shows tabs in the detail pane:
|
||||
|
||||
- **Compose project**: **Dashboard** (project overview, services with live resource usage, named volumes created by the project).
|
||||
- **Container**: **Dashboard** (overview, live resource usage, port bindings that open in the browser, mounts, networks, environment variables, labels), **Log** (last 1,000 lines, following while the container runs, with **Timestamps**), **Processes** (`docker top`) and **Inspect** (the raw JSON).
|
||||
- **Image**: **Dashboard** (tags, containers using it, environment, labels), **Layers** and **Inspect**.
|
||||
- **Volume** and **network**: **Dashboard** and **Inspect**.
|
||||
|
||||
@@ -69,6 +69,7 @@ OpenIDEA 通过 `docker` 命令行操作 Docker,所以只要能提供可用的
|
||||
|
||||
选中某项后,详情区会显示以下标签页:
|
||||
|
||||
- **Compose 项目**:**仪表盘**(项目概览、各服务的实时资源使用情况、该项目创建的命名卷)。
|
||||
- **容器**:**仪表盘**(概览、实时资源使用情况、可在浏览器中打开的端口绑定、挂载、网络、环境变量、标签)、**日志**(最近 1,000 行,容器运行时持续跟随,可切换 **时间戳**)、**进程**(`docker top`)和 **检查**(原始 JSON)。
|
||||
- **镜像**:**仪表盘**(标签、使用它的容器、环境变量、标签)、**镜像层** 和 **检查**。
|
||||
- **卷** 和 **网络**:**仪表盘** 和 **检查**。
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import type { EditorView } from "@codemirror/view";
|
||||
import { expect, stubDesktop, test } from "./fixtures";
|
||||
|
||||
test("gutter breakpoint keeps its location and buttons visible while editing in a short window", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 410, height: 340 });
|
||||
await stubDesktop(page);
|
||||
const name = "RecalculateInternationalPaymentsAcrossMultipleRegionalSettlementCyclesAndVerifyReceiptTotals.ts";
|
||||
const path = `/dev/acme-api/${name}`;
|
||||
await page.evaluate(async (path) => {
|
||||
const contributionsModule = "/src/workbench/contributions.ts";
|
||||
const { editorService } = await import(/* @vite-ignore */ contributionsModule);
|
||||
await editorService().openFile(path);
|
||||
}, path);
|
||||
await page.locator(".cm-content").evaluate(async (editor, path) => {
|
||||
const view = (editor as HTMLElement & { cmTile: { view: EditorView } }).cmTile.view;
|
||||
const insert = Array.from({ length: 14 }, (_, i) => `const amount${i + 1} = ${i * 10};`).join("\n");
|
||||
view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert } });
|
||||
const breakpointsModule = "/src/features/debugger/breakpoints/store.ts";
|
||||
const { addBreakpoint } = await import(/* @vite-ignore */ breakpointsModule);
|
||||
window.__ipc.handlers.debug_set_breakpoints = () => [];
|
||||
addBreakpoint(path, 7, { condition: "amount8 > 50", hitCondition: ">= 3", logMessage: "amount: {amount8}" });
|
||||
}, path);
|
||||
const marker = page.locator(".cm-lineNumbers .cm-gutterElement").filter({ hasText: /^8$/ });
|
||||
const open = () => marker.click({ button: "right" });
|
||||
await open();
|
||||
|
||||
const popup = page.getByRole("dialog", { name: "Breakpoint properties" });
|
||||
const done = popup.getByRole("button", { name: "Done", exact: true });
|
||||
const condition = popup.getByLabel("Condition", { exact: true });
|
||||
await expect(condition).toBeFocused();
|
||||
await expect(done).toBeInViewport({ ratio: 1 });
|
||||
const location = popup.getByTitle(`${path}:8`, { exact: true });
|
||||
await expect(location.getByText(":8", { exact: true })).toBeInViewport({ ratio: 1 });
|
||||
await expect(popup.getByText("Condition", { exact: true })).toHaveCSS("font-size", "13px");
|
||||
|
||||
await condition.fill("amount8 > 60");
|
||||
const log = popup.getByRole("textbox", { name: "Evaluate and log", exact: true });
|
||||
await log.fill("paid: {amount8}");
|
||||
await expect(location).toBeInViewport({ ratio: 1 });
|
||||
await expect(done).toBeInViewport({ ratio: 1 });
|
||||
await done.click();
|
||||
await expect(popup).toBeHidden();
|
||||
|
||||
await open();
|
||||
await expect(condition).toHaveValue("amount8 > 60");
|
||||
await expect(log).toHaveValue("paid: {amount8}");
|
||||
await popup.getByRole("button", { name: /^More/ }).click();
|
||||
const dialog = page.getByRole("dialog", { name: "Breakpoints", exact: true });
|
||||
await expect(dialog.getByLabel("Condition", { exact: true })).toHaveValue("amount8 > 60");
|
||||
});
|
||||
@@ -1,8 +1,8 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import { expect, test } from "./fixtures";
|
||||
|
||||
async function showBuild(page: Page) {
|
||||
await page.evaluate(async () => {
|
||||
async function showBuild(page: Page, diagnosticPath: string | null = null) {
|
||||
await page.evaluate(async (path) => {
|
||||
const storePath = "/src/features/build/store.ts";
|
||||
const layoutPath = "/src/workbench/toolwindows/store.ts";
|
||||
const { useBuildRun } = await import(/* @vite-ignore */ storePath);
|
||||
@@ -17,10 +17,10 @@ async function showBuild(page: Page) {
|
||||
{ kind: "out", text: "Compiling TypeScript" },
|
||||
{ kind: "err", text: "Expected a number" },
|
||||
],
|
||||
messages: [{ severity: "error", text: "Expected a number", path: null, range: null, code: null }],
|
||||
messages: [{ severity: "error", text: "Expected a number", path, range: null, code: null }],
|
||||
});
|
||||
showToolWindow("build", true);
|
||||
});
|
||||
}, diagnosticPath);
|
||||
const build = page.getByRole("region", { name: "Build", exact: true });
|
||||
await expect(build.getByRole("log", { name: "Build output" })).toBeVisible();
|
||||
return build;
|
||||
@@ -35,6 +35,28 @@ test("Build gives about two thirds of the initial split to output", async ({ wor
|
||||
expect(treeWidth / (treeWidth + consoleWidth)).toBeCloseTo(0.33, 2);
|
||||
});
|
||||
|
||||
test("Build reserves room for duration and file counts beside long directory paths", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 760, height: 680 });
|
||||
const path = "/dev/acme-api/src/services/regional-catalogs/generated/api/development/builders/catalog.ts";
|
||||
const build = await showBuild(page, path);
|
||||
const root = build.getByRole("treeitem", { name: /^Build Project/ });
|
||||
const filename = build.getByTitle(path, { exact: true }).getByText("catalog.ts", { exact: true });
|
||||
const counts = build.getByTitle(path, { exact: true }).getByText("1 error", { exact: true });
|
||||
const errorSummary = root.getByText("1 error", { exact: true });
|
||||
const elapsed = root.getByText("1 s 200 ms", { exact: true });
|
||||
await expect(elapsed).toHaveCSS("font-size", "12px");
|
||||
await expect(counts).toBeInViewport({ ratio: 1 });
|
||||
const textFits = (el: Element) => {
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(el);
|
||||
return range.getBoundingClientRect().width <= el.getBoundingClientRect().width;
|
||||
};
|
||||
expect(await filename.evaluate(textFits)).toBe(true);
|
||||
expect(await errorSummary.evaluate(textFits)).toBe(true);
|
||||
const [duration, row] = await Promise.all([elapsed.boundingBox(), root.boundingBox()]);
|
||||
expect(row!.x + row!.width - duration!.x - duration!.width).toBeLessThan(12);
|
||||
});
|
||||
|
||||
test("Build output and diagnostics respond to a console font change", async ({ workbench: page }) => {
|
||||
const build = await showBuild(page);
|
||||
const log = build.getByRole("log", { name: "Build output" });
|
||||
|
||||
@@ -111,6 +111,7 @@ test("completion lists the server's items and inserts the chosen one", async ({
|
||||
});
|
||||
await expect(editor.locator(".cm-content")).toHaveCSS("font-size", zoomedSize);
|
||||
await expect(method.locator(".cm-completionLabel")).toHaveCSS("font-size", zoomedSize);
|
||||
|
||||
await page.keyboard.type("toD");
|
||||
await expect(popup.getByText("total", { exact: true })).toBeHidden();
|
||||
// Refreshing the results rebuilds the list; the hint bar must stay below it, not jump to the top.
|
||||
@@ -124,6 +125,37 @@ test("completion lists the server's items and inserts the chosen one", async ({
|
||||
await expect(popup).toBeHidden();
|
||||
await expect(editor.locator(".cm-activeLine")).toHaveText(/^\s*order\.toDto\(\)$/);
|
||||
expect((await ipcCalls(page, "lsp_completion")).length).toBeGreaterThan(0);
|
||||
|
||||
await page.evaluate(async () => {
|
||||
const path = "/src/platform/actions.ts";
|
||||
await (await import(/* @vite-ignore */ path)).executeAction("editor.splitRight");
|
||||
});
|
||||
const panes = page.locator("[data-pane-id]");
|
||||
await expect(panes).toHaveCount(2);
|
||||
await page.setViewportSize({ width: 480, height: 760 });
|
||||
await panes.last().locator(".cm-content").focus();
|
||||
await page.keyboard.press("End");
|
||||
await page.keyboard.press("Enter");
|
||||
await page.keyboard.type("order.");
|
||||
await page.keyboard.press("Control+Space");
|
||||
const footer = popup.locator(".cm-lsp-completion-footer");
|
||||
await expect
|
||||
.poll(() =>
|
||||
footer.evaluate((el) => {
|
||||
const tip = el.querySelector("span")!;
|
||||
const sort = el.querySelector("button")!;
|
||||
const a = tip.getBoundingClientRect();
|
||||
const b = sort.getBoundingClientRect();
|
||||
return {
|
||||
oneRow: Math.abs(a.y + a.height / 2 - b.y - b.height / 2) <= 1,
|
||||
hintClipped: tip.scrollWidth > tip.clientWidth,
|
||||
sortFits: sort.scrollWidth <= sort.clientWidth + 1 && b.right <= el.getBoundingClientRect().right,
|
||||
};
|
||||
}),
|
||||
)
|
||||
.toEqual({ oneRow: true, hintClipped: true, sortFits: true });
|
||||
await expect(footer.getByTitle("Press ↵ to insert, ⇥ to replace")).toHaveCSS("font-size", "12px");
|
||||
await expect(footer.getByRole("button", { name: "Sort by name" })).toBeInViewport({ ratio: 1 });
|
||||
});
|
||||
|
||||
test("long completion signatures fit the editor when the workbench is narrowed", async ({ workbench: page }) => {
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
import { expect, test } from "./fixtures";
|
||||
|
||||
test("the editor color picker fits recent colors and keeps its actions visible", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 980, height: 720 });
|
||||
await page.evaluate(async () => {
|
||||
const recent = Array.from({ length: 20 }, (_, i) => `#${((i + 1) * 314241).toString(16).padStart(6, "0")}ff`);
|
||||
localStorage.setItem("openidea.colorPicker.recent.v1", JSON.stringify(recent));
|
||||
const contributions = "/src/workbench/contributions.ts";
|
||||
const { editorService } = await import(/* @vite-ignore */ contributions);
|
||||
await editorService().openFile("/dev/acme-api/theme.css");
|
||||
});
|
||||
const editor = page.locator(".cm-editor").first();
|
||||
const contents = editor.locator(".cm-content");
|
||||
await contents.click();
|
||||
await page.keyboard.press("Meta+a");
|
||||
await page.keyboard.insertText(".notice { color: #5a8fbd; }");
|
||||
|
||||
const swatch = editor.locator(".cm-openidea-gutter-colors").getByTitle("#5a8fbd", { exact: true });
|
||||
const picker = page.getByRole("dialog", { name: "Color picker", exact: true });
|
||||
const palette = picker.locator(".react-colorful__saturation");
|
||||
const hex = picker.getByRole("textbox", { name: "Hexadecimal", exact: true });
|
||||
const apply = picker.getByRole("button", { name: "Apply", exact: true });
|
||||
const cancel = picker.getByRole("button", { name: "Cancel", exact: true });
|
||||
const recent = picker.getByRole("group", { name: "Recent colors", exact: true }).getByRole("button");
|
||||
await swatch.click();
|
||||
await expect(hex).toHaveValue("5A8FBDFF");
|
||||
expect((await picker.boundingBox())!.width).toBeLessThanOrEqual(308);
|
||||
await expect(palette).toHaveCSS("height", "152px");
|
||||
expect(await picker.evaluate((el) => el.scrollWidth - el.clientWidth)).toBe(0);
|
||||
await hex.fill("#ff0000");
|
||||
expect(await picker.evaluate((el) => el.scrollWidth - el.clientWidth)).toBe(0);
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(picker).toBeHidden();
|
||||
|
||||
await page.setViewportSize({ width: 280, height: 315 });
|
||||
await swatch.click();
|
||||
await expect(recent).toHaveCount(20);
|
||||
const swatchRows = await recent.evaluateAll((elements) => {
|
||||
const rows: number[] = [];
|
||||
for (const element of elements) {
|
||||
const box = element.getBoundingClientRect();
|
||||
if (!rows.includes(box.top)) rows.push(box.top);
|
||||
const previous = element.previousElementSibling?.getBoundingClientRect();
|
||||
if (previous?.top === box.top && previous.right > box.left) throw new Error("Color swatches overlap");
|
||||
}
|
||||
return rows.length;
|
||||
});
|
||||
expect(swatchRows).toBeGreaterThan(2);
|
||||
expect(await picker.evaluate((el) => el.scrollWidth - el.clientWidth)).toBe(0);
|
||||
await expect(apply).toBeInViewport({ ratio: 1 });
|
||||
await expect(cancel).toBeInViewport({ ratio: 1 });
|
||||
await hex.fill("#d27c54");
|
||||
await cancel.click();
|
||||
await expect(picker).toBeHidden();
|
||||
await expect(contents).toContainText("#5a8fbd");
|
||||
|
||||
await swatch.click();
|
||||
await hex.fill("#d27c54");
|
||||
await apply.click();
|
||||
await expect(picker).toBeHidden();
|
||||
await expect(contents).toContainText("#d27c54");
|
||||
});
|
||||
+163
-10
@@ -780,6 +780,81 @@ test("Commit Options applies a named TODO filter independently of the TODO windo
|
||||
expect(await ipcCalls(page, "vcs_commit")).toEqual([]);
|
||||
});
|
||||
|
||||
test("commit check text scrolls independently of its status icon and retry action", async ({ workbench: page }) => {
|
||||
await stubRepository(page);
|
||||
await page.setViewportSize({ width: 850, height: 650 });
|
||||
await page.evaluate(async () => {
|
||||
const registryPath = "/src/features/vcs/commitCheckRegistry.ts";
|
||||
const layoutPath = "/src/workbench/toolwindows/store.ts";
|
||||
const { registerCommitCheck } = await import(/* @vite-ignore */ registryPath);
|
||||
const layout = await import(/* @vite-ignore */ layoutPath);
|
||||
layout.moveToolWindow("commit", "left");
|
||||
layout.setToolWindowSize("left", 238);
|
||||
for (let index = 0; index < 6; index++) {
|
||||
registerCommitCheck({
|
||||
id: `test.commitLayout.${index}`,
|
||||
order: index - 1000,
|
||||
title: `Ledger check ${index + 1}`,
|
||||
run: () => {
|
||||
if (index === 0) document.body.dataset.checkRuns = String(Number(document.body.dataset.checkRuns ?? 0) + 1);
|
||||
return {
|
||||
severity: "error",
|
||||
text: "The regional settlement totals differ from the monthly inventory audit and need a second review.",
|
||||
fix:
|
||||
index === 5
|
||||
? {
|
||||
label: "Review final check",
|
||||
run: () => {
|
||||
document.body.dataset.commitCheckReviewed = "yes";
|
||||
},
|
||||
}
|
||||
: undefined,
|
||||
};
|
||||
},
|
||||
});
|
||||
}
|
||||
});
|
||||
await page.keyboard.press("Meta+k");
|
||||
const commit = page.getByRole("region", { name: "Commit", exact: true });
|
||||
await commit.getByRole("textbox", { name: "Commit message" }).fill("Review the settlement totals");
|
||||
await commit.getByRole("button", { name: "Commit Options", exact: true }).click();
|
||||
const options = page.getByRole("dialog", { name: "Commit Options", exact: true });
|
||||
await options.getByRole("button", { name: "Run Commit Checks", exact: true }).click();
|
||||
|
||||
const feedback = commit.getByRole("alert").filter({ hasText: "Ledger check 1" });
|
||||
const first = feedback.getByText("Ledger check 1", { exact: true });
|
||||
const second = feedback.getByText("Ledger check 2", { exact: true });
|
||||
const results = first.locator("../..");
|
||||
const icon = feedback.locator("svg").first();
|
||||
const retry = commit.getByRole("button", { name: "Rerun Commit Checks", exact: true });
|
||||
const commitAnyway = commit.getByRole("button", { name: "Commit Anyway", exact: true });
|
||||
await expect(commitAnyway).toBeInViewport({ ratio: 1 });
|
||||
await expect(first).toHaveCSS("font-size", "13px");
|
||||
const firstRow = (await first.locator("..").boundingBox())!;
|
||||
const secondRow = (await second.locator("..").boundingBox())!;
|
||||
expect(secondRow.y - (firstRow.y + firstRow.height)).toBeCloseTo(4, 0);
|
||||
expect(await results.evaluate((node) => node.scrollHeight > node.clientHeight)).toBe(true);
|
||||
const statusTop = (await icon.boundingBox())!.y;
|
||||
const retryTop = (await retry.boundingBox())!.y;
|
||||
await results.evaluate((node) => {
|
||||
node.scrollTop = node.scrollHeight;
|
||||
});
|
||||
expect(await results.evaluate((node) => node.scrollTop)).toBeGreaterThan(0);
|
||||
expect((await icon.boundingBox())!.y).toBeCloseTo(statusTop, 0);
|
||||
expect((await retry.boundingBox())!.y).toBeCloseTo(retryTop, 0);
|
||||
const details = feedback.getByRole("button", { name: "Review final check", exact: true });
|
||||
await expect(details).toBeInViewport({ ratio: 1 });
|
||||
await expect(icon).toBeInViewport({ ratio: 1 });
|
||||
await expect(retry).toBeInViewport({ ratio: 1 });
|
||||
await expect(commitAnyway).toBeInViewport({ ratio: 1 });
|
||||
await details.click();
|
||||
await expect(page.locator("body")).toHaveAttribute("data-commit-check-reviewed", "yes");
|
||||
await retry.click();
|
||||
await expect(page.locator("body")).toHaveAttribute("data-check-runs", "2");
|
||||
await expect(first).toBeVisible();
|
||||
expect(await ipcCalls(page, "vcs_commit")).toEqual([]);
|
||||
});
|
||||
|
||||
test("the TODO check reports unreadable files and can retry after they become available", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
@@ -1084,27 +1159,51 @@ test("the Commit tool window restores the draft and author options for the inclu
|
||||
await expect(message).toHaveValue("Default draft");
|
||||
});
|
||||
|
||||
test("commit message history opens above the message without an empty icon column", async ({ workbench: page }) => {
|
||||
test("commit message history shows compact message previews above the editor", async ({ workbench: page }) => {
|
||||
await page.emulateMedia({ reducedMotion: "reduce" });
|
||||
await stubRepository(page);
|
||||
await page.keyboard.press("Meta+k");
|
||||
const message = page.getByRole("textbox", { name: "Commit message" });
|
||||
await expect(message).toBeVisible();
|
||||
await page.evaluate((root) => {
|
||||
localStorage.setItem(`openidea.vcs.commitMessages:${root}`, JSON.stringify(["Previous commit message"]));
|
||||
localStorage.setItem(
|
||||
`openidea.vcs.commitMessages:${root}`,
|
||||
JSON.stringify([
|
||||
"Update inventory\n\nReview settlement totals",
|
||||
"Update inventory\n\nReconcile export records",
|
||||
...Array.from({ length: 7 }, (_, index) => `Earlier message ${index + 1}`),
|
||||
]),
|
||||
);
|
||||
}, ROOT);
|
||||
await message.fill("Draft");
|
||||
await page.getByRole("button", { name: "Commit Message History" }).click();
|
||||
const history = page.getByRole("button", { name: "Commit Message History" });
|
||||
await history.click();
|
||||
|
||||
const menu = page.getByRole("menu", { name: "Recent commit messages" });
|
||||
const row = menu.getByRole("menuitem", { name: "Previous commit message" });
|
||||
const row = menu.getByRole("menuitem", { name: /Update inventory.*Review settlement totals/ });
|
||||
await expect(row).toBeVisible();
|
||||
const messageBox = await message.boundingBox();
|
||||
const menuBox = await menu.locator("..").boundingBox();
|
||||
expect(messageBox).not.toBeNull();
|
||||
expect(menuBox).not.toBeNull();
|
||||
expect(menuBox!.y + menuBox!.height).toBeLessThan(messageBox!.y);
|
||||
expect(Math.abs(menuBox!.x - messageBox!.x)).toBeLessThan(2);
|
||||
const messageBox = (await message.boundingBox())!;
|
||||
const menuBox = (await menu.locator("..").boundingBox())!;
|
||||
const rowBox = (await row.boundingBox())!;
|
||||
expect(messageBox.y - menuBox.y - menuBox.height).toBeCloseTo(3, 0);
|
||||
expect(Math.abs(menuBox.x - messageBox.x)).toBeLessThan(2);
|
||||
expect(menuBox.height).toBeLessThan(rowBox.height * 8);
|
||||
await expect(row).toHaveCSS("font-family", await message.evaluate((el) => getComputedStyle(el).fontFamily));
|
||||
await expect(row).toHaveCSS("font-size", await message.evaluate((el) => getComputedStyle(el).fontSize));
|
||||
await expect(row.locator("span")).toHaveCount(1);
|
||||
|
||||
await row.press("Escape");
|
||||
await expect(menu).toBeHidden();
|
||||
await expect(message).toHaveValue("Draft");
|
||||
await history.click();
|
||||
await row.press("Home");
|
||||
await expect(row).toBeFocused();
|
||||
await page.keyboard.press("ArrowDown");
|
||||
const second = menu.getByRole("menuitem", { name: /Update inventory.*Reconcile export records/ });
|
||||
await expect(second).toBeFocused();
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(message).toHaveValue("Update inventory\n\nReconcile export records");
|
||||
await expect(message).toBeFocused();
|
||||
});
|
||||
|
||||
test("Amend shows the original author and warns when the committer differs", async ({ workbench: page }) => {
|
||||
@@ -1215,6 +1314,60 @@ async function stubEarlierAmend(page: Page) {
|
||||
});
|
||||
}
|
||||
|
||||
test("Amend sizes the chooser for long subjects while keeping the last commit action distinct", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await stubEarlierAmend(page);
|
||||
const tip = "Record regional settlement adjustments across the quarterly audit and reconciliation reports";
|
||||
const earlier = "Expand the warehouse reconciliation report with monthly ledger and inventory audit totals";
|
||||
await page.evaluate(
|
||||
({ tip, earlier }) => {
|
||||
const handlers = window.__ipc.handlers;
|
||||
const log = handlers.vcs_log!;
|
||||
handlers.vcs_log = (args) =>
|
||||
(log(args) as { id: string; summary: string; message: string }[]).map((commit) => {
|
||||
const subject = commit.id === "1111111" ? tip : commit.id === "aaaaaaa" ? earlier : commit.summary;
|
||||
return { ...commit, summary: subject, message: subject };
|
||||
});
|
||||
},
|
||||
{ tip, earlier },
|
||||
);
|
||||
await page.setViewportSize({ width: 1040, height: 700 });
|
||||
await page.keyboard.press("Meta+k");
|
||||
const panel = page.getByRole("region", { name: "Commit", exact: true });
|
||||
const choose = panel.getByRole("button", { name: "Choose Commit to Amend", exact: true });
|
||||
await choose.click();
|
||||
const list = page.getByRole("listbox", { name: "Choose Commit to Amend", exact: true });
|
||||
const popup = list.locator("xpath=ancestor::*[@data-popup]");
|
||||
const search = popup.getByRole("textbox", { name: "Search commits", exact: true });
|
||||
const last = list.getByRole("option", { name: /^Amend Last Commit/ });
|
||||
const previous = list.getByRole("option", { name: earlier, exact: true });
|
||||
|
||||
await expect(previous).toBeVisible();
|
||||
const wide = (await popup.boundingBox())!;
|
||||
expect(wide.width).toBeGreaterThan(360);
|
||||
expect(wide.width).toBeLessThanOrEqual(522);
|
||||
await expect(last.getByText("Amend Last Commit", { exact: true })).toHaveCSS("font-weight", "600");
|
||||
await expect(last.getByText(tip, { exact: true })).toHaveAttribute("title", tip);
|
||||
await expect(previous.getByText(earlier, { exact: true })).toHaveAttribute("title", earlier);
|
||||
|
||||
await page.setViewportSize({ width: 440, height: 520 });
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const box = (await popup.boundingBox())!;
|
||||
return box.x >= 0 && box.x + box.width <= 440 && box.width < wide.width;
|
||||
})
|
||||
.toBe(true);
|
||||
await expect(search).toBeFocused();
|
||||
await search.fill("inventory audit");
|
||||
await expect(previous).toBeVisible();
|
||||
await search.press("Enter");
|
||||
await expect(list).toBeHidden();
|
||||
await page.setViewportSize({ width: 1040, height: 700 });
|
||||
await page.keyboard.press("Meta+k");
|
||||
await expect(panel.getByRole("textbox", { name: "Commit message" })).toHaveValue(earlier);
|
||||
});
|
||||
|
||||
test("Amend can select an earlier commit before protected history", async ({ workbench: page }) => {
|
||||
await stubEarlierAmend(page);
|
||||
await page.keyboard.press("Meta+k");
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import { expect, stubDesktop, test } from "./fixtures";
|
||||
import type { Page } from "@playwright/test";
|
||||
import { expect, PROJECT, stubDesktop, test } from "./fixtures";
|
||||
|
||||
test("Coverage keeps sortable statistics aligned next to the file tree at sidebar widths", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
async function importCoverage(page: Page, width: number) {
|
||||
await page.setViewportSize({ width: 1050, height: 550 });
|
||||
await expect(page.getByRole("tree", { name: "Project" }).getByRole("treeitem", { name: PROJECT })).toBeVisible();
|
||||
await expect(page.locator("#splash")).toHaveCount(0);
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async () => {
|
||||
await page.evaluate(async (width) => {
|
||||
const projectModule = "/src/platform/project.ts";
|
||||
const actionsModule = "/src/platform/actions.ts";
|
||||
const layoutModule = "/src/workbench/toolwindows/store.ts";
|
||||
@@ -26,10 +27,15 @@ test("Coverage keeps sortable statistics aligned next to the file tree at sideba
|
||||
hasBranches: path === "/tmp/coverage.lcov",
|
||||
files,
|
||||
});
|
||||
setToolWindowSize("right", 280);
|
||||
setToolWindowSize("right", width);
|
||||
await executeAction("coverage.importReport", "/tmp/coverage.lcov");
|
||||
});
|
||||
}, width);
|
||||
}
|
||||
|
||||
test("Coverage keeps sortable statistics aligned next to the file tree at sidebar widths", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await importCoverage(page, 280);
|
||||
const coverage = page.getByRole("region", { name: "Coverage", exact: true });
|
||||
const tree = coverage.getByRole("tree", { name: "Coverage" });
|
||||
const line = coverage.getByRole("columnheader", { name: "Line, %" });
|
||||
@@ -70,3 +76,58 @@ test("Coverage keeps sortable statistics aligned next to the file tree at sideba
|
||||
await expect(line).toBeVisible();
|
||||
expect((await ready.getByTitle("100% (20/20)").boundingBox())!.x).toBeCloseTo((await line.boundingBox())!.x, 0);
|
||||
});
|
||||
|
||||
test("Coverage column widths follow the dividers and survive a narrower dock and reload", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await importCoverage(page, 460);
|
||||
const coverage = page.getByRole("region", { name: "Coverage", exact: true });
|
||||
const line = coverage.getByRole("columnheader", { name: "Line, %" });
|
||||
const branch = coverage.getByRole("columnheader", { name: "Branch, %" });
|
||||
const lineDivider = coverage.getByRole("separator", { name: "Resize Line, % column" });
|
||||
const branchDivider = coverage.getByRole("separator", { name: "Resize Branch, % column" });
|
||||
const ready = coverage.getByRole("treeitem", { name: /^Ready\.ts/ });
|
||||
const nameHeader = coverage.getByRole("columnheader", { name: "Element" });
|
||||
await expect(lineDivider).toBeVisible();
|
||||
const width = async (loc: typeof line) => (await loc.boundingBox())!.width;
|
||||
const originalLine = await width(line);
|
||||
const originalBranch = await width(branch);
|
||||
const originalName = await width(nameHeader);
|
||||
const drag = (await lineDivider.boundingBox())!;
|
||||
await page.mouse.move(drag.x + drag.width / 2, drag.y + drag.height / 2);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(drag.x + drag.width / 2 + 32, drag.y + drag.height / 2, { steps: 4 });
|
||||
await page.mouse.up();
|
||||
await expect.poll(() => width(line)).toBeCloseTo(originalLine - 32, 0);
|
||||
await expect.poll(() => width(nameHeader)).toBeCloseTo(originalName + 32, 0);
|
||||
await expect.poll(() => width(branch)).toBeCloseTo(originalBranch, 0);
|
||||
await expect(line).toHaveAttribute("aria-sort", "none");
|
||||
|
||||
await branchDivider.press("ArrowRight");
|
||||
await expect.poll(() => width(branch)).toBeCloseTo(originalBranch - 10, 0);
|
||||
await expect.poll(() => width(line)).toBeCloseTo(originalLine - 22, 0);
|
||||
expect((await ready.getByTitle("100% (20/20)").boundingBox())!.x).toBeCloseTo((await line.boundingBox())!.x, 0);
|
||||
|
||||
const resizeDock = (size: number) =>
|
||||
page.evaluate(async (size) => {
|
||||
const layoutModule = "/src/workbench/toolwindows/store.ts";
|
||||
const { setToolWindowSize } = await import(/* @vite-ignore */ layoutModule);
|
||||
setToolWindowSize("right", size);
|
||||
}, size);
|
||||
await resizeDock(240);
|
||||
await expect.poll(() => width(line)).toBeLessThan(originalLine - 22);
|
||||
const tree = coverage.getByRole("tree", { name: "Coverage" });
|
||||
await expect.poll(() => tree.evaluate((el) => el.scrollWidth - el.clientWidth)).toBe(0);
|
||||
await expect(branchDivider).toBeInViewport({ ratio: 1 });
|
||||
await resizeDock(460);
|
||||
await expect.poll(() => width(line)).toBeCloseTo(originalLine - 22, 0);
|
||||
await expect.poll(() => width(branch)).toBeCloseTo(originalBranch - 10, 0);
|
||||
|
||||
await page.reload();
|
||||
await importCoverage(page, 460);
|
||||
await expect.poll(() => width(line)).toBeCloseTo(originalLine - 22, 0);
|
||||
await expect.poll(() => width(branch)).toBeCloseTo(originalBranch - 10, 0);
|
||||
await branchDivider.dblclick();
|
||||
await expect.poll(() => width(line)).toBeCloseTo(originalLine, 0);
|
||||
await expect.poll(() => width(branch)).toBeCloseTo(originalBranch, 0);
|
||||
});
|
||||
@@ -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,106 @@
|
||||
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
|
||||
|
||||
const className = "com.example.billing.SettlementSnapshot";
|
||||
const amountField = "crossBorderSettlementAmountInMinorUnitsBeforeExchangeRateAdjustment";
|
||||
const amount = "125486.75";
|
||||
const referenceField = "externalSettlementProcessorReconciliationReferenceForMonthlyReport";
|
||||
const reference = "EU-West / settlement batch 701 / reconciliation complete";
|
||||
|
||||
test("Memory Instances leaves room for field values and referrer actions in a narrow dock", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 1180, height: 720 });
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(
|
||||
async ({ className, amountField, amount, referenceField, reference }) => {
|
||||
const debugModule = "/src/features/debugger/state.ts";
|
||||
const layoutModule = "/src/workbench/toolwindows/store.ts";
|
||||
const { adoptSession } = await import(/* @vite-ignore */ debugModule);
|
||||
const { moveToolWindow, setToolWindowSize, showToolWindow } = await import(/* @vite-ignore */ layoutModule);
|
||||
const h = window.__ipc.handlers;
|
||||
h.debug_jvm_memory_classes = () => ({
|
||||
status: "ready",
|
||||
snapshot: {
|
||||
rows: [{ name: className, instances: 1, bytes: 48, deltaInstances: null, deltaBytes: null, module: null }],
|
||||
totalInstances: 1,
|
||||
totalBytes: 48,
|
||||
hasBaseline: false,
|
||||
elapsedMs: 2,
|
||||
source: "debugger",
|
||||
javaVersion: "21",
|
||||
takenWhileSuspended: true,
|
||||
},
|
||||
});
|
||||
h.debug_jvm_memory_instances = () => ({
|
||||
status: "ready",
|
||||
generation: 1,
|
||||
instances: [{ kind: "object", typeName: className, id: 12 }],
|
||||
truncated: false,
|
||||
});
|
||||
h.debug_jvm_memory_fields = ({ object }) => ({
|
||||
status: "ready",
|
||||
fields:
|
||||
(object as { id: number }).id === 12
|
||||
? [
|
||||
{ name: amountField, value: { kind: "primitive", typeName: "double", text: amount } },
|
||||
{ name: referenceField, value: { kind: "string", text: reference, length: reference.length, id: 16 } },
|
||||
]
|
||||
: [],
|
||||
});
|
||||
h.debug_jvm_memory_referrers = () => ({
|
||||
status: "ready",
|
||||
referrers: [{ value: { kind: "object", id: 12, typeName: className }, via: [referenceField] }],
|
||||
truncated: false,
|
||||
});
|
||||
adoptSession(91, {
|
||||
name: "Billing Service",
|
||||
adapter: "java-debug",
|
||||
status: "paused",
|
||||
stops: 1,
|
||||
caps: { jvmMemory: true, jvmInstances: true },
|
||||
});
|
||||
moveToolWindow("debug", "right");
|
||||
setToolWindowSize("right", 330);
|
||||
showToolWindow("debug", true);
|
||||
},
|
||||
{ className, amountField, amount, referenceField, reference },
|
||||
);
|
||||
|
||||
const debug = page.getByRole("region", { name: "Debug", exact: true });
|
||||
await debug.getByRole("tab", { name: "Memory", exact: true }).click();
|
||||
await debug.getByRole("row").filter({ hasText: className }).dblclick();
|
||||
const title = `Instances of ${className}`;
|
||||
const instances = debug.getByRole("region", { name: title, exact: true });
|
||||
const tree = instances.getByRole("tree", { name: title });
|
||||
const root = tree.getByRole("treeitem", { name: /SettlementSnapshot@12/ });
|
||||
await root.locator("[data-tree-toggle]").click();
|
||||
|
||||
const fieldName = instances.getByText(amountField, { exact: true });
|
||||
const fieldValue = instances.getByText(amount, { exact: true });
|
||||
const fits = (el: Element) => el.clientWidth > 0 && el.scrollWidth <= el.clientWidth + 1;
|
||||
await expect.poll(() => fieldValue.evaluate(fits)).toBe(true);
|
||||
await expect.poll(() => fieldName.evaluate(fits)).toBe(false);
|
||||
await expect(fieldName).toHaveAttribute("title", amountField);
|
||||
await expect(fieldValue).toHaveAttribute("title", amount);
|
||||
await expect(instances.getByText(title, { exact: true })).toHaveCSS(
|
||||
"font-family",
|
||||
await instances.evaluate((el) => getComputedStyle(el).fontFamily),
|
||||
);
|
||||
|
||||
const referrerRow = tree.getByRole("treeitem").filter({ hasText: referenceField });
|
||||
const showReferrers = referrerRow.getByRole("button", { name: "Show Referrers" });
|
||||
await referrerRow.hover();
|
||||
await expect(showReferrers).toBeInViewport({ ratio: 1 });
|
||||
await showReferrers.press("Enter");
|
||||
await expect(tree.getByText("Referrers", { exact: true })).toBeVisible();
|
||||
expect(await ipcCalls(page, "debug_jvm_memory_referrers")).toHaveLength(1);
|
||||
|
||||
await page.evaluate(async () => {
|
||||
const layoutModule = "/src/workbench/toolwindows/store.ts";
|
||||
const { moveToolWindow, setToolWindowSize } = await import(/* @vite-ignore */ layoutModule);
|
||||
moveToolWindow("debug", "bottom");
|
||||
setToolWindowSize("bottom", 400);
|
||||
});
|
||||
await expect.poll(() => fieldName.evaluate(fits)).toBe(true);
|
||||
await expect.poll(() => fieldValue.evaluate(fits)).toBe(true);
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
@@ -629,6 +629,91 @@ test("single-line selection stays on its own row when font glyphs exceed line he
|
||||
expect(Math.abs(selBox!.height - lineBox!.height)).toBeLessThanOrEqual(1);
|
||||
});
|
||||
|
||||
test("find and occurrence highlights stay on their own row when font glyphs exceed line height", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.evaluate(async () => {
|
||||
const projectModule = "/src/platform/project.ts";
|
||||
const schemaModule = "/src/features/settings/model/schema.ts";
|
||||
const [{ useProject }, { DEFAULT_SETTINGS }] = await Promise.all([
|
||||
import(/* @vite-ignore */ projectModule),
|
||||
import(/* @vite-ignore */ schemaModule),
|
||||
]);
|
||||
const base = useProject.getState().settings ?? DEFAULT_SETTINGS;
|
||||
useProject.setState({
|
||||
settings: { ...base, editor: { ...base.editor, fontSize: 18, lineHeight: 18 } },
|
||||
});
|
||||
const root = document.documentElement.style;
|
||||
root.setProperty("--bg-editor", "#ffffff");
|
||||
root.setProperty("--bg-current-line", "#ffffff");
|
||||
root.setProperty("--bg-identifier-under-caret", "#cc0000");
|
||||
root.setProperty("--bg-search-match", "#cc00cc");
|
||||
root.setProperty("--bg-search-match-current", "#cc8800");
|
||||
await document.fonts.ready;
|
||||
});
|
||||
|
||||
const editor = await openFromTree(page, "README.md");
|
||||
const content = editor.locator(".cm-content");
|
||||
await content.click();
|
||||
await page.keyboard.press("Meta+a");
|
||||
await page.keyboard.insertText(
|
||||
[" ", "description", " ", "description", " "].join("\n"),
|
||||
);
|
||||
|
||||
const lines = editor.locator(".cm-line");
|
||||
await expect(lines).toHaveCount(5);
|
||||
|
||||
const blankRowsAreUnpainted = async () => {
|
||||
const [editorBox, b0, b2, b4, matchBox] = await Promise.all([
|
||||
editor.boundingBox(),
|
||||
lines.nth(0).boundingBox(),
|
||||
lines.nth(2).boundingBox(),
|
||||
lines.nth(4).boundingBox(),
|
||||
lines.nth(1).boundingBox(),
|
||||
]);
|
||||
const png = await editor.screenshot();
|
||||
const base64 = png.toString("base64");
|
||||
return page.evaluate(
|
||||
async ({ base64, editorBox, blanks, probeX }) => {
|
||||
const img = new Image();
|
||||
img.src = `data:image/png;base64,${base64}`;
|
||||
await img.decode();
|
||||
const scale = img.width / editorBox!.width;
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = img.width;
|
||||
canvas.height = img.height;
|
||||
const ctx = canvas.getContext("2d")!;
|
||||
ctx.drawImage(img, 0, 0);
|
||||
const x = Math.round((probeX - editorBox!.x) * scale);
|
||||
for (const row of blanks) {
|
||||
const yStart = Math.ceil((row!.y - editorBox!.y) * scale) + 1;
|
||||
const yEnd = Math.floor((row!.y + row!.height - editorBox!.y) * scale) - 1;
|
||||
for (let y = yStart; y <= yEnd; y++) {
|
||||
const [r, g, b] = ctx.getImageData(x, y, 1, 1).data;
|
||||
if (r !== 255 || g !== 255 || b !== 255) return { ok: false, x, y, rgb: [r, g, b] };
|
||||
}
|
||||
}
|
||||
return { ok: true };
|
||||
},
|
||||
{ base64, editorBox, blanks: [b0, b2, b4], probeX: matchBox!.x + 30 },
|
||||
);
|
||||
};
|
||||
|
||||
// Selection match on line 4 (`description`) when line 2 is selected.
|
||||
await lines.nth(1).dblclick();
|
||||
await expect(editor.locator(".cm-selectionMatch")).toHaveCount(1);
|
||||
expect(await blankRowsAreUnpainted()).toEqual({ ok: true });
|
||||
|
||||
// Find matches: line 2 is `.cm-openidea-findMatch-current` (with 1px frame), line 4 is `.cm-openidea-findMatch`.
|
||||
await page.keyboard.press("Meta+f");
|
||||
const find = page.getByRole("textbox", { name: "Find" });
|
||||
await expect(find).toBeFocused();
|
||||
await find.fill("description");
|
||||
await expect(editor.locator(".cm-openidea-findMatch-current")).toHaveCount(1);
|
||||
await expect(editor.locator(".cm-openidea-findMatch")).toHaveCount(2);
|
||||
expect(await blankRowsAreUnpainted()).toEqual({ ok: true });
|
||||
});
|
||||
|
||||
test("vertical tabs leave a narrow editor group most of its width", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 900, height: 600 });
|
||||
await openFromTree(page, "settings.gradle.kts");
|
||||
|
||||
@@ -88,3 +88,40 @@ test("a close button on the left keeps a narrow slot before the icon", async ({
|
||||
const slot = await box(closeOf(selected));
|
||||
expect(slot.x + slot.width).toBeLessThanOrEqual(label.x + 0.5);
|
||||
});
|
||||
|
||||
test("a pinned editor tab uses the close slot and can be unpinned from it", async ({ workbench: page }) => {
|
||||
await openFromTree(page, "README.md");
|
||||
await openFromTree(page, "build.gradle.kts");
|
||||
const strip = page.getByRole("tablist", { name: "Editor tabs" });
|
||||
const unpinned = strip.getByRole("tab", { name: "build.gradle.kts", exact: true });
|
||||
const pinned = strip.getByRole("tab", { name: "build.gradle.kts Pinned", exact: true });
|
||||
const menu = page.getByRole("menu", { name: "Context menu" });
|
||||
const pin = async () => {
|
||||
await unpinned.click({ button: "right" });
|
||||
await menu.getByRole("menuitem", { name: "Pin Tab", exact: true }).click();
|
||||
};
|
||||
await pin();
|
||||
const unpin = pinned.locator("..").getByRole("button", { name: "Unpin Tab", exact: true });
|
||||
|
||||
for (const closeButtonPosition of ["right", "left"]) {
|
||||
await setTabs(page, { closeButtonPosition });
|
||||
await expect(closeOf(pinned)).toHaveCount(0);
|
||||
const tab = await box(pinned.locator(".."));
|
||||
const action = await box(unpin);
|
||||
const label = await box(pinned.locator(":scope > span"));
|
||||
const inset = closeButtonPosition === "left" ? action.x - tab.x : tab.x + tab.width - action.x - action.width;
|
||||
expect(inset).toBeCloseTo(2, 0);
|
||||
expect(action.width).toBeCloseTo(16, 0);
|
||||
if (closeButtonPosition === "left") expect(action.x + action.width).toBeLessThanOrEqual(label.x);
|
||||
else expect(action.x).toBeGreaterThanOrEqual(label.x + label.width);
|
||||
}
|
||||
|
||||
await setTabs(page, { showCloseButton: false });
|
||||
await unpin.click();
|
||||
await expect(unpinned).toHaveAttribute("aria-selected", "true");
|
||||
await expect(closeOf(unpinned)).toHaveCount(0);
|
||||
|
||||
await pin();
|
||||
await pinned.click({ button: "middle" });
|
||||
await expect(pinned).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();
|
||||
});
|
||||
@@ -0,0 +1,80 @@
|
||||
import { expect, test } from "./fixtures";
|
||||
|
||||
const root = "/dev/acme-api";
|
||||
const stem = "InternationalSettlementRegionalReconciliationAndAuditWarehouseAllocationConfiguration";
|
||||
const original = stem + ".txt";
|
||||
const renamed = "WarehouseAllocation.txt";
|
||||
|
||||
test("file rename groups the name and reflows the options without losing validation", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 1000, height: 700 });
|
||||
await page.evaluate(
|
||||
async ({ root, original }) => {
|
||||
const fsModule = "/src/features/project-tree/fs.ts";
|
||||
const storeModule = "/src/features/project-tree/store.ts";
|
||||
const { projectFs } = await import(/* @vite-ignore */ fsModule);
|
||||
const { loadDir } = await import(/* @vite-ignore */ storeModule);
|
||||
await projectFs(root).createFile(root + "/" + original);
|
||||
await loadDir(root, true);
|
||||
},
|
||||
{ root, original },
|
||||
);
|
||||
const source = page.getByRole("treeitem", { name: original, exact: true });
|
||||
await source.click();
|
||||
await page.keyboard.press("Shift+F6");
|
||||
|
||||
const dialog = page.getByRole("dialog", { name: "Rename", exact: true });
|
||||
const prompt = dialog.getByText("Rename file '" + original + "' and its usages to:", { exact: true });
|
||||
const field = dialog.getByRole("textbox", { name: "New name" });
|
||||
const references = dialog.getByRole("checkbox", { name: "Search for references" });
|
||||
const comments = dialog.getByRole("checkbox", { name: "Search in comments and strings" });
|
||||
const submit = dialog.getByRole("button", { name: "Refactor", exact: true });
|
||||
const referencesRow = references.locator("xpath=ancestor::label");
|
||||
const commentsRow = comments.locator("xpath=ancestor::label");
|
||||
|
||||
await expect(field).toBeFocused();
|
||||
const selected = await field.evaluate((el: HTMLInputElement) => el.value.slice(el.selectionStart!, el.selectionEnd!));
|
||||
expect(selected).toBe(stem);
|
||||
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const a = (await prompt.boundingBox())!;
|
||||
const b = (await field.boundingBox())!;
|
||||
return b.y - a.y - a.height;
|
||||
})
|
||||
.toBeCloseTo(4, 0);
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const a = (await referencesRow.boundingBox())!;
|
||||
const b = (await commentsRow.boundingBox())!;
|
||||
return Math.abs(a.y - b.y) < 1 && b.x >= a.x + a.width;
|
||||
})
|
||||
.toBe(true);
|
||||
|
||||
await field.fill("README.md");
|
||||
await expect(dialog.getByRole("alert")).toBeVisible();
|
||||
await expect(submit).toBeDisabled();
|
||||
await page.setViewportSize({ width: 400, height: 520 });
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const a = (await referencesRow.boundingBox())!;
|
||||
const b = (await commentsRow.boundingBox())!;
|
||||
return b.y >= a.y + a.height;
|
||||
})
|
||||
.toBe(true);
|
||||
await expect(field).toHaveValue("README.md");
|
||||
await expect(prompt).toBeInViewport({ ratio: 1 });
|
||||
await expect(submit).toBeInViewport({ ratio: 1 });
|
||||
expect(
|
||||
await dialog.locator("[data-dialog-body]").evaluate((node) => node.scrollWidth - node.clientWidth),
|
||||
).toBeLessThanOrEqual(1);
|
||||
|
||||
await field.fill(renamed);
|
||||
await expect(dialog.getByRole("alert")).toBeHidden();
|
||||
await references.uncheck();
|
||||
await comments.uncheck();
|
||||
await submit.click();
|
||||
await expect(dialog).toBeHidden();
|
||||
await page.setViewportSize({ width: 1000, height: 700 });
|
||||
await expect(page.getByRole("treeitem", { name: renamed, exact: true })).toBeVisible();
|
||||
await expect(source).toHaveCount(0);
|
||||
});
|
||||
@@ -0,0 +1,78 @@
|
||||
import type { Locator, Page } from "@playwright/test";
|
||||
import { expect, openFromTree, test } from "./fixtures";
|
||||
|
||||
const latest = "regional-order-reconciliation-endpoints-for-sandbox-environments/".repeat(3) + "checkout\nText to find";
|
||||
|
||||
async function seedHistory(page: Page, kind: "find" | "replace") {
|
||||
await page.evaluate(
|
||||
async ({ kind, latest }) => {
|
||||
const searchModule = "/src/platform/search.ts";
|
||||
const { rememberSearch } = await import(/* @vite-ignore */ searchModule);
|
||||
for (let i = 0; i < 19; i++) rememberSearch(kind, `Order rule ${i}`);
|
||||
rememberSearch(kind, latest);
|
||||
},
|
||||
{ kind, latest },
|
||||
);
|
||||
}
|
||||
|
||||
async function openHistory(field: Locator, menu: Locator) {
|
||||
await field.focus();
|
||||
await field.press("Alt+ArrowDown");
|
||||
await expect(menu).toBeVisible();
|
||||
}
|
||||
|
||||
test("editor find history grows with the field and restores the original query", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 1040, height: 700 });
|
||||
await openFromTree(page, "build.gradle.kts");
|
||||
await page.keyboard.press("Meta+f");
|
||||
await seedHistory(page, "find");
|
||||
|
||||
const field = page.getByRole("textbox", { name: "Find", exact: true });
|
||||
const menu = page.getByRole("menu", { name: "Recent Searches", exact: true });
|
||||
await openHistory(field, menu);
|
||||
|
||||
const newest = menu.getByRole("menuitem").first();
|
||||
await expect(newest).toHaveText(latest.replace("\n", " ⏎ "));
|
||||
await expect(newest).toHaveAttribute("title", latest);
|
||||
await expect.poll(async () => (await menu.boundingBox())!.width).toBeGreaterThan(420);
|
||||
await newest.press("Enter");
|
||||
await expect(menu).toBeHidden();
|
||||
await expect(field).toHaveValue(latest);
|
||||
await expect(field).toBeFocused();
|
||||
});
|
||||
|
||||
test("project replacement history stays inside a narrow window and keeps its heading visible", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 440, height: 520 });
|
||||
await page.keyboard.press("Meta+Shift+r");
|
||||
await seedHistory(page, "replace");
|
||||
|
||||
const field = page.getByRole("textbox", { name: "Replace with" });
|
||||
const menu = page.getByRole("menu", { name: "Recent Replacements" });
|
||||
await openHistory(field, menu);
|
||||
|
||||
const popup = menu.locator("..");
|
||||
const heading = popup.getByText("Recent Replacements", { exact: true });
|
||||
const newest = menu.getByRole("menuitem").first();
|
||||
await expect(newest).toHaveText(latest.replace("\n", " ⏎ "));
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const { x, width } = (await popup.boundingBox())!;
|
||||
return x >= 0 && x + width <= 440;
|
||||
})
|
||||
.toBe(true);
|
||||
|
||||
await newest.press("End");
|
||||
const oldest = menu.getByRole("menuitem").last();
|
||||
await expect(oldest).toBeFocused();
|
||||
await expect.poll(async () => popup.evaluate((node) => node.scrollTop)).toBeGreaterThan(0);
|
||||
await expect(heading).toBeInViewport();
|
||||
|
||||
await oldest.press("Home");
|
||||
await expect(newest).toBeFocused();
|
||||
await newest.press("Enter");
|
||||
await expect(menu).toBeHidden();
|
||||
await expect(field).toHaveValue(latest);
|
||||
await expect(field).toBeFocused();
|
||||
});
|
||||
@@ -1,6 +1,66 @@
|
||||
import type { Locator } from "@playwright/test";
|
||||
import { expect, stubDesktop, test } from "./fixtures";
|
||||
|
||||
test("Find Usages places read and write filters with the other actions", async ({ workbench: page }) => {
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async () => {
|
||||
const modulePath = "/src/features/code-insight/usages.ts";
|
||||
const { useUsagesPopup } = await import(modulePath);
|
||||
const path = "/dev/acme-api/src/SettlementService.ts";
|
||||
const lines = ["const current = settlement;", "settlement = next;"];
|
||||
window.__ipc.handlers.fs_read_text = () => lines.join("\n");
|
||||
useUsagesPopup.setState({
|
||||
open: true,
|
||||
anchor: { x: 100, y: 150 },
|
||||
symbol: "settlement",
|
||||
loading: false,
|
||||
scope: "project",
|
||||
groups: [
|
||||
{
|
||||
path,
|
||||
usages: lines.map((text, line) => ({
|
||||
path,
|
||||
line,
|
||||
col: text.indexOf("settlement"),
|
||||
endCol: text.indexOf("settlement") + "settlement".length,
|
||||
text,
|
||||
access: line === 0 ? "read" : "write",
|
||||
})),
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
const popup = page.getByRole("dialog", { name: "Usages", exact: true });
|
||||
const read = { name: "Show read accesses", exact: true };
|
||||
const write = { name: "Show write accesses", exact: true };
|
||||
const actions = popup.getByRole("button", { name: "Show Preview", exact: true }).locator("..");
|
||||
await expect(popup.getByRole("option")).toHaveCount(2);
|
||||
for (const width of [1120, 540]) {
|
||||
await page.setViewportSize({ width, height: 640 });
|
||||
expect(await actions.getByRole("toolbar", { name: "Usage access filters", exact: true }).count()).toBe(1);
|
||||
await expect(actions.getByRole("button", read)).toBeInViewport({ ratio: 1 });
|
||||
await expect(actions.getByRole("button", write)).toBeInViewport({ ratio: 1 });
|
||||
}
|
||||
await actions.getByRole("button", write).click();
|
||||
await expect(popup.getByRole("option")).toHaveCount(1);
|
||||
await popup.getByRole("button", { name: /Open in Find Window/ }).click();
|
||||
|
||||
const view = page.getByRole("region", { name: "Find Usages", exact: true });
|
||||
const toolbar = view.getByRole("toolbar", { name: "Usages actions", exact: true });
|
||||
const readButton = toolbar.getByRole("button", read);
|
||||
const writeButton = toolbar.getByRole("button", write);
|
||||
await expect(readButton).toHaveAttribute("aria-pressed", "true");
|
||||
await expect(writeButton).toHaveAttribute("aria-pressed", "false");
|
||||
const a = (await readButton.boundingBox())!;
|
||||
const b = (await writeButton.boundingBox())!;
|
||||
expect(a.x).toBeCloseTo(b.x, 0);
|
||||
expect(b.y).toBeGreaterThanOrEqual(a.y + a.height);
|
||||
await expect(view.locator("mark")).toHaveCount(1);
|
||||
await writeButton.click();
|
||||
await expect(view.locator("mark")).toHaveCount(2);
|
||||
});
|
||||
|
||||
async function checkSize(icon: Locator, size = 16) {
|
||||
const dimensions = await icon.evaluate((node) => {
|
||||
const style = getComputedStyle(node);
|
||||
|
||||
@@ -3,11 +3,12 @@ import { expect, openFromTree, stubDesktop, test } from "./fixtures";
|
||||
test("Git annotations align dates and full author names at UI text size", async ({ workbench: page }) => {
|
||||
const editor = await openFromTree(page, "build.gradle.kts");
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async () => {
|
||||
const longEmail = `reconciliation+${"regional-settlement-".repeat(5)}[email protected]`;
|
||||
await page.evaluate(async (email) => {
|
||||
const root = "/dev/acme-api";
|
||||
const file = `${root}/build.gradle.kts`;
|
||||
const handlers = window.__ipc.handlers;
|
||||
handlers.vcs_blame = () => [
|
||||
const lines = [
|
||||
{
|
||||
commit: "a1234567".padEnd(40, "a"),
|
||||
author: "Lena Park",
|
||||
@@ -21,6 +22,23 @@ test("Git annotations align dates and full author names at UI text size", async
|
||||
summary: "Review totals",
|
||||
},
|
||||
];
|
||||
handlers.vcs_blame = () => lines;
|
||||
handlers.vcs_log = ({ query }) => {
|
||||
const { branch } = query as { branch?: string };
|
||||
const line = lines.find(({ commit }) => commit === branch);
|
||||
if (!line) return [];
|
||||
return [
|
||||
{
|
||||
...line,
|
||||
id: line.commit,
|
||||
shortId: line.commit.slice(0, 8),
|
||||
refs: [],
|
||||
parents: [],
|
||||
email: line === lines[0] ? "[email protected]" : email,
|
||||
message: line.summary,
|
||||
},
|
||||
];
|
||||
};
|
||||
const projectModule = "/src/platform/project.ts";
|
||||
const { useProject } = await import(/* @vite-ignore */ projectModule);
|
||||
const { settings } = useProject.getState();
|
||||
@@ -39,7 +57,7 @@ test("Git annotations align dates and full author names at UI text size", async
|
||||
const actionsModule = "/src/platform/actions.ts";
|
||||
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
|
||||
await executeAction("vcs.annotate", file);
|
||||
});
|
||||
}, longEmail);
|
||||
|
||||
const gutter = editor.locator(".cm-vcs-blame");
|
||||
const first = gutter.locator("[data-commit]").filter({ hasText: "3 May 2026" });
|
||||
@@ -51,6 +69,21 @@ test("Git annotations align dates and full author names at UI text size", async
|
||||
await expect
|
||||
.poll(async () => Math.abs((await firstAuthor.boundingBox())!.x - (await secondAuthor.boundingBox())!.x))
|
||||
.toBeLessThan(1);
|
||||
|
||||
await first.hover();
|
||||
const details = page.getByRole("dialog").filter({ has: page.getByTitle("Show Commit in Git Log") });
|
||||
await expect(details).toContainText("[email protected]");
|
||||
await expect.poll(async () => (await details.boundingBox())!.width).toBeLessThan(400);
|
||||
await expect(details.getByTitle("Show Commit in Git Log")).toHaveCSS(
|
||||
"font-family",
|
||||
await details.evaluate((el) => getComputedStyle(el).fontFamily),
|
||||
);
|
||||
|
||||
await page.setViewportSize({ width: 430, height: 640 });
|
||||
await second.hover();
|
||||
await expect(details).toContainText(longEmail);
|
||||
await expect(details).toBeInViewport({ ratio: 1 });
|
||||
await expect.poll(() => details.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
|
||||
const uiSize = await editor.evaluate((el) => getComputedStyle(el).getPropertyValue("--fs-ui").trim());
|
||||
await expect(firstAuthor).toHaveCSS("font-size", uiSize);
|
||||
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
import { expect, stubDesktop, test } from "./fixtures";
|
||||
|
||||
const rootSubject = "Start warehouse reporting";
|
||||
const mergeSubject = "Merge reporting changes";
|
||||
const firstSubject = "Align regional settlement totals with the warehouse ledger before monthly reconciliation closes";
|
||||
const secondSubject = "Keep archived settlement adjustments in the regional audit trail after the ledger is rebuilt";
|
||||
|
||||
test("Git Log commit choices fit their rows and navigate by keyboard after filtering", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 1040, height: 700 });
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(
|
||||
async ({ mergeSubject, firstSubject, secondSubject, rootSubject }) => {
|
||||
const root = "/dev/acme-api";
|
||||
const changes = [
|
||||
[mergeSubject, "Merge Author", [1, 2]],
|
||||
[firstSubject, "Priya Kapoor", [3]],
|
||||
[secondSubject, "Morgan Olsen", [3]],
|
||||
[rootSubject, "Initial Author", []],
|
||||
] as const;
|
||||
const id = (i: number) => String(i + 1).repeat(40);
|
||||
const commits = changes.map(([summary, author, parents], i) => ({
|
||||
id: id(i),
|
||||
shortId: id(i).slice(0, 8),
|
||||
parents: parents.map(id),
|
||||
refs: i === 0 ? ["HEAD", "main"] : [],
|
||||
author,
|
||||
email: "[email protected]",
|
||||
timeMs: Date.UTC(2026, 10, 15 - i, 10 + i, 30),
|
||||
summary,
|
||||
message: summary,
|
||||
}));
|
||||
const handlers = window.__ipc.handlers;
|
||||
handlers.vcs_log = ({ query }) => {
|
||||
const { skip, limit, range } = query as { skip: number; limit: number; range?: string };
|
||||
return range ? [] : commits.slice(skip, limit ? skip + limit : undefined);
|
||||
};
|
||||
handlers.vcs_log_refs = () => ({});
|
||||
handlers.vcs_log_users = () => [];
|
||||
handlers.vcs_branches = () => [];
|
||||
handlers.vcs_branch_info = () => ({ head: "main", headCommit: id(0), ahead: 0, behind: 0 });
|
||||
handlers.vcs_config_get = () => null;
|
||||
handlers.vcs_commit_files = () => [];
|
||||
handlers.vcs_log_details_batch = ({ revisions }) =>
|
||||
(revisions as string[]).map(() => ({ message: "", containingBranches: [], signature: "N" }));
|
||||
const vcsModule = "/src/features/vcs/store.ts";
|
||||
const contextModule = "/src/platform/context.ts";
|
||||
const actionsModule = "/src/platform/actions.ts";
|
||||
const { useVcs } = await import(/* @vite-ignore */ vcsModule);
|
||||
const { setContext } = await import(/* @vite-ignore */ contextModule);
|
||||
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
|
||||
useVcs.setState({ available: true, root, repo: root, roots: [root], branchesLoaded: true });
|
||||
setContext("vcsAvailable", true);
|
||||
await executeAction("vcs.showLog");
|
||||
},
|
||||
{ mergeSubject, firstSubject, secondSubject, rootSubject },
|
||||
);
|
||||
|
||||
const log = page.getByRole("listbox", { name: "Commits", exact: true });
|
||||
const merge = log.getByRole("option", { name: new RegExp(mergeSubject) });
|
||||
await merge.click();
|
||||
await log.press("ArrowRight");
|
||||
const chooser = page.getByRole("dialog", { name: "Select Parent Commit", exact: true });
|
||||
const options = chooser.getByRole("option");
|
||||
const filter = chooser.getByRole("combobox", { name: "Search commits" });
|
||||
await expect(filter).toBeFocused();
|
||||
await expect(options).toHaveCount(2);
|
||||
const before = (await chooser.boundingBox())!;
|
||||
expect(before.height).toBeLessThan(200);
|
||||
const first = options.filter({ hasText: firstSubject });
|
||||
const subject = first.getByText(firstSubject, { exact: true });
|
||||
const author = first.getByText("Priya Kapoor", { exact: true });
|
||||
const hash = first.getByText("22222222", { exact: true });
|
||||
await expect(subject).toHaveCSS("font-size", "13px");
|
||||
await expect(author).toHaveCSS("font-size", "12px");
|
||||
expect((await subject.boundingBox())!.y).toBeLessThan((await hash.boundingBox())!.y);
|
||||
await expect(subject.locator("..")).toHaveAttribute("title", /Priya Kapoor/);
|
||||
|
||||
await page.setViewportSize({ width: 440, height: 520 });
|
||||
const narrow = (await chooser.boundingBox())!;
|
||||
expect(narrow.x + narrow.width).toBeLessThanOrEqual(440);
|
||||
expect(await chooser.evaluate((node) => node.scrollWidth - node.clientWidth)).toBeLessThanOrEqual(1);
|
||||
await filter.fill("No such change");
|
||||
await expect(chooser.getByText("No commits", { exact: true })).toBeVisible();
|
||||
await filter.press("Enter");
|
||||
await expect(chooser).toBeVisible();
|
||||
await filter.fill("Morgan Olsen");
|
||||
await expect(options).toHaveCount(1);
|
||||
await expect(options.first()).toContainText(secondSubject);
|
||||
await filter.fill("");
|
||||
await expect(options).toHaveCount(2);
|
||||
await filter.press("ArrowDown");
|
||||
await expect(options.filter({ hasText: secondSubject })).toHaveAttribute("aria-selected", "true");
|
||||
await filter.press("Enter");
|
||||
await expect(chooser).toBeHidden();
|
||||
await expect(log.getByRole("option", { name: new RegExp(secondSubject) })).toHaveAttribute("aria-selected", "true");
|
||||
|
||||
await log.getByRole("option", { name: new RegExp(rootSubject) }).click();
|
||||
await log.press("ArrowLeft");
|
||||
const children = page.getByRole("dialog", { name: "Select Child Commit", exact: true });
|
||||
await expect(children.getByRole("option")).toHaveCount(2);
|
||||
await children.getByRole("option", { name: new RegExp(firstSubject) }).click();
|
||||
await expect(children).toBeHidden();
|
||||
await expect(log.getByRole("option", { name: new RegExp(firstSubject) })).toHaveAttribute("aria-selected", "true");
|
||||
});
|
||||
@@ -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(() => {
|
||||
|
||||
@@ -12,6 +12,30 @@ const names = [
|
||||
"InvoicePublisher.ts",
|
||||
];
|
||||
|
||||
test("a pinned editor tab can be unpinned from the hidden tabs list", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 700, height: 650 });
|
||||
await page.evaluate(async (first) => {
|
||||
const module = "/src/workbench/contributions.ts";
|
||||
const { editorService } = await import(/* @vite-ignore */ module);
|
||||
await editorService().openFile(`/dev/acme-api/${first}`);
|
||||
}, names[0]!);
|
||||
const strip = page.getByRole("tablist", { name: "Editor tabs" });
|
||||
const tab = strip.getByRole("tab", { name: names[0], exact: true });
|
||||
await tab.click({ button: "right" });
|
||||
await page.getByRole("menuitem", { name: "Pin Tab", exact: true }).click();
|
||||
await page.evaluate(async (files) => {
|
||||
const module = "/src/workbench/contributions.ts";
|
||||
const { editorService } = await import(/* @vite-ignore */ module);
|
||||
for (const name of files) await editorService().openFile(`/dev/acme-api/${name}`);
|
||||
}, names.slice(1));
|
||||
await strip.evaluate((element) => (element.scrollLeft = element.scrollWidth));
|
||||
await page.getByRole("button", { name: "Show Hidden Tabs" }).click();
|
||||
const row = page.getByRole("grid", { name: "Hidden Editor Tabs" }).getByRole("row").filter({ hasText: names[0]! });
|
||||
await expect(row.getByRole("button", { name: "Close Tab", exact: true })).toHaveCount(0);
|
||||
await row.getByRole("button", { name: "Unpin Tab", exact: true }).click();
|
||||
await expect(tab).toHaveCount(1);
|
||||
});
|
||||
|
||||
test("the editor overflow lists clipped tabs and can close or open one without touching visible tabs", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import { expect, stubDesktop, test } from "./fixtures";
|
||||
|
||||
test("image controls and metadata stay readable in a narrow editor", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 1080, height: 700 });
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async () => {
|
||||
const path = "/dev/acme-api/status.svg";
|
||||
const image =
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" width="128" height="96"><rect width="128" height="96"/></svg>';
|
||||
window.__ipc.handlers.fs_read_image = () => "data:image/svg+xml," + encodeURIComponent(image);
|
||||
window.__ipc.handlers.fs_probe = () => ({ size: 4096, binary: false, tooLarge: false });
|
||||
const contributions = "/src/workbench/contributions.ts";
|
||||
const { editorService } = await import(/* @vite-ignore */ contributions);
|
||||
await editorService().openFile(path);
|
||||
});
|
||||
const toolbars = page.getByRole("toolbar", { name: "Image viewer", exact: true });
|
||||
const toolbar = toolbars.last();
|
||||
const zoomIn = toolbar.getByRole("button", { name: "Zoom In", exact: true });
|
||||
const actualSize = toolbar.getByRole("button", { name: "Actual Size", exact: true });
|
||||
const chessboard = toolbar.getByRole("button", { name: "Show Chessboard", exact: true });
|
||||
const showText = toolbar.getByRole("button", { name: "Open as Text", exact: true });
|
||||
const dimensions = toolbar.getByText(/128\s*×\s*96/);
|
||||
await expect(page.getByRole("img", { name: "status.svg", exact: true })).toBeVisible();
|
||||
await expect(dimensions).toBeVisible();
|
||||
const wideHeight = (await toolbar.boundingBox())!.height;
|
||||
|
||||
await page.getByRole("button", { name: "Split Right", exact: true }).click();
|
||||
await expect(toolbars).toHaveCount(2);
|
||||
await page.setViewportSize({ width: 640, height: 570 });
|
||||
expect(await dimensions.evaluate((el) => el.scrollWidth - el.clientWidth)).toBe(0);
|
||||
expect((await toolbar.boundingBox())!.height).toBeGreaterThan(wideHeight);
|
||||
expect((await dimensions.boundingBox())!.y).toBeGreaterThan((await zoomIn.boundingBox())!.y);
|
||||
await expect(dimensions).toHaveCSS("font-size", "13px");
|
||||
await expect(showText).toHaveCSS("white-space", "nowrap");
|
||||
for (const item of [zoomIn, actualSize, chessboard, showText, dimensions]) {
|
||||
await expect(item).toBeInViewport({ ratio: 1 });
|
||||
}
|
||||
await expect(toolbar.getByText("4.0 KB", { exact: true })).toBeVisible();
|
||||
|
||||
await zoomIn.click();
|
||||
await expect(toolbar.getByText("125%", { exact: true })).toBeVisible();
|
||||
await actualSize.click();
|
||||
await expect(toolbar.getByText("100%", { exact: true })).toBeVisible();
|
||||
await chessboard.click();
|
||||
await expect(chessboard).toHaveAttribute("aria-pressed", "false");
|
||||
await showText.click();
|
||||
await expect(page.locator(".cm-content")).toBeVisible();
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
import { expect, openFromTree, test } from "./fixtures";
|
||||
|
||||
test("multiline editor search keeps three visible lines and replaces with the full text", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
const editor = await openFromTree(page, "build.gradle.kts");
|
||||
await page.setViewportSize({ width: 540, height: 500 });
|
||||
const content = editor.locator(".cm-content");
|
||||
const query = "currency=EUR\nregion=eu-west\npipeline=clearing\nmode=batch\ntimeout=30\nretries=2";
|
||||
const replacement = query.replace("clearing", "settlement").replace("timeout=30", "timeout=45");
|
||||
await content.press("Meta+a");
|
||||
await page.keyboard.insertText(`[ledger]\n${query}\n\n[reporting]\n${query}\n`);
|
||||
await content.press("Escape");
|
||||
await content.press("Meta+r");
|
||||
|
||||
const bar = page.getByRole("search", { name: "Replace in file" });
|
||||
const find = bar.getByRole("textbox", { name: "Find", exact: true });
|
||||
const replace = bar.getByRole("textbox", { name: "Replace", exact: true });
|
||||
await find.fill(query);
|
||||
await replace.fill(replacement);
|
||||
for (const field of [find, replace]) {
|
||||
const visibleLines = await field.evaluate((el) => el.clientHeight / parseFloat(getComputedStyle(el).lineHeight));
|
||||
expect(visibleLines).toBeCloseTo(3);
|
||||
await field.press("Control+End");
|
||||
await expect.poll(() => field.evaluate((el) => el.scrollTop)).toBeGreaterThan(0);
|
||||
}
|
||||
await expect(find).toHaveValue(query);
|
||||
await expect(replace).toHaveValue(replacement);
|
||||
const count = bar.locator("[aria-live]");
|
||||
await expect(count).toHaveText(/\/2$/);
|
||||
const selected = await count.innerText();
|
||||
const next = bar.getByRole("button", { name: /Next Occurrence/ });
|
||||
await next.click();
|
||||
await expect(count).toHaveText(/^[12]\/2$/);
|
||||
await expect(count).not.toHaveText(selected);
|
||||
|
||||
await bar.getByRole("button", { name: "Replace All", exact: true }).click();
|
||||
await expect(editor.locator(".cm-line", { hasText: "timeout=45" })).toHaveCount(2);
|
||||
await expect(editor.locator(".cm-line", { hasText: "pipeline=clearing" })).toHaveCount(0);
|
||||
await bar.getByRole("button", { name: "Close", exact: true }).click();
|
||||
await expect(content).toBeFocused();
|
||||
await content.press("Meta+z");
|
||||
await expect(editor.locator(".cm-line", { hasText: "pipeline=clearing" })).toHaveCount(2);
|
||||
});
|
||||
@@ -83,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();
|
||||
});
|
||||
+35
-2
@@ -11,7 +11,7 @@ async function openNewBranchDialog(
|
||||
page: Page,
|
||||
from?: string,
|
||||
mergeBase = "1111111",
|
||||
blocked = false,
|
||||
blocked: boolean | string = false,
|
||||
withPrefix = false,
|
||||
) {
|
||||
await stubDesktop(page);
|
||||
@@ -43,7 +43,10 @@ async function openNewBranchDialog(
|
||||
];
|
||||
h.vcs_create_branch = ({ options }) =>
|
||||
blocked && (options as { mode?: string } | null)?.mode === "normal"
|
||||
? { checkout: { kind: "localChanges", files: ["dirty.txt"] }, created: null }
|
||||
? {
|
||||
checkout: { kind: "localChanges", files: [typeof blocked === "string" ? blocked : "dirty.txt"] },
|
||||
created: null,
|
||||
}
|
||||
: { checkout: { kind: "done" }, created: { tip: "2222222", previousTip: null } };
|
||||
h.vcs_merge_base = () => mergeBase;
|
||||
const vcsModule = "/src/features/vcs/store.ts";
|
||||
@@ -151,6 +154,36 @@ for (const [button, mode] of [
|
||||
});
|
||||
}
|
||||
|
||||
test("local changes review keeps file names and checkout choices visible", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 1040, height: 740 });
|
||||
const folder = "services/international-payments/regional-settlement/weekly-close/adjustments";
|
||||
const path = `${folder}/ReceiptPolicy.ts`;
|
||||
const { dialog, input } = await openNewBranchDialog(page, "2".repeat(40), "1111111", path);
|
||||
await input.fill("topic");
|
||||
await dialog.getByRole("button", { name: "Create", exact: true }).click();
|
||||
const review = page.getByRole("dialog", { name: "Git Checkout Problem" });
|
||||
const force = review.getByRole("button", { name: "Force Checkout", exact: true });
|
||||
const smart = review.getByRole("button", { name: "Smart Checkout", exact: true });
|
||||
const cancel = review.getByRole("button", { name: "Don't Checkout", exact: true });
|
||||
await expect(force).toBeVisible();
|
||||
expect((await force.boundingBox())!.x - (await review.boundingBox())!.x).toBeLessThan(24);
|
||||
|
||||
await page.setViewportSize({ width: 420, height: 480 });
|
||||
const tree = review.getByRole("tree", { name: "Changed files" });
|
||||
const row = tree.getByRole("treeitem", { name: `ReceiptPolicy.ts ${folder}`, exact: true });
|
||||
await expect(row.getByTitle(path, { exact: true })).toBeVisible();
|
||||
const file = row.getByText("ReceiptPolicy.ts", { exact: true });
|
||||
await expect(file).toBeInViewport({ ratio: 1 });
|
||||
expect(await file.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
|
||||
await expect(row.getByText(folder, { exact: true })).toHaveCSS("font-size", "12px");
|
||||
const restoreHint = review.getByText(/Smart Checkout .* your changes and restores them/);
|
||||
expect((await restoreHint.boundingBox())!.y).toBeLessThan((await tree.boundingBox())!.y);
|
||||
for (const button of [force, smart, cancel]) await expect(button).toBeInViewport({ ratio: 1 });
|
||||
await cancel.click();
|
||||
await expect(review).toBeHidden();
|
||||
expect(await ipcCalls(page, "vcs_create_branch")).toHaveLength(1);
|
||||
});
|
||||
|
||||
test("pasted text has its spaces replaced", async ({ workbench: page }) => {
|
||||
const { dialog, input } = await openNewBranchDialog(page);
|
||||
await input.fill("");
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { expect, test } from "./fixtures";
|
||||
|
||||
test("fits notification body and actions below the dismiss button in a narrow window", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 420, height: 540 });
|
||||
const title = "Validation failed for the catalog service";
|
||||
const body = "The build stopped while checking the catalog response type.";
|
||||
const action = "recheckCatalogServiceResponsePayloadAfterRegeneratingTypesForDevelopment";
|
||||
await page.evaluate(
|
||||
async ({ title, body, action }) => {
|
||||
const servicePath = "/src/workbench/contributions.ts";
|
||||
const { notifications } = await import(/* @vite-ignore */ servicePath);
|
||||
notifications().notify({
|
||||
level: "error",
|
||||
title,
|
||||
body,
|
||||
actions: [{ label: action, run: () => document.body.setAttribute("data-validation-retried", "true") }],
|
||||
});
|
||||
},
|
||||
{ title, body, action },
|
||||
);
|
||||
|
||||
const balloon = page.getByRole("alert").filter({ hasText: title });
|
||||
const message = balloon.getByText(body, { exact: true });
|
||||
const dismiss = balloon.getByRole("button", { name: "Dismiss", exact: true });
|
||||
const retry = balloon.getByRole("button", { name: action, exact: true });
|
||||
await expect(balloon).toBeInViewport({ ratio: 1 });
|
||||
const [messageBox, dismissBox] = await Promise.all([message.boundingBox(), dismiss.boundingBox()]);
|
||||
expect(messageBox!.y).toBeGreaterThanOrEqual(dismissBox!.y + dismissBox!.height);
|
||||
expect(messageBox!.x + messageBox!.width).toBeGreaterThanOrEqual(dismissBox!.x + dismissBox!.width - 1);
|
||||
expect(await retry.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
|
||||
await retry.click();
|
||||
await expect(page.locator("body")).toHaveAttribute("data-validation-retried", "true");
|
||||
await expect(balloon).toBeHidden();
|
||||
});
|
||||
@@ -1,9 +1,7 @@
|
||||
import type { EditorView } from "@codemirror/view";
|
||||
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
|
||||
|
||||
test("Quick Evaluate opens an object tree that fits the editor and returns focus on Escape", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
test("Quick Evaluate and hover keep value previews usable in a narrow editor", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 445, height: 500 });
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async () => {
|
||||
@@ -19,7 +17,9 @@ test("Quick Evaluate opens an object tree that fits the editor and returns focus
|
||||
h.fs_probe = () => ({ size: 48, binary: false, tooLarge: false });
|
||||
h.fs_read_text = () => "summary = {}\nsubtotal = 42\n";
|
||||
h.debug_evaluate_in = ({ expression }) =>
|
||||
expression === "summary" ? value("summary", "{...}", "dict", 101) : value("subtotal", "42", "int");
|
||||
expression === "summary"
|
||||
? value("summary", `{'audit': '${"Regional settlement totals ".repeat(8)}'}`, "dict", 101)
|
||||
: value("subtotal", "42", "int");
|
||||
h.debug_variables = ({ reference }) =>
|
||||
reference === 101
|
||||
? [value("audit", "{...}", "dict", 102), value("total", "47.74", "float")]
|
||||
@@ -81,8 +81,59 @@ test("Quick Evaluate opens an object tree that fits the editor and returns focus
|
||||
await evaluate(2);
|
||||
await expect(hint.getByRole("tree")).toHaveCount(0);
|
||||
await expect(hint).toHaveText(/subtotal\s*=\s*42/);
|
||||
expect(await ipcCalls(page, "debug_evaluate_in")).toEqual([
|
||||
const scalar = hint.locator("[class*='_valueTooltip_']");
|
||||
const uiFont = await page.locator("body").evaluate((el) => getComputedStyle(el).fontFamily);
|
||||
await expect(scalar).toHaveCSS("font-family", uiFont);
|
||||
await expect(scalar).toHaveCSS("font-size", "13px");
|
||||
await expect(scalar).toHaveCSS("font-weight", "700");
|
||||
await expect(scalar.locator(".cm-openidea-icon")).toHaveCount(1);
|
||||
await content.press("Escape");
|
||||
await expect(hint).toBeHidden();
|
||||
|
||||
await page.setViewportSize({ width: 620, height: 480 });
|
||||
await page.evaluate(async () => {
|
||||
const layoutModule = "/src/workbench/toolwindows/store.ts";
|
||||
const servicesModule = "/src/workbench/contributions.ts";
|
||||
const { moveToolWindow, setToolWindowSize } = await import(/* @vite-ignore */ layoutModule);
|
||||
const { toolWindowService } = await import(/* @vite-ignore */ servicesModule);
|
||||
moveToolWindow("project", "left");
|
||||
setToolWindowSize("left", 220);
|
||||
toolWindowService().show("project", false);
|
||||
});
|
||||
await expect.poll(async () => (await editor.boundingBox())!.x).toBeGreaterThan(160);
|
||||
const position = await content.evaluate((el) => {
|
||||
const { view } = (el as HTMLElement & { cmTile: { view: EditorView } }).cmTile;
|
||||
return view.coordsAtPos(view.state.doc.line(1).from + 2);
|
||||
});
|
||||
await page.mouse.move(position!.left, (position!.top + position!.bottom) / 2);
|
||||
const hover = page.locator(".cm-tooltip-hover").locator("[class*='_valueTooltip_']");
|
||||
const expand = hover.getByRole("button", { name: "Expand value" });
|
||||
await expect(hover).toContainText("Regional settlement totals");
|
||||
await expect(hover).toHaveCSS("font-family", uiFont);
|
||||
const summary = hover.locator("[class*='_valueText_']");
|
||||
const textBox = (await summary.boundingBox())!;
|
||||
const controlBox = (await expand.boundingBox())!;
|
||||
const iconBox = (await hover.locator(".cm-openidea-icon").boundingBox())!;
|
||||
expect(textBox.height).toBeGreaterThan(20);
|
||||
expect(Math.abs(controlBox.y - iconBox.y)).toBeLessThan(1);
|
||||
expect(textBox.x).toBeGreaterThanOrEqual(iconBox.x + iconBox.width);
|
||||
const fitsEditor = async () => {
|
||||
const tooltip = await hover.boundingBox();
|
||||
const pane = (await editor.boundingBox())!;
|
||||
return !!tooltip && tooltip.x >= pane.x - 1 && tooltip.x + tooltip.width <= pane.x + pane.width + 1;
|
||||
};
|
||||
await expect.poll(fitsEditor).toBe(true);
|
||||
await page.setViewportSize({ width: 555, height: 480 });
|
||||
await expect.poll(fitsEditor).toBe(true);
|
||||
await expand.click();
|
||||
const pinned = hint.getByRole("tree", { name: "summary" });
|
||||
await expect(pinned).toBeFocused();
|
||||
await pinned.press("Escape");
|
||||
await expect(content).toBeFocused();
|
||||
const calls = await ipcCalls(page, "debug_evaluate_in");
|
||||
expect(calls.filter((call) => call.context === "watch")).toEqual([
|
||||
{ session: 91, frameId: 11, expression: "summary", context: "watch" },
|
||||
{ session: 91, frameId: 11, expression: "subtotal", context: "watch" },
|
||||
]);
|
||||
expect(calls).toContainEqual({ session: 91, frameId: 11, expression: "summary", context: "hover" });
|
||||
});
|
||||
@@ -0,0 +1,75 @@
|
||||
import type { SearchQuery } from "../src/bindings";
|
||||
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
|
||||
|
||||
test("Replace All keeps both values readable and the actions visible", async ({ workbench: page }) => {
|
||||
const pattern = `LEGACY_${"MONTH_END_RECONCILIATION_INPUT_".repeat(15)}END`;
|
||||
const replacement = `ACTIVE_${"MONTH_END_RECONCILIATION_OUTPUT_".repeat(18)}END`;
|
||||
await page.emulateMedia({ reducedMotion: "reduce" });
|
||||
await page.setViewportSize({ width: 1040, height: 700 });
|
||||
await stubDesktop(page);
|
||||
await page.evaluate((pattern) => {
|
||||
window.__ipc.handlers.search_validate = () => null;
|
||||
window.__ipc.handlers.search_start = ({ query, onEvent }) => {
|
||||
if ((query as SearchQuery).pattern !== pattern) return null;
|
||||
setTimeout(() => {
|
||||
for (const relPath of ["invoice.txt", "receipt.txt"]) {
|
||||
window.__ipc.send(onEvent, {
|
||||
type: "file",
|
||||
file: {
|
||||
path: `/dev/acme-api/${relPath}`,
|
||||
relPath,
|
||||
matches: [{ line: 0, text: pattern, ranges: [[0, pattern.length]], textOffset: 0 }],
|
||||
},
|
||||
});
|
||||
}
|
||||
window.__ipc.send(onEvent, {
|
||||
type: "done",
|
||||
summary: { files: 2, matches: 2, limitHit: false, cancelled: false, elapsedMs: 1 },
|
||||
});
|
||||
}, 20);
|
||||
return null;
|
||||
};
|
||||
}, pattern);
|
||||
await page.keyboard.press("Meta+Shift+r");
|
||||
const popup = page.getByRole("dialog", { name: "Replace in Files", exact: true });
|
||||
await popup.getByRole("textbox", { name: "Text to find", exact: true }).fill(pattern);
|
||||
const replacementInput = popup.getByRole("textbox", { name: "Replace with", exact: true });
|
||||
await replacementInput.fill(replacement);
|
||||
await expect(popup.getByRole("listbox", { name: "Matches" }).getByRole("option")).toHaveCount(2);
|
||||
await page.setViewportSize({ width: 440, height: 520 });
|
||||
await popup.getByRole("button", { name: "Replace All", exact: true }).click();
|
||||
|
||||
const dialog = page.getByRole("dialog", { name: "Replace All", exact: true });
|
||||
const findText = dialog.getByRole("region", { name: "Text to find", exact: true });
|
||||
const replaceText = dialog.getByRole("region", { name: "Replace with", exact: true });
|
||||
const replace = dialog.getByRole("button", { name: "Replace", exact: true });
|
||||
const cancel = dialog.getByRole("button", { name: "Cancel", exact: true });
|
||||
await expect(findText).toHaveText(pattern);
|
||||
await expect(replaceText).toHaveText(replacement);
|
||||
await expect(dialog.getByText("Replace 2 occurrences in 2 files?", { exact: true })).toBeVisible();
|
||||
const bottom = (await replace.boundingBox())!.y;
|
||||
for (const item of [findText, replaceText]) {
|
||||
await expect(item).toHaveCSS("font-size", "13px");
|
||||
expect(await item.evaluate((el) => el.scrollHeight > el.clientHeight && el.scrollWidth === el.clientWidth)).toBe(
|
||||
true,
|
||||
);
|
||||
await item.focus();
|
||||
await page.keyboard.press("End");
|
||||
await expect.poll(() => item.evaluate((el) => el.scrollTop)).toBeGreaterThan(0);
|
||||
}
|
||||
expect((await replace.boundingBox())!.y).toBeCloseTo(bottom, 0);
|
||||
await expect(replace).toBeInViewport({ ratio: 1 });
|
||||
await expect(cancel).toBeInViewport({ ratio: 1 });
|
||||
await cancel.click();
|
||||
await expect(dialog).toBeHidden();
|
||||
|
||||
await page.setViewportSize({ width: 1040, height: 700 });
|
||||
await replacementInput.fill("");
|
||||
await popup.getByRole("button", { name: "Open in Find Window", exact: true }).click();
|
||||
const findWindow = page.getByRole("region", { name: "Find", exact: true });
|
||||
await findWindow.getByRole("button", { name: "Replace All", exact: true }).click();
|
||||
await expect(findText).toHaveText(pattern);
|
||||
await expect(replaceText).toHaveText("Empty text");
|
||||
await cancel.click();
|
||||
expect(await ipcCalls(page, "replace_in_files")).toHaveLength(0);
|
||||
});
|
||||
@@ -581,3 +581,54 @@ test("CMake builds the selected target in Build before starting only the applica
|
||||
await expect(run.getByRole("tab", { name: "hello [Release, release]" })).toBeVisible();
|
||||
await expect(run.getByText("COMPILER_OUTPUT", { exact: true })).toHaveCount(0);
|
||||
});
|
||||
|
||||
test("test report export separates the format and destination in a narrow window", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 410, height: 500 });
|
||||
await stubRun(
|
||||
page,
|
||||
[
|
||||
{
|
||||
kind: "stdout",
|
||||
text: '{"Package":"example.com/checkout","Action":"pass","Test":"TestReceipt","Elapsed":0.1}\n',
|
||||
},
|
||||
],
|
||||
0,
|
||||
{ id: "go:report-tests", name: "Checkout tests", kind: "go", command: "go", args: ["test", "-json"], isTest: true },
|
||||
);
|
||||
await page.evaluate(() => {
|
||||
window.__ipc.handlers.fs_entry_kind = () => {
|
||||
throw { kind: "NotFound", message: "Not found" };
|
||||
};
|
||||
window.__ipc.handlers.fs_create_file_bytes = () => null;
|
||||
});
|
||||
|
||||
await page.keyboard.press("Control+r");
|
||||
const results = page.getByRole("toolbar", { name: "Test results" });
|
||||
await results.getByRole("button", { name: "More Actions" }).click();
|
||||
const exportItem = page.getByRole("menuitem", { name: "Export Test Results…" });
|
||||
await expect(exportItem).toBeEnabled();
|
||||
await exportItem.click();
|
||||
|
||||
const dialog = page.getByRole("dialog", { name: "Export Test Results" });
|
||||
const html = dialog.getByRole("radio", { name: "HTML", exact: true });
|
||||
const xml = dialog.getByRole("radio", { name: "XML", exact: true });
|
||||
await expect(html).toBeVisible();
|
||||
expect((await xml.boundingBox())!.y).toBeGreaterThan((await html.boundingBox())!.y);
|
||||
const file = dialog.getByLabel("File name", { exact: true });
|
||||
const folder = dialog.getByLabel("Folder", { exact: true });
|
||||
const browse = dialog.getByRole("button", { name: "Browse…" });
|
||||
await expect(file).toBeFocused();
|
||||
await expect(file).toHaveValue("Test Results - Checkout tests.html");
|
||||
await expect(folder).toHaveValue("/dev/acme-api");
|
||||
await expect(browse).toBeInViewport({ ratio: 1 });
|
||||
expect((await folder.boundingBox())!.width).toBeGreaterThan(180);
|
||||
await file.fill("receipts.html");
|
||||
await folder.fill("reports");
|
||||
await xml.check();
|
||||
await expect(file).toHaveValue("receipts.xml");
|
||||
await expect(dialog.getByRole("checkbox", { name: "Open exported file in browser" })).toBeDisabled();
|
||||
await dialog.getByRole("button", { name: "OK", exact: true }).click();
|
||||
await expect(dialog).toBeHidden();
|
||||
const [write] = await ipcCalls(page, "fs_create_file_bytes");
|
||||
expect(write).toMatchObject({ path: "/dev/acme-api/reports/receipts.xml" });
|
||||
});
|
||||
+152
-20
@@ -1,39 +1,145 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import type { BeforeLaunchTask } from "../src/bindings";
|
||||
import { expect, test } from "./fixtures";
|
||||
|
||||
async function openConfigurations(page: Page, target?: string) {
|
||||
await page.evaluate(async (target) => {
|
||||
test("expands VM options beside the field and returns edited text to the configuration", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
const original = "-Xmx512m\n-Ddemo.endpoint=https://example.test/" + "long-segment/".repeat(12);
|
||||
await page.evaluate(async (vmOptions) => {
|
||||
const path = "/src/features/run/store.ts";
|
||||
const { useRun } = await import(/* @vite-ignore */ path);
|
||||
const base = {
|
||||
kind: "shell",
|
||||
command: "/Users/developer/projects/acme/services/payments/scripts/start-development-server",
|
||||
args: ["--watch"],
|
||||
cwd: "/Users/developer/projects/acme/services/payments",
|
||||
env: { NODE_ENV: "development" },
|
||||
detected: false,
|
||||
isTest: false,
|
||||
debugAdapter: null,
|
||||
};
|
||||
useRun.setState({
|
||||
configs: [
|
||||
{
|
||||
...base,
|
||||
id: "layout:app",
|
||||
name: "Payments development server",
|
||||
target,
|
||||
beforeLaunch: [{ kind: "run", target: "layout:prepare" }],
|
||||
id: "layout:jvm",
|
||||
name: "Catalog service",
|
||||
kind: "application",
|
||||
command: "java",
|
||||
args: ["example.Catalog"],
|
||||
params: { mainClass: "example.Catalog", vmOptions },
|
||||
env: {},
|
||||
cwd: null,
|
||||
detected: false,
|
||||
isTest: false,
|
||||
debugAdapter: "java-debug",
|
||||
},
|
||||
{ ...base, id: "layout:prepare", name: "Prepare generated sources for the payments development server" },
|
||||
],
|
||||
selectedId: "layout:app",
|
||||
editTarget: "layout:jvm",
|
||||
loaded: true,
|
||||
editorOpen: true,
|
||||
});
|
||||
}, target);
|
||||
}, original);
|
||||
|
||||
const config = page.getByRole("dialog", { name: "Run/Debug Configurations", exact: true });
|
||||
const field = config.getByRole("textbox", { name: "VM options", exact: true });
|
||||
const expanded = page.getByRole("dialog", { name: "VM options", exact: true });
|
||||
const editor = expanded.getByRole("textbox", { name: "VM options", exact: true });
|
||||
for (const width of [1100, 560]) {
|
||||
await page.setViewportSize({ width, height: 760 });
|
||||
await field.scrollIntoViewIfNeeded();
|
||||
await field.press("Shift+Enter");
|
||||
await expect(editor).toBeFocused();
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const source = (await field.boundingBox())!;
|
||||
const popup = (await expanded.boundingBox())!;
|
||||
const gap = Math.min(Math.abs(popup.y - source.y - source.height), Math.abs(source.y - popup.y - popup.height));
|
||||
return popup.x >= 0 && popup.x + popup.width <= width && gap <= 6;
|
||||
})
|
||||
.toBe(true);
|
||||
await expect.poll(() => editor.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeGreaterThan(0);
|
||||
await editor.fill("-Xmx1g");
|
||||
await editor.press("Escape");
|
||||
await expect(expanded).toBeHidden();
|
||||
await expect(field).toBeFocused();
|
||||
await expect(field).toHaveValue(original);
|
||||
}
|
||||
|
||||
const expand = config.getByRole("button", { name: "Expand (⇧⏎)", exact: true });
|
||||
await expand.click();
|
||||
await expect(editor).toBeFocused();
|
||||
await editor.fill(original + "\n-Ddemo.mode=local");
|
||||
await editor.press("Control+Enter");
|
||||
await expect(expanded).toBeHidden();
|
||||
await expect(field).toHaveValue(original + "\n-Ddemo.mode=local");
|
||||
});
|
||||
|
||||
async function openConfigurations(page: Page, target?: string, beforeLaunch?: BeforeLaunchTask[]) {
|
||||
await page.evaluate(
|
||||
async ({ target, beforeLaunch }) => {
|
||||
const path = "/src/features/run/store.ts";
|
||||
const { useRun } = await import(/* @vite-ignore */ path);
|
||||
const base = {
|
||||
kind: "shell",
|
||||
command: "/Users/developer/projects/acme/services/payments/scripts/start-development-server",
|
||||
args: ["--watch"],
|
||||
cwd: "/Users/developer/projects/acme/services/payments",
|
||||
env: { NODE_ENV: "development" },
|
||||
detected: false,
|
||||
isTest: false,
|
||||
debugAdapter: null,
|
||||
};
|
||||
useRun.setState({
|
||||
configs: [
|
||||
{
|
||||
...base,
|
||||
id: "layout:app",
|
||||
name: "Payments development server",
|
||||
target,
|
||||
beforeLaunch: beforeLaunch ?? [{ kind: "run", target: "layout:prepare" }],
|
||||
},
|
||||
{ ...base, id: "layout:prepare", name: "Prepare generated sources for the payments development server" },
|
||||
],
|
||||
selectedId: "layout:app",
|
||||
loaded: true,
|
||||
editorOpen: true,
|
||||
});
|
||||
},
|
||||
{ target, beforeLaunch },
|
||||
);
|
||||
await expect(page.getByRole("dialog", { name: "Run/Debug Configurations", exact: true })).toBeVisible();
|
||||
}
|
||||
|
||||
test("before-launch tasks wrap as ordered tags and keep their edit controls", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 1150, height: 820 });
|
||||
await openConfigurations(page, undefined, [
|
||||
{ kind: "build" },
|
||||
{ kind: "buildArtifacts" },
|
||||
{ kind: "command", target: "make generate" },
|
||||
]);
|
||||
const dialog = page.getByRole("dialog", { name: "Run/Debug Configurations", exact: true });
|
||||
const tasks = dialog.getByRole("list", { name: "Before launch tasks", exact: true });
|
||||
const build = tasks.getByRole("button", { name: "1. Build Project", exact: true });
|
||||
const artifacts = tasks.getByRole("button", { name: "2. Build Artifacts", exact: true });
|
||||
await tasks.scrollIntoViewIfNeeded();
|
||||
await expect(build).toBeVisible();
|
||||
expect((await build.boundingBox())!.y).toBeCloseTo((await artifacts.boundingBox())!.y, 0);
|
||||
await expect(build).toHaveCSS("font-size", "13px");
|
||||
|
||||
await page.setViewportSize({ width: 520, height: 820 });
|
||||
await expect.poll(() => tasks.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
|
||||
const command = tasks.getByRole("textbox", { name: "Before launch command 3" });
|
||||
expect((await command.boundingBox())!.y).toBeGreaterThan((await build.boundingBox())!.y + 20);
|
||||
await command.fill("make report");
|
||||
|
||||
await build.press("Enter");
|
||||
const actions = page.getByRole("menu", { name: "Task Actions", exact: true });
|
||||
const moveDown = actions.getByRole("menuitem", { name: "Move Down", exact: true });
|
||||
await expect(moveDown).toBeVisible();
|
||||
await moveDown.click();
|
||||
await expect(tasks.getByRole("button", { name: "1. Build Artifacts", exact: true })).toBeVisible();
|
||||
const moved = tasks.getByRole("listitem").filter({
|
||||
has: page.getByRole("button", { name: "2. Build Project", exact: true }),
|
||||
});
|
||||
await moved.getByRole("button", { name: "Remove Task" }).click();
|
||||
await expect(tasks.getByRole("textbox", { name: "Before launch command 2" })).toHaveValue("make report");
|
||||
|
||||
await tasks.getByRole("button", { name: "Add task", exact: true }).click();
|
||||
await page.getByRole("menuitem", { name: "Build Project", exact: true }).click();
|
||||
await expect(tasks.getByRole("button", { name: "3. Build Project", exact: true })).toBeVisible();
|
||||
});
|
||||
|
||||
test("long run target names leave room for configuration names in the sidebar", async ({ workbench: page }) => {
|
||||
const target = "payments-development-shared-staging-runner-west";
|
||||
await openConfigurations(page, target);
|
||||
@@ -55,6 +161,32 @@ test("long run target names leave room for configuration names in the sidebar",
|
||||
await expect(dialog.getByRole("textbox", { name: "Name", exact: true })).toHaveValue("Payments development server");
|
||||
});
|
||||
|
||||
test("the configuration type list scrolls below its search field in a short window", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 780, height: 370 });
|
||||
await openConfigurations(page);
|
||||
const dialog = page.getByRole("dialog", { name: "Run/Debug Configurations", exact: true });
|
||||
await dialog.getByRole("button", { name: "Add New Configuration", exact: true }).click();
|
||||
const chooser = page.getByRole("dialog", { name: "Add New Configuration", exact: true });
|
||||
const search = chooser.getByRole("textbox", { name: "Search configuration types" });
|
||||
const list = chooser.getByRole("listbox", { name: "Configuration types" });
|
||||
await expect(search).toBeFocused();
|
||||
expect(await chooser.evaluate((el) => el.scrollHeight - el.clientHeight)).toBeLessThanOrEqual(1);
|
||||
expect(await list.evaluate((el) => el.scrollHeight - el.clientHeight)).toBeGreaterThan(0);
|
||||
|
||||
await search.press("End");
|
||||
const active = list.getByRole("option", { selected: true });
|
||||
await expect(active).toBeInViewport({ ratio: 0.98 });
|
||||
expect(await list.evaluate((el) => el.scrollTop)).toBeGreaterThan(0);
|
||||
await expect(active.locator("svg")).toHaveAttribute("width", "16");
|
||||
await expect(search).toBeInViewport({ ratio: 1 });
|
||||
|
||||
await search.fill("Tomcat");
|
||||
await expect(list.getByRole("option", { name: "Tomcat Server", selected: true })).toBeVisible();
|
||||
await search.press("Enter");
|
||||
await expect(chooser).toBeHidden();
|
||||
await expect(dialog.getByRole("tab", { name: "Server", exact: true })).toBeVisible();
|
||||
});
|
||||
|
||||
test("run configuration sidebar resizes with mouse and keyboard and remembers the layout", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
|
||||
|
||||
const prefix = "reconcile-regional-inventory-and-rebuild-order-settlement-cache-for-warehouse-";
|
||||
const east = prefix + "east-stage";
|
||||
const west = prefix + "west-stage";
|
||||
const content = JSON.stringify(
|
||||
{ name: "warehouse-tools", scripts: { [east]: "node east.js", [west]: "node west.js", build: "node build.js" } },
|
||||
null,
|
||||
2,
|
||||
);
|
||||
|
||||
test("the npm gutter keeps distinct ends of long names and runs the selected script", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 440, height: 520 });
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async (text) => {
|
||||
const backendPath = "/src/editor/core/backend.ts";
|
||||
const servicePath = "/src/workbench/contributions.ts";
|
||||
const { docBackend } = await import(/* @vite-ignore */ backendPath);
|
||||
const { editorService } = await import(/* @vite-ignore */ servicePath);
|
||||
const path = "/dev/acme-api/package.json";
|
||||
docBackend().files.set(path, text);
|
||||
const handlers = window.__ipc.handlers;
|
||||
handlers.fs_probe = () => ({ size: text.length, binary: false, tooLarge: false });
|
||||
handlers.fs_read_text = ({ path }) => docBackend().files.get(String(path)) ?? "";
|
||||
handlers.fs_read_dir = () => [];
|
||||
handlers.run_configs = () => [];
|
||||
handlers.run_start = ({ config }) => ({
|
||||
id: 7,
|
||||
configId: (config as { id: string }).id,
|
||||
name: (config as { name: string }).name,
|
||||
pid: 4242,
|
||||
running: true,
|
||||
pty: false,
|
||||
});
|
||||
await editorService().openFile(path);
|
||||
}, content);
|
||||
const editor = page.locator(".cm-editor");
|
||||
const menu = page.getByRole("menu", { name: "Context menu" });
|
||||
for (const name of [east, west]) {
|
||||
await editor.getByTitle("Run '" + name + "'", { exact: true }).click();
|
||||
const label = "Run 'npm run " + name + "'";
|
||||
const run = menu.getByRole("menuitem", { name: label, exact: true });
|
||||
const end = run.getByText(label.slice(-12), { exact: true });
|
||||
await expect(end).toBeVisible();
|
||||
await expect(end.locator("..")).toHaveAttribute("title", label);
|
||||
expect(await end.evaluate((node) => node.clientWidth >= node.scrollWidth)).toBe(true);
|
||||
const start = end.locator("..").locator(":scope > span").first();
|
||||
expect(await start.evaluate((node) => node.clientWidth < node.scrollWidth)).toBe(true);
|
||||
await expect(start).toHaveCSS("text-overflow", "ellipsis");
|
||||
const titleUnderPointer = await start.evaluate((node) => {
|
||||
const { x, y, width, height } = node.getBoundingClientRect();
|
||||
return document.elementFromPoint(x + width / 2, y + height / 2)?.getAttribute("title");
|
||||
});
|
||||
expect(titleUnderPointer).toBe(label);
|
||||
await expect(run).toBeFocused();
|
||||
if (name === east) await run.press("Escape");
|
||||
else await run.press("Enter");
|
||||
await expect(menu).toBeHidden();
|
||||
}
|
||||
await expect
|
||||
.poll(async () => ipcCalls(page, "run_start"))
|
||||
.toMatchObject([{ config: { args: ["run", west], kind: "npm" } }]);
|
||||
});
|
||||
+4
-1
@@ -122,7 +122,10 @@ test("Find in Files streams matches by file and opens the chosen one at its line
|
||||
const expected = getComputedStyle(probe).backgroundColor;
|
||||
probe.remove();
|
||||
const own = getComputedStyle(el);
|
||||
return own.backgroundColor === expected && own.color === getComputedStyle(el.parentElement!).color;
|
||||
return (
|
||||
(own.backgroundColor === expected || own.backgroundImage.includes(expected)) &&
|
||||
own.color === getComputedStyle(el.parentElement!).color
|
||||
);
|
||||
}),
|
||||
).toBe(true);
|
||||
const originalPreview = await preview.textContent();
|
||||
|
||||
@@ -1,4 +1,64 @@
|
||||
import { doubleShift, expect, stubDesktop, test } from "./fixtures";
|
||||
|
||||
test("Search Everywhere keeps line numbers visible beside long Text result filenames", async ({ workbench: page }) => {
|
||||
const relPath = "config/InternationalSettlementReconciliationEndpointsForStagingEnvironments.ts";
|
||||
const query = "settlementEndpoint";
|
||||
const text = `const ${query} = "/staging/settlement";`;
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(
|
||||
({ relPath, text, query }) => {
|
||||
window.__ipc.handlers.search_start = (args) => {
|
||||
setTimeout(() => {
|
||||
const matches = [12344, 12345].map((line) => ({
|
||||
line,
|
||||
text,
|
||||
ranges: [[6, 6 + query.length]],
|
||||
textOffset: 0,
|
||||
}));
|
||||
window.__ipc.send(args.onEvent, {
|
||||
type: "file",
|
||||
file: { path: `/dev/acme-api/${relPath}`, relPath, matches },
|
||||
});
|
||||
window.__ipc.send(args.onEvent, {
|
||||
type: "done",
|
||||
summary: { files: 1, matches: 2, limitHit: false, cancelled: false, elapsedMs: 4 },
|
||||
});
|
||||
}, 20);
|
||||
return null;
|
||||
};
|
||||
},
|
||||
{ relPath, text, query },
|
||||
);
|
||||
|
||||
await doubleShift(page);
|
||||
const dialog = page.getByRole("dialog", { name: "Search Everywhere" });
|
||||
await dialog.getByRole("tab", { name: "Text", exact: true }).click();
|
||||
const search = dialog.getByRole("combobox", { name: "Search query" });
|
||||
await search.fill(query);
|
||||
const rows = dialog.getByRole("option");
|
||||
await expect(rows).toHaveCount(2);
|
||||
for (const width of [920, 440]) {
|
||||
await page.setViewportSize({ width, height: 640 });
|
||||
for (const line of [12345, 12346]) {
|
||||
const row = rows.filter({ hasText: String(line) });
|
||||
await expect(row.locator("mark")).toHaveText(query);
|
||||
expect(
|
||||
await row.evaluate((el) => {
|
||||
const location = el.lastElementChild!;
|
||||
const lineText = location.lastChild!;
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(lineText);
|
||||
const bounds = range.getBoundingClientRect();
|
||||
const clip = location.getBoundingClientRect();
|
||||
return bounds.width > 0 && bounds.left >= clip.left && bounds.right <= clip.right + 1;
|
||||
}),
|
||||
).toBe(true);
|
||||
await expect(row.getByText(relPath.split("/").at(-1)!, { exact: true })).toHaveAttribute("title", relPath);
|
||||
}
|
||||
}
|
||||
await search.press("ArrowDown");
|
||||
await expect(rows.nth(1)).toHaveAttribute("aria-selected", "true");
|
||||
});
|
||||
import type { Page } from "@playwright/test";
|
||||
|
||||
test("action names stay readable beside shortcuts and categories", async ({ workbench: page }) => {
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
* header on screen: titles stay on one line and every header control lies inside the popup.
|
||||
*/
|
||||
import type { Page } from "@playwright/test";
|
||||
import { expect, openFromTree, stubDesktop, test } from "./fixtures";
|
||||
import { expect, ipcCalls, openFromTree, stubDesktop, test } from "./fixtures";
|
||||
|
||||
const LONG_RESULT_PATH = "config/RegionalOrderReconciliationEndpointsForSandboxEnvironments.txt";
|
||||
|
||||
@@ -15,7 +15,7 @@ async function run(page: Page, id: string) {
|
||||
}, id);
|
||||
}
|
||||
|
||||
async function stubFindMatches(page: Page) {
|
||||
async function stubFindMatches(page: Page, firstPath = LONG_RESULT_PATH) {
|
||||
await stubDesktop(page);
|
||||
await page.evaluate((longPath) => {
|
||||
window.__ipc.handlers.search_validate = () => null;
|
||||
@@ -39,7 +39,7 @@ async function stubFindMatches(page: Page) {
|
||||
}, 20);
|
||||
return null;
|
||||
};
|
||||
}, LONG_RESULT_PATH);
|
||||
}, firstPath);
|
||||
}
|
||||
|
||||
async function expectControlsFit(page: Page) {
|
||||
@@ -118,6 +118,35 @@ test.describe("search popups at the minimum window width", () => {
|
||||
await dialog.getByRole("button", { name: /Browse/ }).click({ trial: true });
|
||||
});
|
||||
|
||||
test("multi-line search and replacement leave room for matches and scroll inside their fields", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await stubFindMatches(page);
|
||||
await run(page, "find.replaceInPath");
|
||||
const dialog = page.getByRole("dialog", { name: "Replace in Files" });
|
||||
const search = dialog.getByRole("textbox", { name: "Text to find" });
|
||||
const replacement = dialog.getByRole("textbox", { name: "Replace with" });
|
||||
const query = "base=http://localhost:8080\nregion=eu-west\nmode=batch\nverify=true\nretry=2\ntimeout=30";
|
||||
const changed = query.replace("localhost:8080", "localhost:9443").replace("retry=2", "retry=4");
|
||||
await search.fill(query);
|
||||
await replacement.fill(changed);
|
||||
for (const field of [search, replacement]) {
|
||||
const visibleLines = await field.evaluate((el) => el.clientHeight / parseFloat(getComputedStyle(el).lineHeight));
|
||||
expect(visibleLines).toBeCloseTo(3);
|
||||
await field.press("Control+End");
|
||||
await expect.poll(() => field.evaluate((el) => el.scrollTop)).toBeGreaterThan(0);
|
||||
}
|
||||
await expect(search).toHaveValue(query);
|
||||
await expect(replacement).toHaveValue(changed);
|
||||
await expect(dialog.getByRole("listbox", { name: "Matches" }).getByRole("option").first()).toBeInViewport();
|
||||
const calls = await ipcCalls(page, "search_start");
|
||||
expect(calls.some(({ query: sent }) => (sent as { pattern: string }).pattern === query)).toBe(true);
|
||||
await expect(dialog.getByRole("button", { name: "Replace All", exact: true })).toBeInViewport({ ratio: 1 });
|
||||
|
||||
await replacement.fill("updated");
|
||||
await expect(replacement).toHaveAttribute("rows", "1");
|
||||
});
|
||||
|
||||
test("Replace in Files keeps its footer actions together as the window narrows", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 1120, height: 750 });
|
||||
await openFromTree(page, "settings.gradle.kts");
|
||||
@@ -205,3 +234,29 @@ test("Find in Files prioritizes the preview and remembers an adjusted split", as
|
||||
await expect(handle).toBeAttached();
|
||||
await expect.poll(resultsShare).toBeCloseTo(adjusted, 2);
|
||||
});
|
||||
|
||||
test("Find in Files keeps the file and its parent folder visible in the preview caption", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 400, height: 570 });
|
||||
const prefix = "config/generated/regional-integrations/sandbox/development/notifications";
|
||||
const name = "RegionalLedgerSettings.txt";
|
||||
const path = `${prefix}/runtime/${name}`;
|
||||
await stubFindMatches(page, path);
|
||||
await run(page, "find.inPath");
|
||||
const dialog = page.getByRole("dialog", { name: "Find in Files" });
|
||||
const search = dialog.getByPlaceholder("Search");
|
||||
await search.fill("http://localhost:8080");
|
||||
const preview = dialog.locator("[data-panel][id=preview]");
|
||||
const caption = preview.getByTitle(path, { exact: true });
|
||||
const folder = caption.getByText("/runtime", { exact: true });
|
||||
const beginning = caption.getByText(prefix, { exact: true });
|
||||
await expect(caption.getByText(name, { exact: true })).toBeInViewport({ ratio: 1 });
|
||||
await expect(folder).toBeInViewport({ ratio: 1 });
|
||||
await expect(folder).toHaveCSS("font-size", "13px");
|
||||
expect(await beginning.evaluate((el) => el.scrollWidth > el.clientWidth)).toBe(true);
|
||||
expect(await folder.evaluate((el) => el.scrollWidth <= el.clientWidth)).toBe(true);
|
||||
await search.press("ArrowDown");
|
||||
await search.press("ArrowDown");
|
||||
await expect(preview.getByTitle("config/endpoint-1.txt", { exact: true })).toContainText("endpoint-1.txt");
|
||||
});
|
||||
@@ -0,0 +1,66 @@
|
||||
import { expect, test } from "./fixtures";
|
||||
|
||||
test("Find in Files keeps the scope list and pattern editor usable in a narrow window", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 1040, height: 700 });
|
||||
const longName = "Regional settlement reconciliation sources for month-end audit and publication";
|
||||
await page.evaluate(async (longName) => {
|
||||
const search = "/src/platform/search.ts";
|
||||
const { saveCustomScopes } = await import(/* @vite-ignore */ search);
|
||||
saveCustomScopes(
|
||||
Array.from({ length: 26 }, (_, i) => ({
|
||||
name: i ? `Reconciliation scope ${i + 1}` : longName,
|
||||
pattern: i ? `file:src/scope-${i + 1}//*` : "file:src/reconciliation//*",
|
||||
})),
|
||||
);
|
||||
}, longName);
|
||||
await page.keyboard.press("Meta+Shift+F");
|
||||
const find = page.getByRole("dialog", { name: "Find in Files", exact: true });
|
||||
await find.getByRole("tab", { name: "Scope", exact: true }).click();
|
||||
const openScopes = find.getByRole("button", { name: "Edit Scopes…", exact: true });
|
||||
await openScopes.click();
|
||||
|
||||
const dialog = page.getByRole("dialog", { name: "Scopes", exact: true });
|
||||
const list = dialog.getByRole("list", { name: "Scopes", exact: true });
|
||||
const name = dialog.getByRole("textbox", { name: "Name:", exact: true });
|
||||
const pattern = dialog.getByRole("textbox", { name: "Pattern:", exact: true });
|
||||
await expect(pattern).toHaveValue("file:src/reconciliation//*");
|
||||
expect(await list.evaluate((el) => el.scrollHeight - el.clientHeight)).toBeGreaterThan(100);
|
||||
await expect(list.getByRole("button", { name: longName })).toHaveAttribute("title", longName);
|
||||
expect((await list.boundingBox())!.x).toBeLessThan((await name.boundingBox())!.x);
|
||||
|
||||
await page.setViewportSize({ width: 460, height: 530 });
|
||||
// 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));
|
||||
expect((await pattern.boundingBox())!.y).toBeCloseTo(fields.y, 0);
|
||||
const toolbar = dialog.getByRole("toolbar", { name: "Scopes actions" });
|
||||
const add = toolbar.getByRole("button", { name: "Add Scope", exact: true });
|
||||
const ok = dialog.getByRole("button", { name: "OK", exact: true });
|
||||
await expect(add).toBeInViewport({ ratio: 1 });
|
||||
await expect(ok).toBeInViewport({ ratio: 1 });
|
||||
|
||||
await name.fill("Unsaved selection");
|
||||
await dialog.getByRole("button", { name: "Cancel", exact: true }).click();
|
||||
await openScopes.click();
|
||||
await expect(name).toHaveValue(longName);
|
||||
await add.click();
|
||||
const draft = list.getByRole("button", { name: "Unnamed", exact: true });
|
||||
await expect(draft).toHaveAttribute("aria-current", "true");
|
||||
await expect(draft).toBeInViewport({ ratio: 1 });
|
||||
await expect(ok).toBeDisabled();
|
||||
await name.fill("Release inputs");
|
||||
await pattern.fill("file:src/release//*");
|
||||
await ok.click();
|
||||
await expect(dialog).toBeHidden();
|
||||
await openScopes.click();
|
||||
await list.getByRole("button", { name: "Release inputs", exact: true }).click();
|
||||
await expect(pattern).toHaveValue("file:src/release//*");
|
||||
});
|
||||
+439
-1
@@ -1,5 +1,5 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import { expect, test } from "./fixtures";
|
||||
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
|
||||
|
||||
/** Supply detected configurations without launching desktop processes. */
|
||||
async function configure(page: Page, extra = 0) {
|
||||
@@ -241,3 +241,441 @@ test("the Services detail pane adds no second scrollbar over a console", async (
|
||||
expect(result.scrollers.filter((c) => c.includes("detailPane") || c.includes("_panel_"))).toEqual([]);
|
||||
expect(result.scrollers.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
test("Docker dashboard keeps multi-line container commands bounded and collapsible", async ({ workbench: page }) => {
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async () => {
|
||||
const script = Array.from({ length: 18 }, (_, i) => ` export STEP_${i}="/persist/slot-${i}"`).join("\n");
|
||||
const inspectJson = JSON.stringify([
|
||||
{
|
||||
Created: "2026-11-22T01:41:28Z",
|
||||
State: { Status: "running", Pid: 2048, StartedAt: "2026-11-22T01:41:29Z" },
|
||||
HostConfig: { RestartPolicy: { Name: "unless-stopped", MaximumRetryCount: 0 } },
|
||||
Config: {
|
||||
Entrypoint: ["/bin/bash", "-ec", `set -euo pipefail\n${script}\nexec /entrypoint.sh "$@"\n`, "--"],
|
||||
Cmd: ["./bin/Runner.Listener", "run", "--startuptype", "service"],
|
||||
WorkingDir: "/actions-runner",
|
||||
Env: [],
|
||||
Labels: {},
|
||||
},
|
||||
Mounts: [],
|
||||
NetworkSettings: { Ports: {}, Networks: {} },
|
||||
},
|
||||
]);
|
||||
const containerId = "13de5573bf36a9c8d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2c3";
|
||||
const snapshot = {
|
||||
availability: { kind: "ready", clientVersion: "27.3.1", serverVersion: "27.3.1", context: null },
|
||||
executable: "/usr/local/bin/docker",
|
||||
containers: [
|
||||
{
|
||||
id: containerId,
|
||||
name: "runner-1",
|
||||
image: "myoung34/github-runner:latest",
|
||||
command: '"/bin/bash -ec \'set…"',
|
||||
state: "running",
|
||||
status: "Up 2 hours",
|
||||
ports: "",
|
||||
createdAt: "2026-11-22 01:41:28 +0000 UTC",
|
||||
composeProject: "selfhost",
|
||||
composeService: "github-runner",
|
||||
composeWorkingDir: "/Users/dev/selfhost",
|
||||
composeFiles: ["/Users/dev/selfhost/docker-compose.yml"],
|
||||
},
|
||||
],
|
||||
images: [],
|
||||
volumes: [],
|
||||
networks: [],
|
||||
errors: [],
|
||||
};
|
||||
window.__ipc.handlers.docker_settings = () => ({
|
||||
connections: [{ id: "local", name: "Docker", endpoint: { kind: "default" } }],
|
||||
registries: [],
|
||||
});
|
||||
window.__ipc.handlers.docker_snapshot = () => snapshot;
|
||||
window.__ipc.handlers.docker_inspect = () => inspectJson;
|
||||
window.__ipc.handlers.docker_container_stats = () => ({
|
||||
cpuPerc: "1.20%",
|
||||
memUsage: "256MiB / 8GiB",
|
||||
memPerc: "3.12%",
|
||||
netIo: "1MB / 1MB",
|
||||
blockIo: "0B / 0B",
|
||||
pids: "12",
|
||||
});
|
||||
window.__ipc.handlers.docker_events = () => new Promise(() => {});
|
||||
window.__ipc.handlers.cancel_request = () => null;
|
||||
|
||||
const storeModule = "/src/features/services/store.ts";
|
||||
const treeModule = "/src/features/services/tree.ts";
|
||||
const { useServices } = await import(/* @vite-ignore */ storeModule);
|
||||
const { useServicesTree } = await import(/* @vite-ignore */ treeModule);
|
||||
useServices.setState({
|
||||
settings: { connections: [{ id: "local", name: "Docker", endpoint: { kind: "default" } }], registries: [] },
|
||||
conns: { local: { snapshot, loading: false, error: null } },
|
||||
detailTab: "dashboard",
|
||||
});
|
||||
useServicesTree.setState({
|
||||
expanded: new Set(["docker:local", "docker:local:compose:selfhost"]),
|
||||
selectedKey: `docker:local:container:${containerId}`,
|
||||
selectedKeys: new Set([`docker:local:container:${containerId}`]),
|
||||
});
|
||||
});
|
||||
|
||||
await page.keyboard.press("Meta+8");
|
||||
const services = page.getByRole("region", { name: "Services", exact: true });
|
||||
await expect(services.getByText("Container Overview")).toBeVisible();
|
||||
|
||||
const toggle = services.getByRole("button", { name: /^\d+ lines$/ });
|
||||
await expect(toggle).toHaveAttribute("aria-expanded", "false");
|
||||
|
||||
const preview = services.locator("code[data-no-tooltip]");
|
||||
await expect(preview).toContainText("↵");
|
||||
|
||||
// Hovering the truncated command preview must not spawn a giant auto-ellipsis tooltip.
|
||||
await preview.hover();
|
||||
await page.waitForTimeout(700);
|
||||
await expect(page.getByRole("tooltip")).toHaveCount(0);
|
||||
|
||||
// Collapsed row stays strictly between Started and Working directory (no upward overlap).
|
||||
const startedLabel = services.getByText("Started", { exact: true });
|
||||
const commandLabel = services.getByText("Command", { exact: true });
|
||||
const workingDirLabel = services.getByText("Working directory", { exact: true });
|
||||
const collapsedStartedBox = (await startedLabel.boundingBox())!;
|
||||
const collapsedPreviewBox = (await preview.boundingBox())!;
|
||||
const collapsedWorkingBox = (await workingDirLabel.boundingBox())!;
|
||||
expect(collapsedPreviewBox.y).toBeGreaterThan(collapsedStartedBox.y + collapsedStartedBox.height);
|
||||
expect(collapsedWorkingBox.y).toBeGreaterThan(collapsedPreviewBox.y + collapsedPreviewBox.height);
|
||||
|
||||
// Expanding reveals Entrypoint + Command arguments inside a bounded scroll box growing downward.
|
||||
await toggle.click();
|
||||
const collapseBtn = services.getByRole("button", { name: "Collapse", exact: true });
|
||||
await expect(collapseBtn).toHaveAttribute("aria-expanded", "true");
|
||||
await expect(services.getByText("Entrypoint", { exact: true })).toBeVisible();
|
||||
await expect(services.getByText("Command arguments", { exact: true })).toBeVisible();
|
||||
|
||||
const expandedStartedBox = (await startedLabel.boundingBox())!;
|
||||
const expandedCommandLabelBox = (await commandLabel.boundingBox())!;
|
||||
const entrypointPre = services.locator("pre").first();
|
||||
const scrollContainer = entrypointPre.locator("xpath=ancestor::div[1]/parent::div");
|
||||
const scrollBox = (await scrollContainer.boundingBox())!;
|
||||
const expandedWorkingBox = (await workingDirLabel.boundingBox())!;
|
||||
|
||||
expect(expandedCommandLabelBox.y).toBeGreaterThan(expandedStartedBox.y + expandedStartedBox.height);
|
||||
expect(scrollBox.y).toBeGreaterThan(expandedCommandLabelBox.y);
|
||||
expect(scrollBox.height).toBeLessThanOrEqual(182);
|
||||
expect(expandedWorkingBox.y).toBeGreaterThanOrEqual(scrollBox.y + scrollBox.height - 1);
|
||||
|
||||
await collapseBtn.click();
|
||||
await expect(services.getByRole("button", { name: /^\d+ lines$/ })).toHaveAttribute("aria-expanded", "false");
|
||||
});
|
||||
|
||||
test("Docker Compose container Jump to Source opens the Compose file at the command or the service", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async () => {
|
||||
const composePath = "/dev/acme-api/docker-compose.yml";
|
||||
const composeYaml = [
|
||||
"services:",
|
||||
" postgres:",
|
||||
" image: postgres:16",
|
||||
" github-runner:",
|
||||
" image: myoung34/github-runner:latest",
|
||||
" entrypoint:",
|
||||
" - /bin/bash",
|
||||
" - -ec",
|
||||
" - |",
|
||||
" mkdir -p /persist/slots",
|
||||
' exec /entrypoint.sh "$@"',
|
||||
' command: ["./bin/Runner.Listener", "run", "--startuptype", "service"]',
|
||||
"",
|
||||
].join("\n");
|
||||
|
||||
const backendModule = "/src/editor/core/backend.ts";
|
||||
const { docBackend } = await import(/* @vite-ignore */ backendModule);
|
||||
docBackend().files.set(composePath, composeYaml);
|
||||
window.__ipc.handlers.fs_read_text = ({ path }) => {
|
||||
if (path === composePath) return composeYaml;
|
||||
throw { kind: "notFound", message: `not found: ${String(path)}`, detail: null };
|
||||
};
|
||||
|
||||
const runnerId = "13de5573bf36a9c8d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2c3";
|
||||
const dbId = "98ab76cd54ef3210fedcba9876543210abcdef0123456789abcdef0123456789";
|
||||
const snapshot = {
|
||||
availability: { kind: "ready", clientVersion: "27.3.1", serverVersion: "27.3.1", context: null },
|
||||
executable: "/usr/local/bin/docker",
|
||||
containers: [
|
||||
{
|
||||
id: runnerId,
|
||||
name: "selfhost-github-runner-1",
|
||||
image: "myoung34/github-runner:latest",
|
||||
command: '"/bin/bash -ec \'mkdir…"',
|
||||
state: "running",
|
||||
status: "Up 2 hours",
|
||||
ports: "",
|
||||
createdAt: "2026-11-22 01:41:28 +0000 UTC",
|
||||
composeProject: "selfhost",
|
||||
composeService: "github-runner",
|
||||
composeWorkingDir: "/dev/acme-api",
|
||||
composeFiles: [composePath],
|
||||
},
|
||||
{
|
||||
id: dbId,
|
||||
name: "selfhost-postgres-1",
|
||||
image: "postgres:16",
|
||||
command: "postgres",
|
||||
state: "running",
|
||||
status: "Up 2 hours",
|
||||
ports: "",
|
||||
createdAt: "2026-11-22 01:41:28 +0000 UTC",
|
||||
composeProject: "selfhost",
|
||||
composeService: "postgres",
|
||||
composeWorkingDir: "/dev/acme-api",
|
||||
composeFiles: [composePath],
|
||||
},
|
||||
],
|
||||
images: [],
|
||||
volumes: [],
|
||||
networks: [],
|
||||
errors: [],
|
||||
};
|
||||
|
||||
window.__ipc.handlers.docker_settings = () => ({
|
||||
connections: [{ id: "local", name: "Docker", endpoint: { kind: "default" } }],
|
||||
registries: [],
|
||||
});
|
||||
window.__ipc.handlers.docker_snapshot = () => snapshot;
|
||||
window.__ipc.handlers.docker_inspect = () =>
|
||||
JSON.stringify([
|
||||
{
|
||||
Created: "2026-11-22T01:41:28Z",
|
||||
State: { Status: "running", Pid: 2048, StartedAt: "2026-11-22T01:41:29Z" },
|
||||
HostConfig: { RestartPolicy: { Name: "unless-stopped", MaximumRetryCount: 0 } },
|
||||
Config: {
|
||||
Entrypoint: ["/bin/bash", "-ec", 'mkdir -p /persist/slots\nexec /entrypoint.sh "$@"'],
|
||||
Cmd: ["./bin/Runner.Listener", "run", "--startuptype", "service"],
|
||||
WorkingDir: "/actions-runner",
|
||||
Env: [],
|
||||
Labels: {},
|
||||
},
|
||||
Mounts: [],
|
||||
NetworkSettings: { Ports: {}, Networks: {} },
|
||||
},
|
||||
]);
|
||||
window.__ipc.handlers.docker_container_stats = () => ({
|
||||
cpuPerc: "0.50%",
|
||||
memUsage: "128MiB / 8GiB",
|
||||
memPerc: "1.56%",
|
||||
netIo: "0B / 0B",
|
||||
blockIo: "0B / 0B",
|
||||
pids: "4",
|
||||
});
|
||||
window.__ipc.handlers.docker_events = () => new Promise(() => {});
|
||||
window.__ipc.handlers.cancel_request = () => null;
|
||||
|
||||
const storeModule = "/src/features/services/store.ts";
|
||||
const treeModule = "/src/features/services/tree.ts";
|
||||
const { useServices } = await import(/* @vite-ignore */ storeModule);
|
||||
const { useServicesTree } = await import(/* @vite-ignore */ treeModule);
|
||||
useServices.setState({
|
||||
settings: { connections: [{ id: "local", name: "Docker", endpoint: { kind: "default" } }], registries: [] },
|
||||
conns: { local: { snapshot, loading: false, error: null } },
|
||||
detailTab: "dashboard",
|
||||
});
|
||||
useServicesTree.setState({
|
||||
expanded: new Set(["docker:local", "docker:local:compose:selfhost"]),
|
||||
selectedKey: `docker:local:container:${runnerId}`,
|
||||
selectedKeys: new Set([`docker:local:container:${runnerId}`]),
|
||||
});
|
||||
});
|
||||
|
||||
await page.keyboard.press("Meta+8");
|
||||
const services = page.getByRole("region", { name: "Services", exact: true });
|
||||
await expect(services.getByText("Container Overview")).toBeVisible();
|
||||
|
||||
// Clicking Jump to Source on the Command row opens docker-compose.yml with caret on `command:` value
|
||||
await services.getByRole("button", { name: "Jump to Source", exact: true }).click();
|
||||
const editor = page.locator(".cm-editor");
|
||||
await expect(editor.locator(".cm-activeLine")).toHaveText(
|
||||
' command: ["./bin/Runner.Listener", "run", "--startuptype", "service"]',
|
||||
);
|
||||
const caret = await page.evaluate(async () => {
|
||||
const api = await import(/* @vite-ignore */ "/src/editor/api.ts" as string);
|
||||
const view = api.activeEditor()?.view;
|
||||
if (!view) return null;
|
||||
const head = view.state.selection.main.head;
|
||||
const line = view.state.doc.lineAt(head);
|
||||
return { line: line.number - 1, col: head - line.from };
|
||||
});
|
||||
expect(caret).toEqual({ line: 11, col: 13 });
|
||||
|
||||
// F4 on a Compose container node jumps to its service declaration
|
||||
const tree = services.getByRole("tree", { name: "Services", exact: true });
|
||||
await tree.getByRole("treeitem", { name: /github-runner/ }).click();
|
||||
await page.keyboard.press("F4");
|
||||
await expect(editor.locator(".cm-activeLine")).toHaveText(" github-runner:");
|
||||
await tree.getByRole("treeitem", { name: /postgres/ }).click();
|
||||
await page.keyboard.press("F4");
|
||||
await expect(editor.locator(".cm-activeLine")).toHaveText(" postgres:");
|
||||
});
|
||||
|
||||
test("Docker Compose dashboard shows per-service resource usage and named project volumes", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async () => {
|
||||
(window as unknown as { __cpuPerc: string }).__cpuPerc = "6.25%";
|
||||
const anonName = "37cc33a7d603260a82a378d7d3eeb835b748b5712614e2e5b4a3d6572f5e1e71";
|
||||
const snapshot = {
|
||||
availability: { kind: "ready", clientVersion: "28.0.1", serverVersion: "28.0.1", context: null },
|
||||
executable: "/usr/bin/docker",
|
||||
containers: [
|
||||
{
|
||||
id: "db-1",
|
||||
name: "shop-db-1",
|
||||
image: "postgres:16",
|
||||
command: "postgres",
|
||||
state: "running",
|
||||
status: "Up 15 minutes",
|
||||
ports: "127.0.0.1:5432->5432/tcp",
|
||||
createdAt: "2026-04-20T05:00:00Z",
|
||||
composeProject: "shop",
|
||||
composeService: "db",
|
||||
composeWorkingDir: "/work/shop",
|
||||
composeFiles: ["/work/shop/docker-compose.yml"],
|
||||
mounts: ["shop_pgdata"],
|
||||
networks: ["shop_default"],
|
||||
},
|
||||
{
|
||||
id: "api-1",
|
||||
name: "shop-api-1",
|
||||
image: "node:22",
|
||||
command: "node server.js",
|
||||
state: "exited",
|
||||
status: "Exited (0) 2 minutes ago",
|
||||
ports: "",
|
||||
createdAt: "2026-04-20T05:00:00Z",
|
||||
composeProject: "shop",
|
||||
composeService: "api",
|
||||
composeWorkingDir: "/work/shop",
|
||||
composeFiles: ["/work/shop/docker-compose.yml"],
|
||||
mounts: [],
|
||||
networks: ["shop_default"],
|
||||
},
|
||||
],
|
||||
images: [],
|
||||
volumes: [
|
||||
{
|
||||
name: anonName,
|
||||
driver: "local",
|
||||
mountpoint: `/var/lib/docker/volumes/${anonName}/_data`,
|
||||
composeProject: "shop",
|
||||
scope: "local",
|
||||
labels: { "com.docker.volume.anonymous": "" },
|
||||
},
|
||||
{
|
||||
name: "shop_pgdata",
|
||||
driver: "local",
|
||||
mountpoint: "/var/lib/docker/volumes/shop_pgdata/_data",
|
||||
composeProject: "shop",
|
||||
scope: "local",
|
||||
labels: {
|
||||
"com.docker.compose.project": "shop",
|
||||
"com.docker.compose.volume": "pgdata",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "other_cache",
|
||||
driver: "local",
|
||||
mountpoint: "/var/lib/docker/volumes/other_cache/_data",
|
||||
composeProject: "other",
|
||||
scope: "local",
|
||||
labels: {
|
||||
"com.docker.compose.project": "other",
|
||||
"com.docker.compose.volume": "cache",
|
||||
},
|
||||
},
|
||||
],
|
||||
networks: [{ id: "net-1", name: "shop_default", driver: "bridge", scope: "local", composeProject: "shop" }],
|
||||
errors: [],
|
||||
};
|
||||
|
||||
window.__ipc.handlers.docker_settings = () => ({
|
||||
connections: [{ id: "default", name: "Docker", endpoint: { kind: "default" } }],
|
||||
registries: [],
|
||||
});
|
||||
window.__ipc.handlers.docker_snapshot = () => snapshot;
|
||||
window.__ipc.handlers.docker_events = () => new Promise(() => {});
|
||||
window.__ipc.handlers.docker_inspect = () => "[]";
|
||||
window.__ipc.handlers.docker_container_stats = ({ id }) => {
|
||||
if (id !== "db-1") throw { kind: "notFound", message: "container not running", detail: null };
|
||||
return {
|
||||
cpuPerc: (window as unknown as { __cpuPerc: string }).__cpuPerc,
|
||||
memUsage: "128MiB / 2GiB",
|
||||
memPerc: "6.25%",
|
||||
netIo: "2.4MB / 980kB",
|
||||
blockIo: "12MB / 4.1MB",
|
||||
pids: "17",
|
||||
};
|
||||
};
|
||||
|
||||
const storeMod = "/src/features/services/store.ts";
|
||||
const treeMod = "/src/features/services/tree.ts";
|
||||
const { useServices } = await import(/* @vite-ignore */ storeMod);
|
||||
const { useServicesTree } = await import(/* @vite-ignore */ treeMod);
|
||||
useServices.setState({
|
||||
settings: { connections: [{ id: "default", name: "Docker", endpoint: { kind: "default" } }], registries: [] },
|
||||
conns: { default: { snapshot, loading: false, error: null } },
|
||||
});
|
||||
useServicesTree.setState({
|
||||
expanded: new Set(["docker:default"]),
|
||||
selectedKey: "docker:default:compose:shop",
|
||||
selectedKeys: new Set(["docker:default:compose:shop"]),
|
||||
});
|
||||
});
|
||||
|
||||
await page.keyboard.press("Meta+8");
|
||||
const services = page.getByRole("region", { name: "Services", exact: true });
|
||||
const detail = services.locator("[data-panel][id=services-detail]");
|
||||
await expect(detail.getByText("Compose project 'shop'")).toBeVisible();
|
||||
|
||||
const dbRow = detail.locator("tr", { hasText: "shop-db-1" });
|
||||
const apiRow = detail.locator("tr", { hasText: "shop-api-1" });
|
||||
await expect(dbRow).toContainText("6.25%");
|
||||
await expect(dbRow).toContainText("128MiB / 2GiB (6.25%)");
|
||||
await expect(dbRow).toContainText("2.4MB / 980kB");
|
||||
await expect(dbRow).toContainText("12MB / 4.1MB");
|
||||
await expect(dbRow).toContainText("17");
|
||||
await expect(apiRow).toContainText("Exited (0) 2 minutes ago");
|
||||
|
||||
// Stopped service container is never queried for live stats, and no manual Refresh button is shown.
|
||||
const queriedIds = (await ipcCalls(page, "docker_container_stats")).map((c) => c.id);
|
||||
expect(new Set(queriedIds)).toEqual(new Set(["db-1"]));
|
||||
await expect(detail.getByRole("button", { name: "Refresh", exact: true })).toHaveCount(0);
|
||||
|
||||
// Running service metrics auto-refresh in place without user action.
|
||||
await page.evaluate(() => {
|
||||
(window as unknown as { __cpuPerc: string }).__cpuPerc = "18.50%";
|
||||
});
|
||||
await expect(dbRow).toContainText("18.50%", { timeout: 5000 });
|
||||
|
||||
// Named Compose volume appears with logical name + driver; anonymous and other-project volumes do not.
|
||||
const volumeButton = detail.getByRole("button", { name: /shop_pgdata/ });
|
||||
await expect(volumeButton).toContainText("pgdata · local");
|
||||
await expect(detail.getByText("other_cache")).toHaveCount(0);
|
||||
await expect(detail.getByText(/37cc33a7/)).toHaveCount(0);
|
||||
|
||||
// Clicking the named volume opens its Volume dashboard and links back to the Compose project.
|
||||
await volumeButton.click();
|
||||
await expect(detail.getByText("Volume Overview")).toBeVisible();
|
||||
await detail.getByRole("button", { name: "shop", exact: true }).click();
|
||||
await expect(detail.getByText("Compose project 'shop'")).toBeVisible();
|
||||
|
||||
// Clicking a service in the table navigates to its Container dashboard, which auto-refreshes live stats.
|
||||
await detail.getByRole("button", { name: "shop-db-1", exact: true }).click();
|
||||
await expect(detail.getByText("Container Overview")).toBeVisible();
|
||||
await expect(detail).toContainText("18.50%");
|
||||
await page.evaluate(() => {
|
||||
(window as unknown as { __cpuPerc: string }).__cpuPerc = "27.40%";
|
||||
});
|
||||
await expect(detail).toContainText("27.40%", { timeout: 5000 });
|
||||
});
|
||||
@@ -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 });
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { expect, test } from "./fixtures";
|
||||
|
||||
test("Settings aligns search results with their parent pages and honors smaller tree indents", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.keyboard.press("Meta+,");
|
||||
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
|
||||
const search = dialog.getByRole("textbox", { name: "Search settings" });
|
||||
const tree = dialog.getByRole("tree", { name: "Settings pages" });
|
||||
await search.fill("Language Defaults");
|
||||
|
||||
const editor = tree.getByRole("treeitem", { name: "Editor", exact: true });
|
||||
const scheme = tree.getByRole("treeitem", { name: "Color Scheme", exact: true });
|
||||
const defaults = tree.getByRole("treeitem", { name: "Language Defaults", exact: true });
|
||||
await expect(defaults).toHaveAttribute("aria-selected", "true");
|
||||
await expect(defaults.locator("mark")).toHaveText(["Language", "Defaults"]);
|
||||
|
||||
const insets = () =>
|
||||
Promise.all(
|
||||
[editor, scheme, defaults].map((row) =>
|
||||
row.locator(":scope > span:last-child").evaluate((label) => {
|
||||
const left = label.closest('[role="tree"]')!.getBoundingClientRect().left;
|
||||
return Math.round(label.getBoundingClientRect().left - left);
|
||||
}),
|
||||
),
|
||||
);
|
||||
await expect.poll(insets).toEqual([28, 44, 60]);
|
||||
await page.setViewportSize({ width: 580, height: 720 });
|
||||
await expect.poll(insets).toEqual([28, 44, 60]);
|
||||
await page.evaluate(() => document.documentElement.style.setProperty("--tree-indent", "12px"));
|
||||
await expect.poll(insets).toEqual([28, 40, 52]);
|
||||
|
||||
await search.press("ArrowUp");
|
||||
await expect(scheme).toHaveAttribute("aria-selected", "true");
|
||||
await search.press("ArrowUp");
|
||||
await expect(editor).toHaveAttribute("aria-selected", "true");
|
||||
await expect(search).toBeFocused();
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
import { expect, test } from "./fixtures";
|
||||
|
||||
test("shortcut assignment fits the first stroke and conflict names in a narrow window", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 336, height: 540 });
|
||||
await page.keyboard.press("Meta+,");
|
||||
const settings = page.getByRole("dialog", { name: "Settings", exact: true });
|
||||
await settings.getByRole("treeitem", { name: "Keymap", exact: true }).click();
|
||||
await settings.getByRole("textbox", { name: "Search actions" }).fill("Find Action");
|
||||
const action = settings.getByRole("treeitem", { name: /Find Action/ });
|
||||
await action.click();
|
||||
await settings.getByRole("button", { name: "Add Keyboard Shortcut", exact: true }).click();
|
||||
|
||||
const dialog = page.getByRole("dialog", { name: "Keyboard Shortcut: Find Action…", exact: true });
|
||||
const first = dialog.getByRole("textbox", { name: "First stroke" });
|
||||
const body = dialog.locator("[data-dialog-body]");
|
||||
const titleBar = dialog.locator("[data-dialog-titlebar]");
|
||||
await expect(first).toBeFocused();
|
||||
await expect(titleBar).toHaveText("Keyboard Shortcut");
|
||||
await expect(body.getByText("Find Action…", { exact: true })).toBeVisible();
|
||||
const firstBounds = (await first.boundingBox())!;
|
||||
const bodyBounds = (await body.boundingBox())!;
|
||||
expect(firstBounds.width).toBeGreaterThan(bodyBounds.width - 32);
|
||||
const conflicts = dialog.getByRole("list", { name: "Conflicts:" });
|
||||
await expect(conflicts).toHaveCount(0);
|
||||
|
||||
await first.press("Meta+Alt+L");
|
||||
await expect(conflicts).toBeVisible();
|
||||
await expect(conflicts.getByRole("listitem").filter({ hasText: "Reformat Code" }).first()).toBeVisible();
|
||||
expect(await conflicts.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
|
||||
expect(
|
||||
await conflicts
|
||||
.getByRole("listitem")
|
||||
.evaluateAll((rows) => rows.every((row) => row.scrollHeight <= row.clientHeight)),
|
||||
).toBe(true);
|
||||
expect(await body.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
|
||||
|
||||
const ok = dialog.getByRole("button", { name: "OK", exact: true });
|
||||
await ok.click();
|
||||
const confirmation = page.getByRole("dialog", { name: "Warning", exact: true });
|
||||
await expect(confirmation.getByRole("list").getByText("Reformat Code", { exact: true })).toHaveCount(2);
|
||||
await confirmation.getByRole("button", { name: "Leave", exact: true }).click();
|
||||
await expect(dialog).toBeHidden();
|
||||
await expect(action.locator("kbd").filter({ hasText: "⌥⌘L" })).toHaveCount(1);
|
||||
});
|
||||
@@ -102,6 +102,9 @@ test("edits the staged version and keeps an unsaved draft when the index changes
|
||||
await expect(headPane).toContainText("val committed = 0");
|
||||
await expect(indexPane).toContainText("val external = 3");
|
||||
await expect(localPane).not.toBeEmpty();
|
||||
const indexHeading = page.getByTitle(`Staged (index) ${path}`, { exact: true });
|
||||
await expect(indexHeading.getByText("build.gradle.kts", { exact: true })).toBeVisible();
|
||||
await expect(indexHeading.getByText("Staged (index)", { exact: true })).toBeVisible();
|
||||
const working = await localPane.textContent();
|
||||
|
||||
await page.getByRole("button", { name: "Unstage Change", exact: true }).click();
|
||||
|
||||
@@ -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,81 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
|
||||
|
||||
async function openDialog(page: Page, id: "find.structural" | "find.replaceStructural") {
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async (id) => {
|
||||
window.__ipc.handlers.structural_languages = () => [
|
||||
{ id: "java", name: "Java" },
|
||||
{ id: "typescript", name: "TypeScript" },
|
||||
];
|
||||
window.__ipc.handlers.structural_validate = () => null;
|
||||
const actionsModule = "/src/platform/actions.ts";
|
||||
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
|
||||
await executeAction(id);
|
||||
}, id);
|
||||
}
|
||||
|
||||
test("Structural Search puts language selection beside the taller template editor", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 1080, height: 720 });
|
||||
await openDialog(page, "find.structural");
|
||||
const dialog = page.getByRole("dialog", { name: "Structural Search" });
|
||||
const editor = dialog.getByRole("textbox", { name: "Search template" });
|
||||
const label = dialog.locator("label").filter({ hasText: /^Search template$/ });
|
||||
const language = dialog.getByRole("button", { name: "Language", exact: true });
|
||||
await expect(editor).toBeFocused();
|
||||
await expect(language).toHaveText("Java");
|
||||
|
||||
const { x, y, width, height } = (await editor.boundingBox())!;
|
||||
const caption = (await label.boundingBox())!;
|
||||
const picker = (await language.boundingBox())!;
|
||||
expect(Math.abs(caption.y + caption.height / 2 - (picker.y + picker.height / 2))).toBeLessThanOrEqual(1);
|
||||
expect(Math.abs(caption.x - x)).toBeLessThanOrEqual(1);
|
||||
expect(Math.abs(picker.x + picker.width - (x + width))).toBeLessThanOrEqual(1);
|
||||
expect(y - (picker.y + picker.height)).toBeLessThanOrEqual(6);
|
||||
expect(Math.abs(height - 150)).toBeLessThanOrEqual(1);
|
||||
|
||||
await language.click();
|
||||
await page.getByRole("option", { name: "TypeScript" }).click();
|
||||
await editor.fill("console.log($value$)");
|
||||
await expect
|
||||
.poll(() => ipcCalls(page, "structural_validate"))
|
||||
.toContainEqual({
|
||||
query: { language: "typescript", pattern: "console.log($value$)", replacement: null, maxMatches: 0 },
|
||||
});
|
||||
await expect(dialog.getByRole("button", { name: "Find", exact: true })).toBeEnabled();
|
||||
});
|
||||
|
||||
test("Structural Replace uses editor typography and fits the template controls in a narrow window", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 400, height: 620 });
|
||||
await openDialog(page, "find.replaceStructural");
|
||||
const dialog = page.getByRole("dialog", { name: "Structural Replace" });
|
||||
const search = dialog.getByRole("textbox", { name: "Search template" });
|
||||
const replacement = dialog.getByRole("textbox", { name: "Replace template" });
|
||||
await expect(search).toBeFocused();
|
||||
await page.evaluate(async () => {
|
||||
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, fontFamily: "Consolas", fontSize: 17, lineHeight: 26 } },
|
||||
});
|
||||
});
|
||||
|
||||
for (const template of [search, replacement]) {
|
||||
await expect(template).toHaveCSS("font-family", /^Consolas,/);
|
||||
await expect(template).toHaveCSS("font-size", "17px");
|
||||
await expect(template).toHaveCSS("line-height", "26px");
|
||||
const box = (await template.boundingBox())!;
|
||||
expect(box.x).toBeGreaterThanOrEqual(0);
|
||||
expect(box.x + box.width).toBeLessThanOrEqual(400);
|
||||
expect(Math.abs(box.height - 105)).toBeLessThanOrEqual(1);
|
||||
}
|
||||
await expect(dialog.getByRole("radio", { name: "Whole project" })).toBeInViewport();
|
||||
await replacement.fill("Objects.equals($a$, $b$)");
|
||||
await expect(replacement).toHaveValue("Objects.equals($a$, $b$)");
|
||||
await expect(dialog.getByRole("button", { name: "Cancel" })).toBeInViewport();
|
||||
});
|
||||
+22
-4
@@ -71,7 +71,15 @@ for (const { width, split } of [{ width: 220 }, { width: 280 }, { width: 520 },
|
||||
const search = terminal.getByRole("search", { name: "Find in terminal" });
|
||||
const input = search.getByRole("textbox", { name: "Find in terminal" });
|
||||
await input.fill("alpha");
|
||||
await expect(search.locator("[aria-live=polite]")).toHaveText(/\d+\/3/);
|
||||
const count = search.locator("[aria-live=polite]");
|
||||
await expect(count).toHaveText(/\d+\/3/);
|
||||
await expect(count).toHaveCSS("font-size", "13px");
|
||||
const match = await count.textContent();
|
||||
// The incremental search can report after the first Enter; retry until Enter moves on.
|
||||
await expect(async () => {
|
||||
await input.press("Enter");
|
||||
await expect(count).not.toHaveText(match!, { timeout: 1000 });
|
||||
}).toPass();
|
||||
if (process.env.OPENIDEA_TERMINAL_SHOTS)
|
||||
await terminal.screenshot({
|
||||
path: `${process.env.OPENIDEA_TERMINAL_SHOTS}/terminal-${width}${split ? "-split" : ""}.png`,
|
||||
@@ -83,9 +91,19 @@ for (const { width, split } of [{ width: 220 }, { width: 280 }, { width: 520 },
|
||||
expect(rect.x).toBeGreaterThanOrEqual(bounds.x);
|
||||
expect(rect.x + rect.width).toBeLessThanOrEqual(bounds.x + bounds.width + 1);
|
||||
}
|
||||
expect((await input.boundingBox())!.width).toBeGreaterThan(40);
|
||||
|
||||
const matchCase = search.getByRole("button", { name: "Match Case", exact: true });
|
||||
const inputBox = (await input.boundingBox())!;
|
||||
if (width <= 280 || split) {
|
||||
expect(inputBox.width).toBeGreaterThan(bounds.width * 0.62);
|
||||
expect((await matchCase.boundingBox())!.y).toBeGreaterThan(inputBox.y + inputBox.height);
|
||||
} else {
|
||||
expect(inputBox.width).toBeGreaterThan(80);
|
||||
}
|
||||
const countBox = (await count.boundingBox())!;
|
||||
const previousBox = (await search.getByRole("button", { name: "Previous Occurrence", exact: true }).boundingBox())!;
|
||||
expect(previousBox.x - countBox.x - countBox.width).toBeLessThanOrEqual(4);
|
||||
expect(countBox.y + countBox.height / 2).toBeCloseTo(previousBox.y + previousBox.height / 2, 0);
|
||||
|
||||
await matchCase.focus();
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(matchCase).toHaveAttribute("aria-pressed", "true");
|
||||
@@ -130,7 +148,7 @@ test("wide terminal search leaves the grid in place and avoids covering the acti
|
||||
const top = (await search.boundingBox())!;
|
||||
expect(top.y).toBeCloseTo(before.y, 0);
|
||||
expect(top.x + top.width).toBeCloseTo(before.x + before.width, 0);
|
||||
expect(top.width).toBeLessThan(before.width);
|
||||
expect(top.width).toBeLessThan(420);
|
||||
|
||||
await input.fill("right-edge");
|
||||
await expect(search.locator("[aria-live=polite]")).toHaveText("1/1");
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
+1
-1
@@ -67,7 +67,7 @@
|
||||
"@floating-ui/react-dom": "^2.1.9",
|
||||
"@fontsource-variable/inter": "^5.3.0",
|
||||
"@fontsource-variable/jetbrains-mono": "^5.3.0",
|
||||
"@lezer/common": "^1.5.3",
|
||||
"@lezer/common": "^1.5.6",
|
||||
"@lezer/highlight": "^1.2.5",
|
||||
"@lezer/lr": "^1.4.11",
|
||||
"@mathjax/mathjax-tex-font": "4.1.3",
|
||||
|
||||
Generated
+44
-44
@@ -76,8 +76,8 @@ importers:
|
||||
specifier: ^5.3.0
|
||||
version: 5.3.0
|
||||
'@lezer/common':
|
||||
specifier: ^1.5.3
|
||||
version: 1.5.3
|
||||
specifier: ^1.5.6
|
||||
version: 1.5.6
|
||||
'@lezer/highlight':
|
||||
specifier: ^1.2.5
|
||||
version: 1.2.5
|
||||
@@ -473,8 +473,8 @@ packages:
|
||||
'@jridgewell/[email protected]':
|
||||
resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==}
|
||||
|
||||
'@lezer/[email protected].3':
|
||||
resolution: {integrity: sha512-H0iErY4e43LpXbYDyBci5W4v/RwTgGV3YzYOlJPiGZ8RY8w51kVE+xLn1tg3Z6UmSfyETvtsUK3r7YsgDQEI7Q==}
|
||||
'@lezer/[email protected].6':
|
||||
resolution: {integrity: sha512-NZxu3q49ck+YYbEJPuIPIyFP37XneBvzPIarBHEXBLBVfkZqQieZ/Y2boYnGNYtmjpOZLnAKs/lwqtmDpi365w==}
|
||||
|
||||
'@lezer/[email protected]':
|
||||
resolution: {integrity: sha512-vh9gWWJOXFVY8HBHK3Twzq8MgwG2iN4GSyzBP9sCGTe37P15x2R14VaBQk0VA0ezTRN1KHYBBsHhvpGZ2Xy/pA==}
|
||||
@@ -2481,21 +2481,21 @@ snapshots:
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
|
||||
'@codemirror/[email protected]':
|
||||
dependencies:
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
|
||||
'@codemirror/[email protected]':
|
||||
dependencies:
|
||||
'@codemirror/lang-html': 6.4.12
|
||||
'@codemirror/lang-javascript': 6.2.5
|
||||
'@codemirror/language': 6.13.1
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
@@ -2509,7 +2509,7 @@ snapshots:
|
||||
'@codemirror/autocomplete': 6.20.3
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/state': 6.7.6
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/css': 1.3.9
|
||||
|
||||
'@codemirror/[email protected]':
|
||||
@@ -2517,7 +2517,7 @@ snapshots:
|
||||
'@codemirror/autocomplete': 6.20.3
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/state': 6.7.6
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/go': 1.0.1
|
||||
|
||||
'@codemirror/[email protected]':
|
||||
@@ -2528,7 +2528,7 @@ snapshots:
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/css': 1.3.9
|
||||
'@lezer/html': 1.3.13
|
||||
|
||||
@@ -2544,7 +2544,7 @@ snapshots:
|
||||
'@codemirror/lint': 6.9.7
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/javascript': 1.5.6
|
||||
|
||||
'@codemirror/[email protected]':
|
||||
@@ -2554,7 +2554,7 @@ snapshots:
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
@@ -2567,7 +2567,7 @@ snapshots:
|
||||
dependencies:
|
||||
'@codemirror/lang-css': 6.3.1
|
||||
'@codemirror/language': 6.13.1
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
@@ -2578,7 +2578,7 @@ snapshots:
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
@@ -2589,7 +2589,7 @@ snapshots:
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/markdown': 1.8.0
|
||||
|
||||
'@codemirror/[email protected]':
|
||||
@@ -2597,7 +2597,7 @@ snapshots:
|
||||
'@codemirror/lang-html': 6.4.12
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/state': 6.7.6
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/php': 1.0.6
|
||||
|
||||
'@codemirror/[email protected]':
|
||||
@@ -2605,7 +2605,7 @@ snapshots:
|
||||
'@codemirror/autocomplete': 6.20.3
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/state': 6.7.6
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/python': 1.1.19
|
||||
|
||||
'@codemirror/[email protected]':
|
||||
@@ -2618,7 +2618,7 @@ snapshots:
|
||||
'@codemirror/lang-css': 6.3.1
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/state': 6.7.6
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/sass': 1.1.0
|
||||
|
||||
'@codemirror/[email protected]':
|
||||
@@ -2626,7 +2626,7 @@ snapshots:
|
||||
'@codemirror/autocomplete': 6.20.3
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/state': 6.7.6
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
@@ -2635,14 +2635,14 @@ snapshots:
|
||||
'@codemirror/lang-html': 6.4.12
|
||||
'@codemirror/lang-javascript': 6.2.5
|
||||
'@codemirror/language': 6.13.1
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
'@codemirror/[email protected]':
|
||||
dependencies:
|
||||
'@codemirror/language': 6.13.1
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
@@ -2652,7 +2652,7 @@ snapshots:
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/xml': 1.0.6
|
||||
|
||||
'@codemirror/[email protected]':
|
||||
@@ -2660,7 +2660,7 @@ snapshots:
|
||||
'@codemirror/autocomplete': 6.20.3
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/state': 6.7.6
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
'@lezer/yaml': 1.0.4
|
||||
@@ -2696,7 +2696,7 @@ snapshots:
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/streamparser': 6.0.0
|
||||
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
style-mod: 4.1.4
|
||||
@@ -2832,101 +2832,101 @@ snapshots:
|
||||
'@jridgewell/resolve-uri': 3.1.2
|
||||
'@jridgewell/sourcemap-codec': 1.6.0
|
||||
|
||||
'@lezer/[email protected].3': {}
|
||||
'@lezer/[email protected].6': {}
|
||||
|
||||
'@lezer/[email protected]':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
'@lezer/[email protected]':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
'@lezer/[email protected]':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
'@lezer/[email protected]':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
'@lezer/[email protected]':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
|
||||
'@lezer/[email protected]':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
'@lezer/[email protected]':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
'@lezer/[email protected]':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
'@lezer/[email protected]':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
'@lezer/[email protected](patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
|
||||
'@lezer/[email protected]':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/highlight': 1.2.5
|
||||
|
||||
'@lezer/[email protected]':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
'@lezer/[email protected]':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
'@lezer/[email protected]':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
'@lezer/[email protected]':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
'@lezer/[email protected]':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
'@lezer/[email protected]':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
@@ -3200,12 +3200,12 @@ snapshots:
|
||||
dependencies:
|
||||
'@codemirror/autocomplete': 6.20.3
|
||||
'@codemirror/language': 6.13.1
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@plutojl/lezer-julia': 1.2.0
|
||||
|
||||
'@plutojl/[email protected]':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/common': 1.5.6
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
|
||||
import { ensureSyntaxTree, syntaxTree } from "@codemirror/language";
|
||||
import { javascript } from "@codemirror/lang-javascript";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { TreeFragment } from "@lezer/common";
|
||||
|
||||
/** Functions with long doc comments: re-parsing reuses a whole comment as one node. */
|
||||
const source = Array.from(
|
||||
@@ -25,3 +26,63 @@ describe("incremental parsing (#4468)", () => {
|
||||
expect(tree.topNode.firstChild?.from).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
/** `count` documented classes: as many top-level statements, each after a doc comment longer than the parser's look-ahead margin. */
|
||||
function documentedClasses(count: number): string {
|
||||
return Array.from(
|
||||
{ length: count },
|
||||
(_, i) =>
|
||||
`/** Repository for entity ${i}, with a comment long enough to look ahead of. */\n` +
|
||||
`export class Repository${i}<T extends { id: number }> {\n` +
|
||||
` find(id: number): T | undefined {\n return this.items.get(id)\n }\n}\n\n`,
|
||||
).join("");
|
||||
}
|
||||
|
||||
const parser = javascript({ typescript: true }).language.parser;
|
||||
|
||||
/** Inserts `insert` at `at`, re-parsing incrementally from `tree`; returns the new tree and how many parser steps that took. */
|
||||
function reparse(doc: string, tree: ReturnType<typeof parser.parse>, at: number, insert: string) {
|
||||
const fragments = TreeFragment.applyChanges(TreeFragment.addTree(tree), [
|
||||
{ fromA: at, toA: at, fromB: at, toB: at + insert.length },
|
||||
]);
|
||||
const edited = doc.slice(0, at) + insert + doc.slice(at);
|
||||
const parse = parser.startParse(edited, fragments);
|
||||
let steps = 0;
|
||||
let result = null;
|
||||
while (!(result = parse.advance())) steps++;
|
||||
return { doc: edited, tree: result, steps };
|
||||
}
|
||||
|
||||
describe("incremental parsing of long statement lists", () => {
|
||||
// A repeat group's look-ahead was that of the whole list, ending at the last doc comment: no group before an
|
||||
// edit could be reused, so typing cost grew with the position in the file, one statement at a time.
|
||||
it("takes as many parser steps in a long file as in a short one", () => {
|
||||
const steps = (count: number) => {
|
||||
const doc = documentedClasses(count);
|
||||
const at = doc.indexOf("return", doc.length >> 1);
|
||||
return reparse(doc, parser.parse(doc), at, "a").steps;
|
||||
};
|
||||
const short = steps(100);
|
||||
const long = steps(1600);
|
||||
expect(long).toBeLessThan(short * 2);
|
||||
});
|
||||
|
||||
it("matches a fresh parse wherever the edit is", () => {
|
||||
const doc = documentedClasses(300);
|
||||
const tree = parser.parse(doc);
|
||||
const edits: Array<[string, string]> = [
|
||||
["/**", "a"],
|
||||
["return", "a"],
|
||||
["export class Repository150", "// "],
|
||||
["}\n\n/** Repository for entity 299", "}"],
|
||||
["find(id", "static "],
|
||||
];
|
||||
for (const [anchor, insert] of edits) {
|
||||
const at = doc.indexOf(anchor) + (anchor.startsWith("}") ? 0 : 0);
|
||||
const result = reparse(doc, tree, at, insert);
|
||||
expect(result.tree.toString(), `after inserting ${JSON.stringify(insert)} before ${JSON.stringify(anchor)}`).toBe(
|
||||
parser.parse(result.doc).toString(),
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* Paints an inline mark's background capped at `1lh` so a font taller than the line height
|
||||
* does not bleed into the rows above and below. When the inline box is shorter than `1lh`,
|
||||
* its own border box clips the gradient. Safari before 16.4 has no `lh` and drops the
|
||||
* shorthand, keeping the plain colour before it.
|
||||
*/
|
||||
export function inlineBackground(color: string) {
|
||||
return {
|
||||
backgroundColor: color,
|
||||
background: `linear-gradient(${color}, ${color}) center / 100% 1lh no-repeat`,
|
||||
WebkitBoxDecorationBreak: "clone",
|
||||
boxDecorationBreak: "clone",
|
||||
};
|
||||
}
|
||||
|
||||
/** Fallback style for an inline mark with a 1px frame (`inlineFramedModern` caps it at `1lh`). */
|
||||
export function inlineFramedFallback(fill: string, frame: string) {
|
||||
return {
|
||||
backgroundColor: fill,
|
||||
outline: `1px solid ${frame}`,
|
||||
outlineOffset: "-1px",
|
||||
WebkitBoxDecorationBreak: "clone",
|
||||
boxDecorationBreak: "clone",
|
||||
};
|
||||
}
|
||||
|
||||
/** `@supports (height: 1lh)` override for `inlineFramedFallback`: caps both fill and 1px frame at `1lh`. */
|
||||
export function inlineFramedModern(fill: string, frame: string) {
|
||||
return {
|
||||
outline: "none",
|
||||
background: [
|
||||
`linear-gradient(to bottom, ${frame} 0 1px, transparent 1px calc(100% - 1px), ${frame} calc(100% - 1px) 100%) center / 100% min(100%, 1lh) no-repeat`,
|
||||
`linear-gradient(to right, ${frame} 0 1px, transparent 1px calc(100% - 1px), ${frame} calc(100% - 1px) 100%) center / 100% min(100%, 1lh) no-repeat`,
|
||||
`linear-gradient(${fill}, ${fill}) center / calc(100% - 2px) calc(min(100%, 1lh) - 2px) no-repeat`,
|
||||
].join(", "),
|
||||
};
|
||||
}
|
||||
@@ -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. */
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { StreamLanguage } from "@codemirror/language";
|
||||
import { javascript } from "@codemirror/lang-javascript";
|
||||
import { kotlin } from "@codemirror/legacy-modes/mode/clike";
|
||||
import { highlightTree } from "@lezer/highlight";
|
||||
import { lineLiteralAt, literalAt, literalsExtension } from "./literals";
|
||||
import { setSyntaxHighlights } from "./syntaxHighlight";
|
||||
|
||||
vi.mock("@lezer/highlight", async (importOriginal) => {
|
||||
const original = await importOriginal<typeof import("@lezer/highlight")>();
|
||||
return { ...original, highlightTree: vi.fn(original.highlightTree) };
|
||||
});
|
||||
|
||||
const highlighted = vi.mocked(highlightTree);
|
||||
beforeEach(() => {
|
||||
highlighted.mockClear();
|
||||
});
|
||||
|
||||
/** The `[from, to]` window of every `highlightTree` call since the last `beforeEach`. */
|
||||
const windows = () => highlighted.mock.calls.map(([tree, , , from = 0, to = tree.length]) => [from, to]);
|
||||
|
||||
const code = (lines: number) =>
|
||||
Array.from({ length: lines }, (_, i) => `const v${i} = "value ${i}"; // note ${i}\nlet n${i} = ${i};`).join("\n") +
|
||||
"\nconst text = `first\nsecond`;\n";
|
||||
|
||||
const typescript = () => [javascript({ typescript: true })];
|
||||
|
||||
describe("lineLiteralAt", () => {
|
||||
it("finds the string literal or comment at a position, as literalAt does", () => {
|
||||
const state = EditorState.create({ doc: code(20), extensions: typescript() });
|
||||
const at = (needle: string, shift = 0) => state.doc.toString().indexOf(needle) + shift;
|
||||
for (const [pos, kind] of [
|
||||
[at('"value 7"', 3), "string"],
|
||||
[at("// note 7", 4), "comment"],
|
||||
[at("const v7", 2), null],
|
||||
[at("n7 = 7", 4), null],
|
||||
] as const) {
|
||||
expect(lineLiteralAt(state, pos)?.kind ?? null).toBe(kind);
|
||||
expect(lineLiteralAt(state, pos)).toEqual(literalAt(state, pos));
|
||||
}
|
||||
});
|
||||
|
||||
it("returns a literal that goes on past the line cut at the line break", () => {
|
||||
const state = EditorState.create({ doc: code(3), extensions: typescript() });
|
||||
const doc = state.doc.toString();
|
||||
const open = doc.indexOf("`first");
|
||||
const lit = lineLiteralAt(state, open + 2)!;
|
||||
expect(lit.kind).toBe("string");
|
||||
expect(lit.from).toBe(open);
|
||||
expect(state.doc.lineAt(lit.to).number).not.toBe(state.doc.lineAt(lit.from).number);
|
||||
const second = doc.indexOf("second");
|
||||
const rest = lineLiteralAt(state, second + 2)!;
|
||||
expect(state.doc.lineAt(rest.from).number).not.toBe(state.doc.lineAt(rest.to).number);
|
||||
});
|
||||
|
||||
it("highlights the line and its line breaks, not the document", () => {
|
||||
// `literalAt` asks for the whole document: a rebuilt scan of every line for each Enter typed.
|
||||
const sizes = [200, 4000].map((lines) => {
|
||||
const state = EditorState.create({ doc: code(lines), extensions: typescript() });
|
||||
const pos = state.doc.toString().indexOf('"value 150"') + 3;
|
||||
const line = state.doc.lineAt(pos);
|
||||
highlighted.mockClear();
|
||||
expect(lineLiteralAt(state, pos)?.kind).toBe("string");
|
||||
const covered = windows().map(([from, to]) => to! - from!);
|
||||
expect(Math.max(...covered)).toBeLessThanOrEqual(line.length + 2);
|
||||
return covered.length;
|
||||
});
|
||||
expect(sizes[1]).toBe(sizes[0]);
|
||||
});
|
||||
|
||||
it("finds literals of languages with a stream parser", () => {
|
||||
const doc = 'val a = 1\nval s = "hi there" // done\n';
|
||||
const state = EditorState.create({ doc, extensions: [StreamLanguage.define(kotlin)] });
|
||||
expect(lineLiteralAt(state, doc.indexOf("hi") + 1)).toEqual({
|
||||
from: doc.indexOf('"hi'),
|
||||
to: doc.indexOf(" //"),
|
||||
kind: "string",
|
||||
});
|
||||
expect(lineLiteralAt(state, doc.indexOf("done"))?.kind).toBe("comment");
|
||||
expect(lineLiteralAt(state, doc.indexOf("val a"))).toBeNull();
|
||||
});
|
||||
|
||||
it("falls back to the highlights of the backend for languages without a parser", () => {
|
||||
const doc = "plain\nx = 'quoted'\n";
|
||||
const state = EditorState.create({ doc, extensions: [literalsExtension] }).update({
|
||||
effects: setSyntaxHighlights.of({ kinds: ["string"], data: [doc.indexOf("'q"), doc.indexOf("'\n") + 1, 0] }),
|
||||
}).state;
|
||||
expect(lineLiteralAt(state, doc.indexOf("quoted"))).toEqual({
|
||||
from: doc.indexOf("'q"),
|
||||
to: doc.indexOf("'\n") + 1,
|
||||
kind: "string",
|
||||
});
|
||||
expect(lineLiteralAt(state, 2)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -6,6 +6,7 @@
|
||||
*/
|
||||
import { StateField, type EditorState } from "@codemirror/state";
|
||||
import { ensureSyntaxTree, syntaxTree } from "@codemirror/language";
|
||||
import type { Tree } from "@lezer/common";
|
||||
import { highlightTree, tagHighlighter, tags as t } from "@lezer/highlight";
|
||||
import type { SyntaxHighlightKind } from "@/platform/ipc";
|
||||
import type { LiteralKind } from "@/platform/search";
|
||||
@@ -64,17 +65,29 @@ const cache = new WeakMap<object, readonly LiteralRange[]>();
|
||||
/** How long counting may wait for the parser to reach the end of the document. */
|
||||
const PARSE_BUDGET_MS = 50;
|
||||
|
||||
/** Comments and string literals of `tree` between `from` and `to`; a literal reaching past either end is cut there. */
|
||||
function highlightedLiterals(tree: Tree, from: number, to: number): LiteralRange[] {
|
||||
const out: LiteralRange[] = [];
|
||||
highlightTree(
|
||||
tree,
|
||||
highlighter,
|
||||
(start, end, cls) => {
|
||||
const kind: LiteralKind | null = cls.includes("comment") ? "comment" : cls.includes("string") ? "string" : null;
|
||||
if (kind) push(out, start, end, kind);
|
||||
},
|
||||
from,
|
||||
to,
|
||||
);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Comments and string literals of `state` (cached per syntax tree). */
|
||||
export function literalRanges(state: EditorState): readonly LiteralRange[] {
|
||||
const tree = ensureSyntaxTree(state, state.doc.length, PARSE_BUDGET_MS) ?? syntaxTree(state);
|
||||
if (tree.length === 0) return state.field(treeSitterLiterals, false) ?? [];
|
||||
const hit = cache.get(tree);
|
||||
if (hit) return hit;
|
||||
const out: LiteralRange[] = [];
|
||||
highlightTree(tree, highlighter, (from, to, cls) => {
|
||||
const kind: LiteralKind | null = cls.includes("comment") ? "comment" : cls.includes("string") ? "string" : null;
|
||||
if (kind) push(out, from, to, kind);
|
||||
});
|
||||
const out = highlightedLiterals(tree, 0, tree.length);
|
||||
cache.set(tree, out);
|
||||
return out;
|
||||
}
|
||||
@@ -86,7 +99,22 @@ export function literalKindAt(state: EditorState, pos: number): LiteralKind | nu
|
||||
|
||||
/** The comment or string literal `pos` lies in, if any. */
|
||||
export function literalAt(state: EditorState, pos: number): LiteralRange | null {
|
||||
const ranges = literalRanges(state);
|
||||
return rangeAt(literalRanges(state), pos);
|
||||
}
|
||||
|
||||
/**
|
||||
* Like `literalAt`, for a caller that only wants literals within one line: it parses and highlights
|
||||
* the line of `pos` and the line breaks around it, not the document. A literal that goes on past
|
||||
* the line comes back cut at the line break, so it still reaches into another line.
|
||||
*/
|
||||
export function lineLiteralAt(state: EditorState, pos: number): LiteralRange | null {
|
||||
const line = state.doc.lineAt(pos);
|
||||
const tree = ensureSyntaxTree(state, line.to, PARSE_BUDGET_MS) ?? syntaxTree(state);
|
||||
if (tree.length === 0) return literalAt(state, pos);
|
||||
return rangeAt(highlightedLiterals(tree, Math.max(0, line.from - 1), Math.min(tree.length, line.to + 1)), pos);
|
||||
}
|
||||
|
||||
function rangeAt(ranges: readonly LiteralRange[], pos: number): LiteralRange | null {
|
||||
let lo = 0;
|
||||
let hi = ranges.length - 1;
|
||||
while (lo <= hi) {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { EditorSelection, EditorState, Prec, type Extension } from "@codemirror/state";
|
||||
import { Decoration, EditorView } from "@codemirror/view";
|
||||
import { inlineBackground, inlineFramedFallback, inlineFramedModern } from "./inlineBg";
|
||||
import { selectionMarks } from "./selectionMarks";
|
||||
|
||||
const views: EditorView[] = [];
|
||||
@@ -54,4 +55,22 @@ describe("selectionMarks", () => {
|
||||
v.dispatch({ selection: EditorSelection.cursor(3) });
|
||||
expect(v.contentDOM.querySelector(".cm-openidea-selected")).toBeNull();
|
||||
});
|
||||
|
||||
it("caps inline highlight backgrounds and 1px frames at 1lh with pre-16.4 fallbacks", () => {
|
||||
expect(inlineBackground("var(--editor-search)")).toEqual({
|
||||
backgroundColor: "var(--editor-search)",
|
||||
background: "linear-gradient(var(--editor-search), var(--editor-search)) center / 100% 1lh no-repeat",
|
||||
WebkitBoxDecorationBreak: "clone",
|
||||
boxDecorationBreak: "clone",
|
||||
});
|
||||
expect(inlineFramedFallback("var(--fill)", "var(--frame)")).toMatchObject({
|
||||
backgroundColor: "var(--fill)",
|
||||
outline: "1px solid var(--frame)",
|
||||
outlineOffset: "-1px",
|
||||
});
|
||||
const modern = inlineFramedModern("var(--fill)", "var(--frame)");
|
||||
expect(modern.outline).toBe("none");
|
||||
expect(modern.background).toContain("100% min(100%, 1lh)");
|
||||
expect(modern.background).toContain("calc(100% - 2px) calc(min(100%, 1lh) - 2px)");
|
||||
});
|
||||
});
|
||||
Loaded 100 of 286 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user