Порівняти коміти

...
Автор SHA1 Повідомлення Дата
l0ng-ai 9e4e76f979 fix(agents): keep following a conversation's end unless the user scrolls away
A conversation stopped following its end, and stopped painting its earlier
entries, without the user scrolling: every scroll event recomputed "at the
end" from the offset, and WebKit moves the offset back on its own while rows
lay out (and the conversation can grow before the event of a scroll to the
end arrives). Switching tabs back showed it scrolled up with the rest never
loaded.

Only scrolling by the user (wheel, touch, keys, the scrollbar, Find) leaves
the end now; other scroll events while following go back to the end.
2026-11-09 12:26:44 +08:00
ppxb d17f6755f3 fix(dap): avoid free-port race when starting debug adapters (#2262) 2026-11-09 12:10:31 +08:00
l0ng-ai f1c10f4d84 perf(search): switch editors in the frame the Switcher closes (#2267)
The Switcher popup unmounts synchronously and gives focus back, then the selection opens in the same task, so closing and switching paint in one frame instead of two.
2026-11-09 12:05:04 +08:00
l0ng-ai 54d35d8a67 feat(lsp): language servers inside plugin-injected ranges (#2235)
* feat(lsp): language servers inside plugin-injected ranges

* chore(plugins): rebuild bundled plugins for the updated injections docs
2026-11-09 11:53:07 +08:00
arookieofc b6b09eb968 fix(delve): retry removing __debug_bin leftovers on Windows (#2257)
A just-killed dlv can still hold this session's binary while the previous
run's lock is already released, so one remove_file attempt only ever
deleted the older leftover. Retry with a short back-off so the sweep
outlasts the handle release.
2026-11-09 11:47:26 +08:00
l0ng-ai 36fae164a8 perf: add a scenario for switching between and scrolling long agent conversations (#2259)
Adds the agentTabs perf scenario: two 2,100-entry agent conversations switched with Ctrl+Tab and scrolled, with budgets on DOM size, rows skipping rendering off screen, switch latency, scroll jumps and frame pacing.
2026-11-09 11:36:35 +08:00
arookieofc 8c21a1e088 fix(run): scroll the config list and form independently in the editor dialog (#2255)
.editBody had a min-height but no cap, so a tall form grew it past the
viewport and the dialog body scrolled both panes together. Cap it below
the dialog's own body bound and let each pane's overflow take over.
2026-11-09 11:36:21 +08:00
l0ng-ai ecba8aff68 docs(readme): update the WeChat group QR code 2026-11-09 11:33:51 +08:00
arookieofc c90d3a7a8e fix(java): run jdtls on a new-enough JDK behind Scoop shims and project JAVA_HOME (#2230)
* fix(java): run jdtls on a new-enough JDK behind Scoop shims and project JAVA_HOME

Two ways jdtls ended up on a JDK too old for its bundles (#2227):

- jdtls_min_java resolved the command's own path to derive the install
  root, but a Scoop shim (shims\jdtls.exe) hides the release layout, so
  the bundles' real requirement fell back to JDTLS_MIN_JAVA (21) while a
  1.64 install needs JavaSE 25. Extract the resolve/follow-shim flow
  from launch_directly into jdtls::script_for and share it.
- configure_jdtls only wrote JAVA_HOME when the config had none, so a
  project JAVA_HOME (JDK 8 for compilation) won over the chosen
  server_jdk. Probe the configured value: a home too old or incomplete
  for the server is replaced by server_jdk or any usable JDK; an
  unresolvable explicit value stays (the user's call).

* test(java): compare JDK homes against canonical paths

jdk_at reports the canonicalized home (macOS /var -> /private/var,
Windows 8.3 short names), which configure_jdtls now writes to JAVA_HOME.
Have test_jdk canonicalize too, and assert the runtimes/JAVA_HOME values
against the Jdk.home fields instead of raw fixtures.path() joins, which
also differ on Windows when the join arg uses forward slashes.

* test(jdtls): compare JAVA_HOME against the canonical jdk home

test_jdk now canonicalizes home, so the duplicate-versions assertion must
compare against server.home rather than the raw tempdir join, which on
Windows carries 8.3 short names.
2026-11-09 11:08:28 +08:00
l0ng-ai 115d789091 perf(agents): make switching to a long conversation tab cheap (#2252)
Folded conversation sections render their content only when opened (or while Find in Conversation is open), and off-screen rows skip rendering once laid out, so showing a kept-alive agent tab no longer restyles the whole history.
2026-11-09 11:05:53 +08:00
Kamal ElFadlтаelfadl fb92a82101 feat(debugger): support clickable file and URL links in debug console (#2245)
Co-authored-by: elfadl <[email protected]>
2026-11-09 10:56:44 +08:00
arookieofc 7829bee55c fix(vcs): edit the full commit message, not only the subject (#2242)
A paged Git log only carries each commit's summary line; the Edit Commit
Message dialog therefore opened with the body missing, and OK rewrote the
commit to the subject alone.

Load the full message through loadLogDetails when the commit's
messageTruncated flag is set, the same path Copy Commit Message already
uses, so the dialog edits subject and body together.

Fixes #2238
2026-11-09 10:48:39 +08:00
l0ng-ai 13b590f2c7 feat(plugins): let test frameworks select tests to rerun (#2228)
* feat(plugins): let test frameworks select tests to rerun

* test(smoke): await Rerun Failed Tests
2026-11-09 10:08:51 +08:00
l0ng-ai 8d5504b376 fix(usages): keep the scope summary row from taking half of the Find Usages panel 2026-11-09 10:07:02 +08:00
l0ng-ai 60b19b2ffb Revert "fix(agents): stop defaulting new tasks to bypass" (#2234)
Reverts #2232: new agent tasks default to Bypass again.
2026-11-09 09:55:17 +08:00
l0ng-ai 73b3a99699 fix(agents): stop defaulting new tasks to bypass (#2232)
New agent tasks defaulted to Bypass whenever the provider offered it, whatever the user had chosen. A task now starts with the settings shown in the composer: the provider's reported mode, or Ask for Cursor. An explicit choice is kept, including Bypass, and running tasks keep their own mode. Cached provider settings could hold a Bypass written automatically with no record of its source, so a cached bypass is dropped on load, read and save while the option stays offered.

Fixes #740
2026-11-09 09:46:57 +08:00
arookieofc 95843ea12d fix(vue): highlight SCSS in <style lang="scss"> blocks (#2219) (#2221)
The Vue editor mode (`@codemirror/lang-vue` over the stock HTML base)
parses every `<style>` block as plain CSS, so SCSS — nested rules,
$-variables, and so on — rendered uncoloured or mis-highlighted.

Register a Vue mode of our own (overriding the language-data entry) that
gives the HTML base a nested Sass grammar for `<style>` whose `lang`
is `scss` or `sass`; blocks without a dialect keep CSS.
2026-11-09 09:23:17 +08:00
l0ng-ai 3dac5b8bdc fix(plugins): report Problems to plugins in remote projects (#2223) 2026-11-09 09:18:11 +08:00
l0ng-ai fd8b4ff14c fix(terminal): resume pasted input as soon as the PTY accepts more (#2220) 2026-11-09 09:17:30 +08:00
129 змінених файлів з 3834 додано та 570 видалено

No files matched your search

+128 -10
Переглянути файл
@@ -4,10 +4,12 @@ use std::collections::VecDeque;
use std::io::{self, Write};
use std::sync::{Arc, Condvar, Mutex};
use std::thread::JoinHandle;
#[cfg(any(not(unix), test))]
use std::time::Duration;
const MAX_BYTES: usize = 4 * 1024 * 1024;
const MAX_WRITES: usize = 1024;
#[cfg(any(not(unix), test))]
const RETRY: Duration = Duration::from_millis(4);
#[derive(Default)]
@@ -28,10 +30,11 @@ pub struct InputWriter {
}
impl InputWriter {
/// Unix writers must first be made nonblocking with `nonblocking`.
/// On Unix, pass the readiness hook returned by `nonblocking` for this writer.
pub fn new(
name: String,
mut writer: Box<dyn Write + Send>,
#[cfg(unix)] mut wait_writable: impl FnMut() -> io::Result<()> + Send + 'static,
on_error: impl FnOnce(io::Error) + Send + 'static,
) -> io::Result<Self> {
let shared = Arc::new((Mutex::new(State::default()), Condvar::new()));
@@ -74,11 +77,19 @@ impl InputWriter {
Ok(()) => {}
Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
let state = lock.lock().unwrap();
if state.aborted {
return Ok(());
#[cfg(unix)]
match wait_writable() {
Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
result => result?,
}
#[cfg(not(unix))]
{
let state = lock.lock().unwrap();
if state.aborted {
return Ok(());
}
drop(wake.wait_timeout(state, RETRY).unwrap());
}
drop(wake.wait_timeout(state, RETRY).unwrap());
}
Err(e) => return Err(e),
}
@@ -168,14 +179,46 @@ impl Drop for InputWriter {
}
}
/// PTY clones share file status flags, so readers must also handle WouldBlock.
/// Make a writer nonblocking and return its readiness hook. PTY clones share file
/// status flags, so readers must also handle WouldBlock.
#[cfg(unix)]
pub fn nonblocking(fd: std::os::fd::RawFd) -> io::Result<()> {
pub fn nonblocking(fd: std::os::fd::RawFd) -> io::Result<impl FnMut() -> io::Result<()> + Send> {
let wait = readiness(fd, libc::POLLOUT)?;
let flags = unsafe { libc::fcntl(fd, libc::F_GETFL) };
if flags == -1 || unsafe { libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK) } == -1 {
return Err(io::Error::last_os_error());
}
Ok(())
Ok(wait)
}
/// Wait for output from a nonblocking PTY without delaying the child's next read.
#[cfg(unix)]
pub fn readable(fd: std::os::fd::RawFd) -> io::Result<impl FnMut() -> io::Result<()> + Send> {
readiness(fd, libc::POLLIN)
}
#[cfg(unix)]
fn readiness(fd: std::os::fd::RawFd, events: libc::c_short) -> io::Result<impl FnMut() -> io::Result<()> + Send> {
use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
// Own a duplicate so the hook remains valid if the caller closes its fd.
let duplicate = unsafe { libc::fcntl(fd, libc::F_DUPFD_CLOEXEC, 0) };
if duplicate == -1 {
return Err(io::Error::last_os_error());
}
// SAFETY: fcntl returned a new, owned descriptor.
let fd = unsafe { OwnedFd::from_raw_fd(duplicate) };
Ok(move || {
let mut pollfd = libc::pollfd { fd: fd.as_raw_fd(), events, revents: 0 };
// Readiness wakes immediately; the timeout only bounds abort latency.
if unsafe { libc::poll(&mut pollfd, 1, 50) } == -1 {
return Err(io::Error::last_os_error());
}
if pollfd.revents & libc::POLLNVAL != 0 {
return Err(io::Error::from_raw_os_error(libc::EBADF));
}
Ok(())
})
}
#[cfg(test)]
@@ -221,6 +264,11 @@ mod tests {
let writer = InputWriter::new(
"test-input".into(),
Box::new(SlowWriter { ready: ready.clone(), output: output.clone(), dropped: tx }),
#[cfg(unix)]
|| {
std::thread::sleep(RETRY);
Ok(())
},
|e| panic!("{e}"),
)
.unwrap();
@@ -243,6 +291,11 @@ mod tests {
let writer = InputWriter::new(
"test-input".into(),
Box::new(SlowWriter { ready: ready.clone(), output: output.clone(), dropped: tx }),
#[cfg(unix)]
|| {
std::thread::sleep(RETRY);
Ok(())
},
|e| panic!("{e}"),
)
.unwrap();
@@ -256,6 +309,26 @@ mod tests {
assert_eq!(*output.lock().unwrap(), format!("{paste}tail").as_bytes());
}
#[cfg(unix)]
#[test]
fn readiness_errors_are_reported_and_reject_following_writes() {
let (dropped, _rx) = mpsc::channel();
let (errors, error) = mpsc::channel();
let writer = InputWriter::new(
"test-error-input".into(),
Box::new(SlowWriter { ready: Arc::new(AtomicBool::new(false)), output: Arc::default(), dropped }),
|| Err(io::Error::from_raw_os_error(libc::EBADF)),
move |e| errors.send(e.raw_os_error()).unwrap(),
)
.unwrap();
writer.write(b"input").unwrap();
assert_eq!(error.recv_timeout(Duration::from_secs(1)).unwrap(), Some(libc::EBADF));
assert_eq!(writer.write(b"later").unwrap_err().kind(), io::ErrorKind::BrokenPipe);
let state = writer.shared.0.lock().unwrap();
assert!(state.queue.is_empty());
assert_eq!(state.bytes, 0);
}
#[test]
fn tiny_writes_are_also_bounded() {
let shared = Arc::new((Mutex::new(State::default()), Condvar::new()));
@@ -266,14 +339,59 @@ mod tests {
assert_eq!(writer.write(b"x").unwrap_err().kind(), io::ErrorKind::WouldBlock);
}
#[cfg(unix)]
#[test]
fn writable_input_resumes_without_timer_delays() {
use std::io::Read;
use std::os::fd::AsRawFd;
use std::os::unix::net::UnixStream;
let (pipe, mut peer) = UnixStream::pair().unwrap();
let capacity: libc::c_int = 1024;
// Keep the OS buffer small enough that a timer per buffer takes seconds.
assert_eq!(
unsafe {
libc::setsockopt(
pipe.as_raw_fd(),
libc::SOL_SOCKET,
libc::SO_SNDBUF,
(&capacity as *const libc::c_int).cast(),
std::mem::size_of_val(&capacity) as libc::socklen_t,
)
},
0
);
peer.set_read_timeout(Some(Duration::from_secs(3))).unwrap();
let wait_writable = nonblocking(pipe.as_raw_fd()).unwrap();
let writer =
InputWriter::new("test-ready-input".into(), Box::new(pipe), wait_writable, |e| panic!("{e}")).unwrap();
let bytes = vec![b'x'; MAX_BYTES];
writer.write(&bytes).unwrap();
writer.finish();
// Start with a full buffer, then make the fd writable from another thread.
std::thread::sleep(Duration::from_millis(50));
let (tx, rx) = mpsc::channel();
let started = Instant::now();
let reader = std::thread::spawn(move || {
let mut output = Vec::new();
peer.read_to_end(&mut output).unwrap();
tx.send(output).unwrap();
});
let output = rx.recv_timeout(Duration::from_secs(1)).expect("input resumes as soon as the fd is writable");
assert_eq!(output, bytes);
reader.join().unwrap();
eprintln!("4 MiB input drained in {:?}", started.elapsed());
}
#[cfg(unix)]
#[test]
fn close_interrupts_a_full_os_pipe_while_the_peer_stays_open() {
use std::os::fd::AsRawFd;
use std::os::unix::net::UnixStream;
let (pipe, _peer) = UnixStream::pair().unwrap();
nonblocking(pipe.as_raw_fd()).unwrap();
let mut writer = InputWriter::new("test-pipe-input".into(), Box::new(pipe), |e| panic!("{e}")).unwrap();
let wait_writable = nonblocking(pipe.as_raw_fd()).unwrap();
let mut writer =
InputWriter::new("test-pipe-input".into(), Box::new(pipe), wait_writable, |e| panic!("{e}")).unwrap();
writer.write(&vec![b'x'; MAX_BYTES]).unwrap();
std::thread::sleep(Duration::from_millis(50));
assert!(!writer.worker.as_ref().unwrap().is_finished());
+147 -82
Переглянути файл
@@ -166,6 +166,11 @@ pub fn parse_address(addr: &str) -> Option<(String, u16)> {
}
/// A port that was free a moment ago on the loopback interface.
///
/// Inherently racy: another process can bind the port between the listener being
/// dropped here and the adapter binding it. Callers that hand the port to a child
/// retry on a bind conflict (see [`ProcessLauncher`]), or — better — let the child
/// pick `:0` and report the actual port back (as the Kotlin JDWP debuggee does).
pub fn free_port() -> std::io::Result<u16> {
let listener = std::net::TcpListener::bind(("127.0.0.1", 0))?;
Ok(listener.local_addr()?.port())
@@ -394,6 +399,9 @@ const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
const EMBEDDED_START_TIMEOUT: Duration = Duration::from_secs(120);
/// Probe of a `connect` address before starting the command.
const PROBE_TIMEOUT: Duration = Duration::from_millis(500);
/// Attempts at a fresh port for a TCP adapter: the one `free_port` hands out can be
/// claimed by another process before the adapter binds it, so a new one usually wins.
const PORT_ATTEMPTS: u32 = 3;
impl AdapterLauncher for ProcessLauncher {
fn launch(&self, mut spec: AdapterSpec, reuse_port: Option<u16>) -> LaunchFuture {
@@ -459,95 +467,140 @@ impl AdapterLauncher for ProcessLauncher {
.ok_or_else(|| missing(&spec))?
}
};
let port = match spec.transport {
// An embedded adapter started without `${port}` listens on its usual address.
Transport::Tcp => match &embedded {
Some((_, port)) if !spec.args.iter().any(|a| a.contains(PORT_PLACEHOLDER)) => Some(*port),
_ => Some(free_port()?),
},
Transport::Stdio => None,
};
let args = substitute_root(&spec.args, &spec.cwd);
let args = match port {
Some(port) => substitute_port(&args, port),
None => args,
};
let mut cmd = Command::new(&binary);
if let Some(path) = adapter_path(&spec.env) {
cmd.env("PATH", path);
}
ide_core::process::prepare(cmd.as_std_mut());
if spec.adapter == "rdbg" {
ide_core::process::own_group(cmd.as_std_mut());
}
cmd.args(&args)
.envs(spec.env.iter().map(|(k, v)| (k, v)))
.current_dir(&spec.cwd)
.stdin(if port.is_some() { Stdio::null() } else { Stdio::piped() })
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true);
let mut child =
cmd.spawn().map_err(|e| IdeError::unavailable(format!("failed to start {}: {e}", binary.display())))?;
let (program_sink, program_output) = if SHARES_STDIO.contains(&spec.adapter.as_str()) {
let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
(Some(tx), Some(rx))
} else {
(None, None)
};
if let Some(err) = child.stderr.take() {
pump_lines(err, spec.adapter.clone(), stderr.clone(), program_sink.clone().map(|tx| (tx, "stderr")));
}
match port {
None => {
let stdin = child.stdin.take().ok_or_else(|| IdeError::internal("adapter stdin unavailable"))?;
let stdout = child.stdout.take().ok_or_else(|| IdeError::internal("adapter stdout unavailable"))?;
Ok(AdapterIo {
reader: Box::new(stdout),
writer: Box::new(stdin),
child: Some(child),
port: None,
stderr,
program_output,
})
}
Some(port) => {
if let Some(out) = child.stdout.take() {
pump_lines(out, spec.adapter.clone(), stderr.clone(), program_sink.map(|tx| (tx, "stdout")));
}
let timeout = if embedded.is_some() { EMBEDDED_START_TIMEOUT } else { CONNECT_TIMEOUT };
let stream = match connect_with_retries(LOOPBACK, port, Some(&mut child), timeout).await {
Ok(s) => s,
Err(e) => {
if spec.adapter == "rdbg"
&& let Some(pid) = child.id()
{
ide_core::process::kill_tree_of(pid);
}
let _ = child.start_kill();
let tail = stderr.lock().join("\n");
return Err(if tail.is_empty() {
e
} else {
IdeError::unavailable(format!("{}\n{tail}", e.message))
});
}
let base_args = substitute_root(&spec.args, &spec.cwd);
match spec.transport {
Transport::Stdio => spawn_adapter(&spec, &binary, &base_args, None, CONNECT_TIMEOUT).await,
Transport::Tcp => {
// An embedded adapter started without `${port}` listens on its usual
// address; every other TCP adapter gets a port chosen here so it can be
// retried if another process takes it before the adapter binds.
let fixed = match &embedded {
Some((_, port)) if !spec.args.iter().any(|a| a.contains(PORT_PLACEHOLDER)) => Some(*port),
_ => None,
};
let (r, w) = stream.into_split();
Ok(AdapterIo {
reader: Box::new(r),
writer: Box::new(w),
child: Some(child),
port: Some(port),
stderr,
program_output,
})
let start_timeout = if embedded.is_some() { EMBEDDED_START_TIMEOUT } else { CONNECT_TIMEOUT };
for attempt in 1..=PORT_ATTEMPTS {
let port = match fixed {
Some(port) => port,
None => free_port()?,
};
let args = substitute_port(&base_args, port);
match spawn_adapter(&spec, &binary, &args, Some(port), start_timeout).await {
Ok(io) => return Ok(io),
Err(e) => {
if fixed.is_none() && attempt < PORT_ATTEMPTS && is_port_race(&e) {
tracing::warn!(
target: "ide_dap::adapter",
"debug adapter failed to start on port {port}: {}; retrying",
e.message
);
continue;
}
return Err(e);
}
}
}
unreachable!("the retry loop returns on its last attempt")
}
}
})
}
}
/// Starts `binary` with `args`, then connects to it when `port` is set (a TCP adapter)
/// or hands back its stdio when it is not. The child is stopped if it never accepts.
async fn spawn_adapter(
spec: &AdapterSpec,
binary: &Path,
args: &[String],
port: Option<u16>,
start_timeout: Duration,
) -> IdeResult<AdapterIo> {
let stderr = Arc::new(parking_lot::Mutex::new(Vec::new()));
let mut cmd = Command::new(binary);
if let Some(path) = adapter_path(&spec.env) {
cmd.env("PATH", path);
}
ide_core::process::prepare(cmd.as_std_mut());
if spec.adapter == "rdbg" {
ide_core::process::own_group(cmd.as_std_mut());
}
cmd.args(args)
.envs(spec.env.iter().map(|(k, v)| (k, v)))
.current_dir(&spec.cwd)
.stdin(if port.is_some() { Stdio::null() } else { Stdio::piped() })
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true);
let mut child =
cmd.spawn().map_err(|e| IdeError::unavailable(format!("failed to start {}: {e}", binary.display())))?;
let (program_sink, program_output) = if SHARES_STDIO.contains(&spec.adapter.as_str()) {
let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
(Some(tx), Some(rx))
} else {
(None, None)
};
if let Some(err) = child.stderr.take() {
pump_lines(err, spec.adapter.clone(), stderr.clone(), program_sink.clone().map(|tx| (tx, "stderr")));
}
match port {
None => {
let stdin = child.stdin.take().ok_or_else(|| IdeError::internal("adapter stdin unavailable"))?;
let stdout = child.stdout.take().ok_or_else(|| IdeError::internal("adapter stdout unavailable"))?;
Ok(AdapterIo {
reader: Box::new(stdout),
writer: Box::new(stdin),
child: Some(child),
port: None,
stderr,
program_output,
})
}
Some(port) => {
if let Some(out) = child.stdout.take() {
pump_lines(out, spec.adapter.clone(), stderr.clone(), program_sink.map(|tx| (tx, "stdout")));
}
let stream = match connect_with_retries(LOOPBACK, port, Some(&mut child), start_timeout).await {
Ok(s) => s,
Err(e) => {
if spec.adapter == "rdbg"
&& let Some(pid) = child.id()
{
ide_core::process::kill_tree_of(pid);
}
let _ = child.start_kill();
let tail = stderr.lock().join("\n");
return Err(if tail.is_empty() {
e
} else {
IdeError::unavailable(format!("{}\n{tail}", e.message))
});
}
};
let (r, w) = stream.into_split();
Ok(AdapterIo {
reader: Box::new(r),
writer: Box::new(w),
child: Some(child),
port: Some(port),
stderr,
program_output,
})
}
}
}
/// A failed adapter start that another process grabbing the free port can explain
/// (POSIX and Windows "address already in use" texts, or the adapter exiting because
/// it could not bind). Anything else is a real start failure and is not retried.
fn is_port_race(err: &IdeError) -> bool {
let message = err.message.to_ascii_lowercase();
message.contains("address already in use")
|| message.contains("addrinuse")
|| message.contains("only one usage of each socket address")
|| message.contains("exited before accepting connections")
}
fn pump_lines<R: AsyncRead + Unpin + Send + 'static>(
stream: R,
name: String,
@@ -775,4 +828,16 @@ mod tests {
assert_eq!(err.kind, ide_core::error::ErrorKind::Unavailable);
assert!(err.message.contains("runs inside the Java language server"), "{}", err.message);
}
#[test]
fn port_conflicts_are_recognised_for_retry() {
let in_use = IdeError::unavailable(
"debug adapter exited before accepting connections (exit status: 1)\nbind: address already in use",
);
assert!(is_port_race(&in_use));
assert!(is_port_race(&IdeError::unavailable(
"Only one usage of each socket address (protocol/network address/port) is normally permitted."
)));
assert!(!is_port_race(&IdeError::unavailable("failed to start codelldb: file not found")));
}
}
+16 -5
Переглянути файл
@@ -607,11 +607,22 @@ fn remove_delve_binaries(cwd: &Path) {
|| s == ".exe"
|| (s.starts_with(".exe") && s[".exe".len()..].chars().all(|c| c.is_ascii_digit()))
});
if leftover
&& entry.file_type().is_ok_and(|t| t.is_file())
&& let Err(e) = std::fs::remove_file(entry.path())
{
tracing::debug!("could not remove Delve leftover {}: {e}", entry.path().display());
if !leftover || entry.file_type().is_ok_and(|t| !t.is_file()) {
continue;
}
// Windows: a just-killed dlv / debuggee can still hold this session's
// binary while the previous one's lock is already gone, so one try
// leaves exactly the current leftover behind. Retry on a short back-off
// to outlast the handle release; a truly busy file is retried into the
// next run's sweep anyway.
for attempt in 0..5 {
match std::fs::remove_file(entry.path()) {
Ok(()) => break,
Err(e) if attempt == 4 => {
tracing::debug!("could not remove Delve leftover {}: {e}", entry.path().display());
}
Err(_) => std::thread::sleep(std::time::Duration::from_millis(50 * (attempt as u64 + 1))),
}
}
}
}
+65 -12
Переглянути файл
@@ -630,9 +630,15 @@ pub(crate) fn run_in_terminal(s: &Arc<Session>, args: &Value) -> Result<Value, S
.openpty(PtySize { rows: 24, cols: 200, pixel_width: 0, pixel_height: 0 })
.map_err(|e| format!("cannot open a terminal for {program}: {e}"))?;
#[cfg(unix)]
if let Some(fd) = pair.master.as_raw_fd() {
ide_core::input::nonblocking(fd).map_err(|e| format!("terminal of {program}: {e}"))?;
}
let wait_writable = ide_core::input::nonblocking(
pair.master.as_raw_fd().ok_or_else(|| format!("terminal of {program}: PTY has no file descriptor"))?,
)
.map_err(|e| format!("terminal of {program}: {e}"))?;
#[cfg(unix)]
let wait_readable = ide_core::input::readable(
pair.master.as_raw_fd().ok_or_else(|| format!("terminal of {program}: PTY has no file descriptor"))?,
)
.map_err(|e| format!("terminal of {program}: {e}"))?;
let mut cmd = CommandBuilder::new(program);
// CodeLLDB's launcher clears the terminal first; the console keeps the session's earlier output.
cmd.args(rest.iter().filter(|a| *a != "--clear-screen"));
@@ -662,16 +668,27 @@ pub(crate) fn run_in_terminal(s: &Arc<Session>, args: &Value) -> Result<Value, S
drop(pair.slave);
let reader = pair.master.try_clone_reader().map_err(|e| format!("terminal of {program}: {e}"))?;
let writer = pair.master.take_writer().map_err(|e| format!("terminal of {program}: {e}"))?;
let writer = ide_core::input::InputWriter::new(format!("openidea-debug-input-{}", s.id.0), writer, |e| {
tracing::warn!("debug input: {e}");
})
let writer = ide_core::input::InputWriter::new(
format!("openidea-debug-input-{}", s.id.0),
writer,
#[cfg(unix)]
wait_writable,
|e| {
tracing::warn!("debug input: {e}");
},
)
.inspect_err(|_| {
let _ = child.kill();
let _ = child.wait();
})
.map_err(|e| format!("terminal input worker: {e}"))?;
let pid = child.process_id();
forward_terminal_output(s, reader);
forward_terminal_output(
s,
reader,
#[cfg(unix)]
wait_readable,
);
if let Some(mut previous) = s.program.lock().replace(ProgramTerminal { writer, child, _master: pair.master }) {
let _ = previous.child.kill();
}
@@ -680,7 +697,11 @@ pub(crate) fn run_in_terminal(s: &Arc<Session>, args: &Value) -> Result<Value, S
}
/// The program's terminal output, as stdout lines (`\r\n` as `\n`; colours are kept).
fn forward_terminal_output(s: &Session, mut reader: Box<dyn std::io::Read + Send>) {
fn forward_terminal_output(
s: &Session,
mut reader: Box<dyn std::io::Read + Send>,
#[cfg(unix)] mut wait_readable: impl FnMut() -> std::io::Result<()> + Send + 'static,
) {
let session = s.id;
let sink = s.owner.sink.clone();
let _ = std::thread::Builder::new().name(format!("openidea-debuggee-{}", session.0)).spawn(move || {
@@ -692,6 +713,14 @@ fn forward_terminal_output(s: &Session, mut reader: Box<dyn std::io::Read + Send
Ok(n) => pending.extend_from_slice(&buf[..n]),
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
#[cfg(unix)]
if let Err(e) = wait_readable()
&& e.kind() != std::io::ErrorKind::Interrupted
{
tracing::warn!(%session, "debug terminal read: {e}");
break;
}
#[cfg(not(unix))]
std::thread::sleep(std::time::Duration::from_millis(4));
continue;
}
@@ -762,7 +791,6 @@ fn forward_output<R: AsyncRead + Unpin + Send + 'static>(s: &Session, mut stream
/// Launch with the IDE's resolved runtime and classpath; the adapter only attaches.
pub(crate) async fn start_kotlin_debuggee(s: &Arc<Session>, args: &mut Value) -> ide_core::IdeResult<()> {
use tokio::io::{AsyncBufReadExt, BufReader};
let port = crate::adapter::free_port()?;
let java = args.get("javaExec").and_then(Value::as_str).unwrap_or("java");
let strings = |key: &str| -> Vec<String> {
args.get(key)
@@ -775,7 +803,9 @@ pub(crate) async fn start_kotlin_debuggee(s: &Arc<Session>, args: &mut Value) ->
let mut cmd = tokio::process::Command::new(java);
ide_core::process::prepare(cmd.as_std_mut());
cmd.args(strings("vmArguments"))
.arg(format!("-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=127.0.0.1:{port}"))
// Let the JVM pick its own port (`:0`) and report it below: pre-picking a free
// port here races with other processes that may take it before the JVM binds.
.arg("-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=127.0.0.1:0")
.arg("-cp")
.arg(classpath);
let modules = strings("modulePaths");
@@ -808,14 +838,18 @@ pub(crate) async fn start_kotlin_debuggee(s: &Arc<Session>, args: &mut Value) ->
}
let mut stdout =
BufReader::new(child.stdout.take().ok_or_else(|| ide_core::IdeError::internal("Missing JVM stdout"))?);
tokio::time::timeout(Duration::from_secs(15), async {
// The JVM chose the port (`:0` above) and reports it here; reading it back removes
// the free-port race window entirely.
let port = tokio::time::timeout(Duration::from_secs(15), async {
loop {
let mut line = String::new();
if stdout.read_line(&mut line).await? == 0 {
return Err(ide_core::IdeError::unavailable("JVM exited before starting its debug listener"));
}
if line.contains("Listening for transport dt_socket") {
return Ok(());
return parse_jdwp_port(&line).ok_or_else(|| {
ide_core::IdeError::unavailable(format!("JVM reported an unreadable debug port: {}", line.trim()))
});
}
s.emit(DebugEvent::Output { category: "stdout".into(), output: line });
}
@@ -829,3 +863,22 @@ pub(crate) async fn start_kotlin_debuggee(s: &Arc<Session>, args: &mut Value) ->
args["timeout"] = json!(10000);
Ok(())
}
/// The port a JVM chose, from `Listening for transport dt_socket at address: <port>`
/// (some JVMs print `host:port` or `[::1]:port`, so take what follows the last colon).
fn parse_jdwp_port(line: &str) -> Option<u16> {
line.rsplit_once("address:")?.1.trim().rsplit(':').next()?.trim().parse().ok()
}
#[cfg(test)]
mod tests {
use super::parse_jdwp_port;
#[test]
fn reads_the_port_the_jvm_chose() {
assert_eq!(parse_jdwp_port("Listening for transport dt_socket at address: 51234"), Some(51234));
assert_eq!(parse_jdwp_port("Listening for transport dt_socket at address: 127.0.0.1:51234"), Some(51234));
assert_eq!(parse_jdwp_port("Listening for transport dt_socket at address: [::1]:51234"), Some(51234));
assert_eq!(parse_jdwp_port("unrelated output"), None);
}
}
+107 -20
Переглянути файл
@@ -9,6 +9,34 @@ use ide_lsp::types::*;
use ide_plugin::ProviderDocument;
use std::path::Path;
/// Select an embedded server only for point requests; formatting and rename keep the host.
async fn position_document(host: &Host, window: &str, doc: DocId, pos: Pos) -> IdeResult<DocId> {
let lsp = host.project(window)?.lsp.clone();
lsp.refresh_injections(doc).await?;
Ok(lsp.injected_document(doc, pos))
}
async fn begin_position_request(
host: &Host,
window: &str,
request: RequestId,
doc: DocId,
pos: Pos,
) -> IdeResult<(DocId, ide_core::CancellationToken)> {
let cancel = host.begin_request(request);
let target = tokio::select! {
result = position_document(host, window, doc, pos) => result,
_ = cancel.cancelled() => Err(ide_core::IdeError::cancelled()),
};
match target {
Ok(target) => Ok((target, cancel)),
Err(e) => {
host.end_request(request);
Err(e)
}
}
}
async fn prepare_actions(
project: std::sync::Arc<crate::Project>,
doc: DocId,
@@ -41,8 +69,8 @@ pub async fn lsp_completion(
trigger: Option<String>,
) -> IdeResult<CompletionList> {
let lsp = host.project(window)?.lsp.clone();
let cancel = host.begin_request(request);
let result = lsp.completion(doc, pos, trigger.clone(), cancel).await;
let (target, cancel) = begin_position_request(host, window, request, doc, pos).await?;
let result = lsp.completion(target, pos, trigger.clone(), cancel).await;
host.end_request(request);
// Plugin providers (`[[contributes.providers]]`) add theirs.
let Some((plugins, d)) = plugin_providers(host, window, doc, ProviderKind::Completion) else { return result };
@@ -238,14 +266,14 @@ pub async fn lsp_hover(
pos: Pos,
) -> IdeResult<Option<Hover>> {
let lsp = host.project(window)?.lsp.clone();
let cancel = host.begin_request(request);
let (target, cancel) = begin_position_request(host, window, request, doc, pos).await?;
let Some((plugins, d)) = plugin_providers(host, window, doc, ProviderKind::Hover) else {
let result = lsp.hover(doc, pos, cancel).await;
let result = lsp.hover(target, pos, cancel).await;
host.end_request(request);
return result;
};
let (result, hovers) =
tokio::join!(lsp.hover(doc, pos, cancel), plugin_call(move || plugins.provide_hover(&d, pos)));
tokio::join!(lsp.hover(target, pos, cancel), plugin_call(move || plugins.provide_hover(&d, pos)));
host.end_request(request);
let hovers = hovers.unwrap_or_default();
if hovers.is_empty() {
@@ -260,7 +288,8 @@ pub async fn lsp_hover(
}
pub async fn lsp_signature_help(host: &Host, window: &str, doc: DocId, pos: Pos) -> IdeResult<Option<SignatureHelp>> {
let server = host.project(window)?.lsp.signature_help(doc, pos).await;
let target = position_document(host, window, doc, pos).await?;
let server = host.project(window)?.lsp.signature_help(target, pos).await;
if matches!(&server,Ok(Some(h)) if !h.signatures.is_empty()) {
return server;
}
@@ -278,7 +307,9 @@ pub async fn lsp_signature_help(host: &Host, window: &str, doc: DocId, pos: Pos)
}
pub async fn lsp_goto(host: &Host, window: &str, doc: DocId, pos: Pos, kind: GotoKind) -> IdeResult<Vec<Location>> {
if kind == GotoKind::Definition
let target = position_document(host, window, doc, pos).await?;
if target == doc
&& kind == GotoKind::Definition
&& let Some(plugins) = crate::plugins::editor_plugin_host()
{
let project = host.project(window)?;
@@ -289,7 +320,7 @@ pub async fn lsp_goto(host: &Host, window: &str, doc: DocId, pos: Pos, kind: Got
return Ok(found.targets);
}
}
let result = host.project(window)?.lsp.goto(doc, pos, kind).await;
let result = host.project(window)?.lsp.goto(target, pos, kind).await;
if matches!(kind, GotoKind::Implementation | GotoKind::TypeDefinition) {
let k =
if kind == GotoKind::Implementation { ProviderKind::Implementation } else { ProviderKind::TypeDefinition };
@@ -424,8 +455,46 @@ pub async fn lsp_implementations(
positions: Vec<Pos>,
) -> IdeResult<Vec<Vec<Location>>> {
let lsp = host.project(window)?.lsp.clone();
let cancel = host.begin_request(request);
let result = lsp.implementations(doc, &positions, cancel).await;
let (_, cancel) =
begin_position_request(host, window, request, doc, positions.first().copied().unwrap_or_default()).await?;
let mut groups = std::collections::BTreeMap::<DocId, Vec<(usize, Pos)>>::new();
for (index, pos) in positions.iter().copied().enumerate() {
groups.entry(lsp.injected_document(doc, pos)).or_default().push((index, pos));
}
if groups.is_empty() {
groups.insert(doc, Vec::new());
}
let results = futures::future::join_all(groups.into_iter().map(|(target, entries)| {
let (lsp, cancel) = (lsp.clone(), cancel.clone());
async move {
let positions: Vec<_> = entries.iter().map(|(_, p)| *p).collect();
(entries, lsp.implementations(target, &positions, cancel).await)
}
}))
.await;
let mut out = vec![Vec::new(); positions.len()];
let mut error = None;
let mut succeeded = false;
for (entries, result) in results {
match result {
Ok(found) => {
succeeded = true;
for ((index, _), locations) in entries.into_iter().zip(found) {
out[index] = locations;
}
}
Err(e) => {
error.get_or_insert(e);
}
}
}
let result = if cancel.is_cancelled() {
Err(ide_core::IdeError::cancelled())
} else if succeeded {
Ok(out)
} else {
Err(error.expect("at least one request"))
};
host.end_request(request);
if let Some((plugins, d)) = plugin_providers(host, window, doc, ProviderKind::Implementation) {
let count = positions.len();
@@ -456,9 +525,9 @@ pub async fn lsp_goto_implementation(
on_partial: super::Channel<Vec<Location>>,
) -> IdeResult<Vec<Location>> {
let lsp = host.project(window)?.lsp.clone();
let cancel = host.begin_request(request);
let (target, cancel) = begin_position_request(host, window, request, doc, pos).await?;
let result = lsp
.goto_implementation(doc, pos, cancel, &|locs| {
.goto_implementation(target, pos, cancel, &|locs| {
let _ = on_partial.send(locs);
})
.await;
@@ -505,9 +574,9 @@ pub async fn lsp_references(
) -> IdeResult<References> {
let project = host.project(window)?;
let lsp = project.lsp.clone();
let cancel = host.begin_request(request);
let (target, cancel) = begin_position_request(host, window, request, doc, pos).await?;
let result = async {
let symbol = indexed_symbol(host, window, doc, pos).await?;
let symbol = if target == doc { indexed_symbol(host, window, doc, pos).await? } else { None };
if let Some(symbol) = &symbol {
let project = project.clone();
let snapshot = symbol.clone();
@@ -517,7 +586,7 @@ pub async fn lsp_references(
}
let result = lsp
.references_streaming(
doc,
target,
pos,
include_declaration,
project_wide,
@@ -643,7 +712,8 @@ fn merge_indexed_references(mut server: References, symbol: &crate::plugins::nav
}
pub async fn lsp_document_highlights(host: &Host, window: &str, doc: DocId, pos: Pos) -> IdeResult<Vec<Highlight>> {
let server = host.project(window)?.lsp.document_highlights(doc, pos).await;
let target = position_document(host, window, doc, pos).await?;
let server = host.project(window)?.lsp.document_highlights(target, pos).await;
let Some((plugins, d)) = plugin_providers(host, window, doc, ProviderKind::DocumentHighlights) else {
return server;
};
@@ -674,7 +744,9 @@ pub async fn lsp_code_actions(
let project = host.project(window)?;
let documents = project.documents.clone();
let version = blocking(move || documents.version(doc)).await?;
let result = project.lsp.code_actions(doc, range, only.clone()).await;
let target = position_document(host, window, doc, range.start).await?;
let range = project.lsp.injected_request_range(target, range);
let result = project.lsp.code_actions(target, range, only.clone()).await;
let plugin_actions = match plugin_providers(host, window, doc, ProviderKind::CodeActions) {
Some((plugins, d)) => plugin_call(move || plugins.provide_code_actions(&d, range)).await.unwrap_or_default(),
None => Vec::new(),
@@ -811,8 +883,9 @@ pub async fn lsp_code_action_query(
let project = host.project(window)?;
let documents = project.documents.clone();
let version = blocking(move || documents.version(doc)).await?;
let cancel = host.begin_request(request);
let result = project.lsp.code_action_query(doc, range, only, cancel).await;
let (target, cancel) = begin_position_request(host, window, request, doc, range.start).await?;
let range = project.lsp.injected_request_range(target, range);
let result = project.lsp.code_action_query(target, range, only, cancel).await;
host.end_request(request);
let mut result = result?;
result.actions = prepare_actions(project, doc, version, result.actions).await?;
@@ -1433,7 +1506,9 @@ pub struct PluginLanguageVisuals {
pub gutter_actions: Vec<(String, ide_plugin::language_features::GutterAction)>,
}
pub async fn plugin_language_visuals(host: &Host, window: &str, doc: DocId) -> IdeResult<PluginLanguageVisuals> {
let snap = host.project(window)?.documents.snapshot(doc)?;
let project = host.project(window)?;
let snap = project.documents.snapshot(doc)?;
let generation = project.lsp.injection_generation();
blocking(move || {
let d = ProviderDocument {
path: snap.path.0,
@@ -1450,6 +1525,18 @@ pub async fn plugin_language_visuals(host: &Host, window: &str, doc: DocId) -> I
out.colors = plugins.language_colors(&d);
out.gutter_actions = plugins.language_gutter_actions(&d);
}
project.lsp.set_injections_at(
doc,
d.version as u32,
out.injections
.iter()
.map(|i| ide_lsp::InjectedRange {
range: i.range,
language: ide_core::LanguageId::new(i.language.clone()),
})
.collect(),
generation,
);
Ok(out)
})
.await
+41 -8
Переглянути файл
@@ -276,16 +276,12 @@ impl PluginHost {
self.shared.run_configurations.write().insert((plugin, project), items);
}
}
/// Parses a bounded batch under the editor-provider soft/hard budgets.
pub fn parse_test_results(
/// Resolves only an owned plugin test configuration in the client's trusted project.
fn test_configuration(
&self,
client: &str,
config: &str,
chunk: String,
) -> IdeResult<Option<Vec<ide_plugin::PluginTestEvent>>> {
if chunk.len() > 64 << 10 {
return Err(IdeError::invalid("test output batch too large"));
}
) -> IdeResult<Option<(std::path::PathBuf, String, String)>> {
let root = self.shared.project_of(client).ok_or_else(|| IdeError::not_found("no project"))?;
if !self.shared.workspace().is_some_and(|w| w.trusted(&root)) {
return Err(IdeError::invalid("project is not trusted"));
@@ -302,7 +298,44 @@ impl PluginHost {
{
return Ok(None);
}
let plugin = self.get(owner)?;
Ok(Some((root, owner.to_owned(), id.to_owned())))
}
/// Derives replacement argv under the parser's soft/hard call budgets.
pub fn select_tests(&self, client: &str, config: &str, tests: Vec<Vec<String>>) -> IdeResult<Option<Vec<String>>> {
if tests.is_empty()
|| tests.len() > 10000
|| tests.iter().any(|p| p.is_empty() || p.len() > 128)
|| serde_json::to_vec(&tests).is_ok_and(|b| b.len() > 4 << 20)
{
return Ok(None);
}
let Some((root, owner, id)) = self.test_configuration(client, config)? else { return Ok(None) };
let plugin = self.get(&owner)?;
let (actor, activated) = self.ensure_active(&plugin, None)?;
if activated {
self.changed();
}
let invocation = ide_plugin::Invocation { workspace_root: Some(root), ..Default::default() };
let hard = self.limits.edit_hard;
let started = Instant::now();
let result = actor.call(Some(self.limits.edit_soft), move |rt| rt.select_tests(id, tests, invocation, hard));
let args = self.finish_provider_call(&plugin, &actor, started, result).flatten();
Ok(args.filter(|args| args.len() <= 10000 && args.iter().map(String::len).sum::<usize>() <= 4 << 20))
}
/// Parses a bounded batch under the editor-provider soft/hard budgets.
pub fn parse_test_results(
&self,
client: &str,
config: &str,
chunk: String,
) -> IdeResult<Option<Vec<ide_plugin::PluginTestEvent>>> {
if chunk.len() > 64 << 10 {
return Err(IdeError::invalid("test output batch too large"));
}
let Some((root, owner, id)) = self.test_configuration(client, config)? else { return Ok(None) };
let plugin = self.get(&owner)?;
let (actor, activated) = self.ensure_active(&plugin, None)?;
if activated {
self.changed();
+33 -1
Переглянути файл
@@ -1,4 +1,4 @@
//! Embedded plugin-provider documents preserve the host's UTF-16 coordinates.
//! Embedded documents preserve the host's UTF-16 coordinates.
use super::{PluginHost, ProviderKind};
use ide_core::{Pos, Range};
use ide_plugin::{ProviderDocument, language_features::Injection};
@@ -104,6 +104,38 @@ pub(crate) fn virtual_text(doc: &ProviderDocument, ranges: &[Injection], languag
text
}
/// Shared by local and remote projects; all plugin work runs on the host.
static LSP_PROJECTS: parking_lot::Mutex<Vec<std::sync::Weak<ide_lsp::LspManager>>> =
parking_lot::Mutex::new(Vec::new());
pub(super) fn providers_changed() {
let projects = {
let mut projects = LSP_PROJECTS.lock();
projects.retain(|p| p.strong_count() > 0);
projects.iter().filter_map(std::sync::Weak::upgrade).collect::<Vec<_>>()
};
for project in projects {
project.injection_providers_changed();
}
}
pub(crate) fn configure_lsp(lsp: &Arc<ide_lsp::LspManager>) {
LSP_PROJECTS.lock().push(Arc::downgrade(lsp));
lsp.set_injection_provider(Arc::new(|path, language, version, text| {
let Some(plugins) = super::editor_plugin_host() else { return Vec::new() };
plugins
.provide_injections(&ProviderDocument {
path: path.to_path_buf(),
language: language.0.clone(),
version: version.into(),
text: text.to_owned(),
})
.into_iter()
.map(|i| ide_lsp::InjectedRange { range: i.range, language: ide_core::LanguageId::new(i.language) })
.collect()
}));
}
#[cfg(test)]
mod tests {
use super::*;
+1 -1
Переглянути файл
@@ -11,7 +11,7 @@ use std::collections::{BTreeMap, HashMap};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Weak};
pub const MAX_DOCUMENT_BYTES: usize = 2 << 20;
pub const MAX_DOCUMENT_BYTES: usize = ide_lsp::MAX_INJECTED_DOCUMENT_BYTES;
const MAX_FILES: usize = 20_000;
const MAX_EDGES: usize = 4096;
+14
Переглянути файл
@@ -76,16 +76,29 @@ pub struct Providers {
impl Providers {
fn add(self: &Arc<Self>, plugin: String, decl: Decl) -> Disposable {
let injections = decl.kinds.contains(&ProviderKind::Injections);
let seq = self.seq.fetch_add(1, Ordering::Relaxed);
self.items.write().push((seq, plugin, decl.kinds, decl.languages));
if injections {
self.injections_changed();
}
let weak = Arc::downgrade(self);
Disposable::new(move || {
if let Some(this) = weak.upgrade() {
this.items.write().retain(|(s, ..)| *s != seq);
if injections {
this.injections_changed();
}
}
})
}
fn injections_changed(self: &Arc<Self>) {
if editor_plugin_host().is_some_and(|host| Arc::ptr_eq(&host.providers, self)) {
super::injections::providers_changed();
}
}
/// Plugins providing `kind` for `language`, in declaration order.
pub fn plugins_for(&self, kind: ProviderKind, language: &str) -> Vec<String> {
self.matching::<Vec<_>>(kind, language).into_iter().map(|(plugin, _)| plugin).collect()
@@ -260,6 +273,7 @@ static EDITOR_PROVIDERS: RwLock<Option<Weak<PluginHost>>> = RwLock::new(None);
/// definition and inline completion (`None` removes them).
pub fn set_editor_providers(host: Option<&Arc<PluginHost>>) {
*EDITOR_PROVIDERS.write() = host.map(Arc::downgrade);
super::injections::providers_changed();
}
/// The plugin host whose providers take part, when any declares `kind`.
+15
Переглянути файл
@@ -468,6 +468,16 @@ impl RemotePlugins {
}
});
let h = host.clone();
d.add("plugin_select_tests", move |c| {
let h = h.clone();
async move {
let host = alive(&h)?;
let config = c.arg::<String>("config")?;
let tests = c.arg("tests")?;
blocking(move || host.select_tests(&c.window, &config, tests)).await
}
});
let h = host.clone();
d.add("plugin_parse_test_results", move |c| {
let h = h.clone();
async move {
@@ -617,6 +627,11 @@ impl RemotePlugins {
c.host.mcp_reports.set_focused_editor(&c.window, c.arg("editor")?, c.arg("focused")?);
Ok(())
});
d.add("mcp_report_problems", |c| async move {
c.host.project(&c.window)?;
c.host.mcp_reports.report_problems(&c.window, c.arg("reset")?, c.arg("files")?);
Ok(())
});
let h = host.clone();
d.add("plugin_decoration_sets", move |_c| {
let h = h.clone();
+1
Переглянути файл
@@ -133,6 +133,7 @@ impl Host {
)?;
mark("index");
let lsp = LspManager::new(root.clone(), languages.clone(), sink.clone());
crate::plugins::injections::configure_lsp(&lsp);
lsp.set_execution_allowed(trusted.load(Ordering::Acquire));
lsp.set_content_roots(extra_roots.clone());
let settings = Arc::new(settings);
+4
Переглянути файл
@@ -286,6 +286,10 @@ where
let p = Peer::connect(reader, writer, handler);
let _ = peer.set(p.clone());
p.closed().await;
// Reports belong to the disconnected desktop, even while the host shuts down.
for window in host.projects.read().keys() {
host.mcp_reports.forget_window(window);
}
}
/// Sends a window's events to the client as `event` notifications.
+132
Переглянути файл
@@ -93,6 +93,9 @@ async fn editor_ops_merge_the_fixture_format_selection_and_execute_owned_command
let p = plugins(tmp.path());
p.set_workspace(Some(Arc::new(HostWorkspace(Arc::downgrade(&host)))));
set_editor_providers(Some(&p));
let generation = host.project("main").unwrap().lsp.injection_generation();
drop(plugins(&tmp.path().join("unrelated")));
assert_eq!(host.project("main").unwrap().lsp.injection_generation(), generation);
let path = root.join("a.txt");
std::fs::write(&path, "value\nnext\nend").unwrap();
let doc = ops::doc::open(&host, "main", path.clone()).await.unwrap();
@@ -201,6 +204,7 @@ async fn editor_ops_merge_the_fixture_format_selection_and_execute_owned_command
let visual = invoke(&peer, "plugin_language_visuals", serde_json::json!({"doc":doc.id})).await;
assert_eq!(visual["gutterActions"].as_array().unwrap().len(), 1);
set_editor_providers(Some(&p));
injected_lsp(&host, &p, &root, &peer).await;
p.set_enabled(ID, false).unwrap();
assert!(ops::lsp::plugin_formatters().is_empty());
set_editor_providers(None);
@@ -232,3 +236,131 @@ fn formatting_uses_the_command_budget_while_editor_calls_can_expire() {
assert!(p.language_signature_help(&doc, Pos::default()).is_none());
assert!(p.info_of(ID).unwrap().stats.slow_calls > 0);
}
// Same TCP fake-server pattern as plugin_refactoring; the real Wasm export supplies the range.
async fn injected_lsp(host: &Host, plugins: &PluginHost, root: &Path, remote: &ide_jsonrpc::Peer) {
use ide_jsonrpc::{Handler, Peer};
use parking_lot::Mutex;
use serde_json::{Value, json};
#[derive(Default)]
struct Fake {
docs: Mutex<std::collections::HashMap<String, String>>,
requests: Mutex<Vec<(String, Value)>>,
}
impl Handler for Fake {
fn on_notification(&self, method: &str, p: Value) {
let uri = p["textDocument"]["uri"].as_str().unwrap_or_default().to_owned();
match method {
"textDocument/didOpen" => {
self.docs.lock().insert(uri, p["textDocument"]["text"].as_str().unwrap().into());
}
"textDocument/didChange" => {
self.docs.lock().insert(uri, p["contentChanges"][0]["text"].as_str().unwrap().into());
}
"textDocument/didClose" => {
self.docs.lock().remove(&uri);
}
_ => {}
}
}
fn on_request(&self, method: &str, p: Value) -> Result<Value, (i64, String)> {
self.requests.lock().push((method.to_owned(), p.clone()));
Ok(match method {
"initialize" => {
json!({"capabilities": {"textDocumentSync": {"openClose":true,"change":1}, "completionProvider":{"resolveProvider":true}, "hoverProvider":true, "definitionProvider":true}})
}
"textDocument/completion" => json!([{"label":"embedded-server", "data":{"identity":7}}]),
"completionItem/resolve" => {
assert_eq!(p["data"], json!({"identity":7}));
json!({"label":"embedded-server", "detail":"resolved"})
}
"textDocument/hover" => {
json!({"contents":"embedded hover", "range":{"start":{"line":0,"character":0},"end":{"line":0,"character":99}}})
}
"textDocument/definition" => {
json!({"uri":p["textDocument"]["uri"], "range":{"start":{"line":0,"character":0},"end":{"line":0,"character":99}}})
}
_ => Value::Null,
})
}
}
let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
let port = listener.local_addr().unwrap().port();
let fake = Arc::new(Fake::default());
let peers = Arc::new(Mutex::new(Vec::<Peer>::new()));
let (accepted, state) = (peers.clone(), fake.clone());
let task = tokio::spawn(async move {
while let Ok((stream, _)) = listener.accept().await {
let (r, w) = stream.into_split();
accepted.lock().push(Peer::connect(r, w, state.clone()));
}
});
let cfg: ide_language::LanguageServerConfig =
toml::from_str(&format!("name='injected-sql'\ncommand='no-process-required'\nconnect='127.0.0.1:{port}'"))
.unwrap();
let project = host.project("main").unwrap();
project.lsp.set_servers_hook(Box::new(
move |language, _| if language.as_str() == "sql" { vec![cfg.clone()] } else { Vec::new() },
));
let path = root.join("injection.txt");
std::fs::write(&path, "😀[[sql]] tail").unwrap();
let doc = ops::doc::open(host, "main", path.clone()).await.unwrap();
let items = ops::lsp::lsp_completion(host, "main", RequestId(91), doc.id, Pos::new(0, 5), None).await.unwrap();
let item = items.items.into_iter().find(|i| i.label == "embedded-server").unwrap();
assert_eq!(
ops::lsp::lsp_resolve_completion(host, "main", doc.id, item).await.unwrap().detail.as_deref(),
Some("resolved")
);
let opened = fake.docs.lock().clone();
assert_eq!(opened.len(), 1);
assert_eq!(opened.values().next().unwrap(), " sql ");
let virtual_uri = opened.keys().next().unwrap().clone();
assert!(!ide_lsp::uri_to_path(&virtual_uri).unwrap().exists());
let before = fake.requests.lock().iter().filter(|(m, _)| m == "textDocument/completion").count();
ops::lsp::lsp_completion(host, "main", RequestId(92), doc.id, Pos::new(0, 2), None).await.unwrap();
assert_eq!(fake.requests.lock().iter().filter(|(m, _)| m == "textDocument/completion").count(), before);
let defs = ops::lsp::lsp_goto(host, "main", doc.id, Pos::new(0, 5), ide_lsp::types::GotoKind::Declaration).await;
// Declaration isn't advertised; definition exercises mapping without a plugin definition provider.
assert!(defs.is_err());
let defs =
ops::lsp::lsp_goto(host, "main", doc.id, Pos::new(0, 5), ide_lsp::types::GotoKind::Definition).await.unwrap();
assert_eq!(defs[0].path.0, path);
assert_eq!(defs[0].range, Range::new(Pos::new(0, 4), Pos::new(0, 7)));
let hover: Value = remote
.request(
"invoke",
json!({"window":"main","cmd":"lsp_hover","args":{"request":93,"doc":doc.id,"pos":{"line":0,"col":5}}}),
None,
)
.await
.unwrap();
assert!(hover.to_string().contains("embedded hover"), "{hover}");
ops::doc::edit(
host,
"main",
doc.id,
doc.version,
ide_core::ChangeSet { changes: vec![ide_core::TextChange { from: 4, to: 7, insert: "SQL".into() }] },
)
.unwrap();
ops::lsp::lsp_completion(host, "main", RequestId(94), doc.id, Pos::new(0, 5), None).await.unwrap();
let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
while fake.docs.lock().get(&virtual_uri).is_none_or(|s| s != " SQL ") {
assert!(tokio::time::Instant::now() < deadline);
tokio::time::sleep(Duration::from_millis(10)).await;
}
plugins.set_enabled(ID, false).unwrap();
while !fake.docs.lock().is_empty() {
assert!(tokio::time::Instant::now() < deadline);
tokio::time::sleep(Duration::from_millis(10)).await;
}
assert_eq!(project.lsp.injected_document(doc.id, Pos::new(0, 5)), doc.id);
ops::doc::close(host, "main", doc.id).unwrap();
project.lsp.shutdown_all().await;
project.lsp.set_servers_hook(Box::new(|_, _| Vec::new()));
task.abort();
let _ = task.await;
for peer in peers.lock().drain(..) {
peer.kill();
}
}
+46 -2
Переглянути файл
@@ -76,11 +76,11 @@ impl TestWorkspace {
impl PluginWorkspace for TestWorkspace {
fn run_configuration(&self, _client: &str, plugin: &str, id: &str) -> Result<ide_run::RunConfig, HostError> {
if plugin != "execution" || !matches!(id, "detected" | "dynamic") {
if !(plugin == "execution" && matches!(id, "detected" | "dynamic") || plugin == "api14" && id == "tests") {
return Err(HostError::NotFound(id.into()));
}
Ok(ide_run::RunConfig {
id: format!("plugin:execution:{id}"),
id: format!("plugin:{plugin}:{id}"),
name: "Tests".into(),
kind: "plugin".into(),
command: "execution-tool".into(),
@@ -6018,6 +6018,50 @@ fn api14_stage3_configurations_test_results_and_content_actions_use_real_exports
assert!(f.host.parse_test_results("main", "plugin:execution:dynamic", "trap".into()).unwrap().is_none());
}
#[test]
fn api14_fixture_exports_test_selection() {
let f = fixture(Limits::default());
f.install(&sample("api14"));
assert_eq!(
f.host.select_tests("main", "plugin:api14:tests", vec![vec!["Suite".into(), "Test".into()]]).unwrap(),
Some(vec!["Suite::Test".into()])
);
}
#[cfg(unix)]
#[test]
fn api14_test_selection_uses_owned_config_ids_and_name_paths() {
let f = execution_fixture();
f.host.refresh_run_configurations(&f.project);
for id in ["dynamic", "detected"] {
assert_eq!(
f.host
.select_tests(
"main",
&format!("plugin:execution:{id}"),
vec![vec!["Suite".into(), "Test".into()], vec!["Other".into()]]
)
.unwrap(),
Some(vec![id.into(), "Suite::Test".into(), "Other".into()])
);
}
assert_eq!(f.host.select_tests("main", "plugin:execution:dynamic", vec![vec!["none".into()]]).unwrap(), None);
assert_eq!(f.host.select_tests("main", "cargo:test", vec![vec!["Test".into()]]).unwrap(), None);
assert_eq!(f.host.select_tests("main", "plugin:execution:dynamic", vec![]).unwrap(), None);
}
#[cfg(unix)]
#[test]
fn api14_test_selection_traps_and_timeouts_are_unsupported() {
for failure in ["trap", "timeout"] {
let f = execution_fixture();
f.host.refresh_run_configurations(&f.project);
let started = Instant::now();
assert_eq!(f.host.select_tests("main", "plugin:execution:dynamic", vec![vec![failure.into()]]).unwrap(), None);
assert!(started.elapsed() < Duration::from_secs(5));
}
}
#[cfg(unix)]
#[test]
fn api14_stage3_terminal_calls_are_denied_without_process_grants() {
+73 -2
Переглянути файл
@@ -396,7 +396,7 @@ async fn api14_remote_calls_keep_browser_listeners_and_secrets_on_the_desktop()
plugins.register(&mut dispatcher);
let (client_io, server_io) = tokio::io::duplex(1 << 20);
let (sr, sw) = tokio::io::split(server_io);
tokio::spawn(rpc::serve(host, dispatcher, peer_slot, sr, sw));
let server = tokio::spawn(rpc::serve(host.clone(), dispatcher, peer_slot, sr, sw));
let (cr, cw) = tokio::io::split(client_io);
let client = Arc::new(Client { desktop: Some(desktop.clone()), ..Client::default() });
let peer = Peer::connect(cr, cw, client.clone());
@@ -416,6 +416,53 @@ async fn api14_remote_calls_keep_browser_listeners_and_secrets_on_the_desktop()
assert!(editors.as_str().unwrap().contains("active: true"));
let problems = invoke(&peer, "plugin_run_command", run("problems", None)).await.unwrap();
assert_eq!(problems.as_str(), Some("[]"));
let other_file = project.join("other.txt");
std::fs::write(&other_file, "other text").unwrap();
let outside_file = tmp.path().join("outside.txt");
std::fs::write(&outside_file, "outside").unwrap();
let problem = |path: &Path, message: &str| {
json!({"path": path, "items": [{
"range": {"start": {"line": 0, "col": 1}, "end": {"line": 0, "col": 3}},
"severity": "warning", "message": message, "source": "remote-check", "code": null
}]})
};
let files = json!([
problem(&remote_file, "remote warning"),
problem(&other_file, "other warning"),
problem(&outside_file, "outside warning")
]);
invoke(&peer, "mcp_report_problems", json!({"reset": true, "files": files})).await.unwrap();
let problems = invoke(&peer, "plugin_run_command", run("problems", None)).await.unwrap();
let problems = problems.as_str().unwrap();
assert!(problems.contains("remote warning"), "{problems}");
assert!(problems.contains("other warning"), "{problems}");
assert!(!problems.contains("outside warning"), "{problems}");
for path in ["remote.txt", remote_file.to_str().unwrap()] {
let problems = invoke(&peer, "plugin_run_command", run("problems", Some(path))).await.unwrap();
let problems = problems.as_str().unwrap();
assert!(problems.contains("remote warning"), "{problems}");
assert!(!problems.contains("other warning"), "{problems}");
assert!(problems.contains(remote_file.to_str().unwrap()), "{problems}");
}
assert_eq!(invoke(&peer, "plugin_run_command", run("problems", Some("missing.txt"))).await.unwrap(), json!("[]"));
invoke(&peer, "mcp_report_problems", json!({"reset": false, "files": [{"path": remote_file, "items": []}]}))
.await
.unwrap();
let problems = invoke(&peer, "plugin_run_command", run("problems", None)).await.unwrap();
assert!(!problems.as_str().unwrap().contains("remote warning"));
assert!(problems.as_str().unwrap().contains("other warning"));
invoke(
&peer,
"mcp_report_problems",
json!({"reset": true, "files": [problem(&remote_file, "replacement warning")]}),
)
.await
.unwrap();
let problems = invoke(&peer, "plugin_run_command", run("problems", None)).await.unwrap();
assert!(problems.as_str().unwrap().contains("replacement warning"));
assert!(!problems.as_str().unwrap().contains("other warning"));
invoke(&peer, "mcp_report_problems", json!({"reset": true, "files": []})).await.unwrap();
assert_eq!(invoke(&peer, "plugin_run_command", run("problems", None)).await.unwrap(), json!("[]"));
invoke(&peer, "plugin_run_command", run("open-editor", Some("remote.txt"))).await.unwrap();
invoke(&peer, "plugin_run_command", run("decorations", remote_file.to_str())).await.unwrap();
let sets = invoke(&peer, "plugin_decoration_sets", json!({})).await.unwrap();
@@ -466,9 +513,33 @@ async fn api14_remote_calls_keep_browser_listeners_and_secrets_on_the_desktop()
stream.read_to_string(&mut response).await.unwrap();
assert!(response.contains("You can close this tab"));
assert_eq!(oauth.await.unwrap().unwrap(), json!("code=desktop%2Bcode"));
invoke(&peer, "mcp_report_problems", json!({"reset": true, "files": files})).await.unwrap();
invoke(&peer, "close_project", json!({})).await.unwrap();
invoke(&peer, "open_project", json!({"path": project})).await.unwrap();
assert_eq!(invoke(&peer, "plugin_run_command", run("problems", None)).await.unwrap(), json!("[]"));
invoke(&peer, "mcp_report_problems", json!({"reset": true, "files": files})).await.unwrap();
peer.kill();
tokio::time::timeout(Duration::from_secs(5), server).await.unwrap().unwrap();
let plugin_host = plugins.host().clone();
let result = tokio::task::spawn_blocking(move || {
plugin_host
.run_command(
"api14",
"problems",
None,
ide_plugin::Invocation {
client: Some("main".into()),
workspace_root: Some(project),
..Default::default()
},
)
.unwrap()
})
.await
.unwrap();
assert_eq!(result.as_deref(), Some("[]"));
plugins.host().shutdown();
desktop.shutdown();
peer.kill();
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+31 -3
Переглянути файл
@@ -17,15 +17,30 @@ pub type Lookup<'a> = Box<dyn Fn(&Path) -> Option<Arc<DocText>> + Send + Sync +
/// Converts server positions to IDE coordinates. For UTF-16 servers this is
/// the identity; otherwise line text comes from open documents or disk.
type MapLocation<'a> = Box<dyn Fn(Location) -> Option<Location> + Send + Sync + 'a>;
type MapEdit<'a> = Box<dyn Fn(&mut WorkspaceEdit) + Send + Sync + 'a>;
pub struct Conv<'a> {
pub enc: Encoding,
map_location: Option<MapLocation<'a>>,
map_edit: Option<MapEdit<'a>>,
lookup: Lookup<'a>,
cache: Mutex<HashMap<PathBuf, Option<Arc<DocText>>>>,
}
impl<'a> Conv<'a> {
pub fn new(enc: Encoding, lookup: impl Fn(&Path) -> Option<Arc<DocText>> + Send + Sync + 'a) -> Self {
Self { enc, lookup: Box::new(lookup), cache: Mutex::new(HashMap::new()) }
Self { enc, lookup: Box::new(lookup), cache: Mutex::new(HashMap::new()), map_location: None, map_edit: None }
}
pub fn with_injections(
mut self,
location: impl Fn(Location) -> Option<Location> + Send + Sync + 'a,
edit: impl Fn(&mut WorkspaceEdit) + Send + Sync + 'a,
) -> Self {
self.map_location = Some(Box::new(location));
self.map_edit = Some(Box::new(edit));
self
}
#[cfg(test)]
@@ -62,7 +77,11 @@ impl<'a> Conv<'a> {
pub fn location(&self, loc: &lsp::Location) -> Option<Location> {
let (path, uri) = uri_target(loc.uri.as_str());
let range = self.range(&path, loc.range);
Some(Location { path: path.into(), range, uri })
let loc = Location { path: path.into(), range, uri };
match &self.map_location {
Some(map) => map(loc),
None => Some(loc),
}
}
pub fn text_edit(&self, path: &Path, e: lsp::TextEdit) -> TextEdit {
@@ -662,6 +681,9 @@ pub fn workspace_edit(conv: &Conv, e: lsp::WorkspaceEdit) -> WorkspaceEdit {
}
}
let mut edit = WorkspaceEdit { files, ..Default::default() };
if let Some(map) = &conv.map_edit {
map(&mut edit);
}
edit.deduplicate();
edit
}
@@ -829,7 +851,13 @@ pub fn workspace_symbols(conv: &Conv, r: lsp::WorkspaceSymbolResponse) -> Vec<Wo
lsp::OneOf::Left(l) => conv.location(&l)?,
lsp::OneOf::Right(w) => {
let (path, uri) = uri_target(w.uri.as_str());
Location { path: path.into(), range: Range::default(), uri }
{
let loc = Location { path: path.into(), range: Range::default(), uri };
match &conv.map_location {
Some(map) => map(loc)?,
None => loc,
}
}
}
};
Some(WorkspaceSymbol { name: s.name, kind: symbol_kind(s.kind), container: s.container_name, location })
+3
Переглянути файл
@@ -139,6 +139,9 @@ impl ClientHandler {
}
};
let Some(path) = uri_to_path(params.uri.as_str()) else { return };
if !mgr.accepts_injected_diagnostics(&path, params.version) {
return;
}
// Files opened only for a request (references search) are not the user's problems.
if (self.server.external_diagnostics.load(std::sync::atomic::Ordering::Acquire)
&& !mgr.docs.lock().values().any(|d| d.path == path))
+769
Переглянути файл
@@ -0,0 +1,769 @@
//! Masked file documents for plugin-provided embedded languages.
use crate::{
LspManager, convert,
server::Server,
text::Encoding,
types::{Command, CompletionItem},
};
use ide_core::{DocId, FileEdit, IdeError, IdeResult, LanguageId, Location, Pos, Range, WorkspaceEdit};
use parking_lot::{Mutex, RwLock};
use serde_json::{Value, json};
use std::sync::atomic::{AtomicU64, Ordering};
use std::{
collections::HashMap,
path::{Path, PathBuf},
sync::Arc,
time::Duration,
};
pub const MAX_INJECTED_DOCUMENT_BYTES: usize = 2 << 20;
const MAX_DOCUMENTS: usize = 32;
const MARKER: &str = ".openidea-injected-";
const ORIGIN: &str = "$openideaInjection";
pub(super) const COMMAND: &str = "$openideaInjectedCommand";
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct InjectedRange {
pub range: Range,
pub language: LanguageId,
}
/// Runs on a blocking worker, with the host's unsaved snapshot.
pub type InjectionProvider = dyn Fn(&Path, &LanguageId, u32, &str) -> Vec<InjectedRange> + Send + Sync;
#[derive(Clone)]
struct Document {
host: DocId,
host_path: PathBuf,
version: u32,
path: PathBuf,
injection: InjectedRange,
active: bool,
}
#[derive(Default)]
pub(super) struct State {
pub gate: Mutex<()>,
provider: RwLock<Option<Arc<InjectionProvider>>>,
documents: RwLock<HashMap<DocId, Document>>,
refreshed: Mutex<HashMap<DocId, u32>>,
refresh: tokio::sync::Mutex<()>,
generation: AtomicU64,
}
fn reserved(path: &Path) -> bool {
path.file_name().is_some_and(|s| {
let name = s.to_string_lossy();
name.rsplit_once(MARKER)
.and_then(|(_, suffix)| suffix.split_once('.'))
.is_some_and(|(id, _)| !id.is_empty() && id.bytes().all(|c| c.is_ascii_digit()))
}) && !path.exists()
}
fn contains(range: Range, pos: Pos) -> bool {
range.start <= pos && pos < range.end
}
fn clip(bounds: Range, range: Range) -> Option<Range> {
if range.start > range.end {
return None;
}
if range.is_empty() {
return contains(bounds, range.start).then_some(range);
}
let start = bounds.start.max(range.start);
let end = bounds.end.min(range.end);
(start < end).then_some(Range::new(start, end))
}
fn confined(bounds: Range, range: Range) -> bool {
range.start <= range.end && bounds.start <= range.start && range.end <= bounds.end
}
fn mask(text: &str, range: Range) -> String {
let mut at = Pos::default();
let mut out = String::with_capacity(text.len());
for c in text.chars() {
if contains(range, at) || matches!(c, '\n' | '\r') {
out.push(c);
} else {
out.extend(std::iter::repeat_n(' ', c.len_utf16()));
}
if c == '\n' {
at.line += 1;
at.col = 0;
} else if c != '\r' {
at.col += c.len_utf16() as u32;
}
}
out
}
impl LspManager {
pub fn set_injection_provider(&self, provider: Arc<InjectionProvider>) {
*self.injections.provider.write() = Some(provider);
}
pub(super) fn schedule_injections(&self, doc: DocId) {
if self.injections.provider.read().is_none() || self.is_injected_doc(doc) {
return;
}
let Some(me) = self.me.upgrade() else { return };
let Ok(snap) = self.snapshot(doc) else { return };
self.runtime.spawn(async move {
tokio::time::sleep(Duration::from_millis(300)).await;
if me.snapshot(doc).is_ok_and(|s| s.version == snap.version) {
let _ = me.refresh_injections(doc).await;
}
});
}
/// Refresh on demand as well as after edits: point requests need not wait for the debounce.
pub async fn refresh_injections(&self, doc: DocId) -> IdeResult<()> {
let _refresh = self.injections.refresh.lock().await;
let generation = self.injections.generation.load(Ordering::Acquire);
let Ok(snap) = self.snapshot(doc) else { return Ok(()) };
if self.is_injected_doc(doc) || self.injections.refreshed.lock().get(&doc) == Some(&(snap.version as u32)) {
return Ok(());
}
let provider = self.injections.provider.read().clone();
let ranges = if snap.text.as_str().len() <= MAX_INJECTED_DOCUMENT_BYTES && !uri_is_virtual(&snap.path) {
if let Some(provider) = provider {
let (path, language, text, version) = (snap.path, snap.language, snap.text, snap.version);
tokio::task::spawn_blocking(move || provider(&path, &language, version as u32, text.as_str()))
.await
.map_err(|e| IdeError::unavailable(e.to_string()))?
} else {
Vec::new()
}
} else {
Vec::new()
};
if let Some(me) = self.me.upgrade() {
tokio::task::spawn_blocking(move || me.set_injections_at(doc, snap.version as u32, ranges, generation))
.await
.map_err(|e| IdeError::unavailable(e.to_string()))?;
}
if self.injection_generation() != generation || !self.snapshot(doc).is_ok_and(|s| s.version == snap.version) {
return Err(IdeError::cancelled());
}
Ok(())
}
/// Revision of plugin providers used to reject an obsolete refresh.
pub fn injection_generation(&self) -> u64 {
self.injections.generation.load(Ordering::Acquire)
}
pub fn set_injections(&self, host: DocId, version: u32, ranges: Vec<InjectedRange>) {
self.set_injections_at(host, version, ranges, self.injection_generation());
}
pub fn set_injections_at(&self, host: DocId, version: u32, mut ranges: Vec<InjectedRange>, generation: u64) {
let _gate = self.injections.gate.lock();
if generation != self.injection_generation() {
return;
}
let Ok(snap) = self.snapshot(host) else { return };
if snap.version as u32 != version || self.is_injected_doc(host) {
return;
}
if snap.text.as_str().len() > MAX_INJECTED_DOCUMENT_BYTES {
ranges.clear();
}
ranges.sort_by_key(|r| r.range);
let mut end = Pos::default();
ranges.retain(|i| {
let r = i.range;
let valid_pos = |p: Pos| {
(p.line as usize) < snap.text.line_count()
&& snap.text.lsp_to_ide(Encoding::Utf8, snap.text.ide_to_lsp(Encoding::Utf8, p)) == p
};
if r.start >= r.end
|| r.start < end
|| !valid_pos(r.start)
|| !valid_pos(r.end)
|| i.language == snap.language
|| self.language_servers(&i.language).is_empty()
{
return false;
}
end = r.end;
true
});
ranges.truncate(MAX_DOCUMENTS);
let mut old: Vec<_> = self
.injections
.documents
.read()
.iter()
.filter(|(_, d)| d.host == host)
.map(|(id, d)| (*id, d.clone()))
.collect();
old.sort_by_key(|(_, d)| d.injection.range);
let mut retained = Vec::new();
for (slot, injection) in ranges.into_iter().enumerate() {
let existing =
old.iter().position(|(id, d)| !retained.contains(id) && d.injection == injection).or_else(|| {
old.get(slot)
.filter(|(id, d)| !retained.contains(id) && d.injection.language == injection.language)
.map(|_| slot)
});
let text = mask(snap.text.as_str(), injection.range);
if let Some(index) = existing {
let (id, mut d) = old[index].clone();
if d.injection != injection {
self.clear_injected_diagnostics(&d);
}
d.version = version;
d.injection = injection;
d.active = true;
self.injections.documents.write().insert(id, d);
self.sync_injected(id, &text);
retained.push(id);
} else {
let Some(cfg) = self.languages.get(&injection.language) else { continue };
let ext = cfg
.extensions
.iter()
.find(|s| !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric()))
.map(String::as_str)
.unwrap_or("txt");
let mut id = DocId::next();
let path = loop {
let path = snap.path.with_file_name(format!(
".{}{MARKER}{}.{}",
snap.path.file_name().unwrap_or_default().to_string_lossy(),
id.0,
ext
));
if !path.exists() {
break path;
}
id = DocId::next();
};
self.injections.documents.write().insert(
id,
Document {
host,
host_path: snap.path.clone(),
version,
path: path.clone(),
injection: injection.clone(),
active: true,
},
);
let servers = self.servers_for(&injection.language, &path);
self.attach(
id,
path.clone(),
crate::uri::path_to_uri(&path),
&injection.language,
version,
&text,
servers,
);
retained.push(id);
}
}
for (id, d) in old {
if !retained.contains(&id) {
self.injections.documents.write().remove(&id);
self.close_document(id);
self.clear_injected_diagnostics(&d);
}
}
self.injections.refreshed.lock().insert(host, version);
}
/// Plugin enable/disable/reload changes the ranges even without a buffer edit.
pub fn injection_providers_changed(&self) {
let _gate = self.injections.gate.lock();
self.injections.generation.fetch_add(1, Ordering::AcqRel);
self.injections.refreshed.lock().clear();
let hosts: Vec<_> = self.docs.lock().keys().copied().collect();
for doc in hosts {
if !self.is_injected_doc(doc) {
self.close_injections(doc);
self.schedule_injections(doc);
}
}
}
pub(super) fn map_injected_event(&self, mut event: ide_core::IdeEvent) -> Option<ide_core::IdeEvent> {
if let ide_core::IdeEvent::Diagnostics { path, .. } = &mut event
&& reserved(path)
{
let docs = self.injections.documents.read();
let d = docs.values().find(|d| d.path == path.as_ref())?;
*path = d.host_path.clone().into();
}
Some(event)
}
pub(super) fn injected_request_stamp(&self, params: &Value) -> Option<(DocId, i32)> {
let path = crate::uri::uri_to_path(params.pointer("/textDocument/uri")?.as_str()?)?;
if !reserved(&path) {
return None;
}
self.docs.lock().iter().find(|(_, d)| d.path == path).map(|(id, d)| (*id, d.version))
}
pub(super) fn check_injected_request(&self, doc: DocId, version: i32) -> IdeResult<()> {
let active = self.injections.documents.read().get(&doc).is_some_and(|d| d.active);
if !active || !self.snapshot(doc).is_ok_and(|s| s.version == version) {
return Err(IdeError::cancelled());
}
Ok(())
}
pub(super) fn accepts_injected_diagnostics(&self, path: &Path, version: Option<i32>) -> bool {
if !reserved(path) {
return true;
}
let docs = self.injections.documents.read();
docs.iter().any(|(id, d)| {
d.active && d.path == path && self.snapshot(*id).is_ok_and(|s| version.is_none_or(|v| s.version == v))
})
}
pub fn injected_document(&self, host: DocId, pos: Pos) -> DocId {
let version = self.snapshot(host).ok().map(|s| s.version as u32);
self.injections
.documents
.read()
.iter()
.find(|(_, d)| d.host == host && d.active && Some(d.version) == version && contains(d.injection.range, pos))
.map_or(host, |(id, _)| *id)
}
pub fn injected_request_range(&self, doc: DocId, range: Range) -> Range {
self.clip_injected_range(doc, range).unwrap_or(range)
}
pub(super) fn is_injected_doc(&self, doc: DocId) -> bool {
self.injections.documents.read().contains_key(&doc)
}
pub(super) fn clip_injected_range(&self, doc: DocId, range: Range) -> Option<Range> {
match self.injections.documents.read().get(&doc) {
Some(d) if d.active => clip(d.injection.range, range),
Some(_) => None,
None => Some(range),
}
}
fn sync_injected(&self, id: DocId, text: &str) {
let mut docs = self.docs.lock();
let Some(d) = docs.get_mut(&id) else { return };
if d.text.as_str() == text {
return;
}
d.version += 1;
Arc::make_mut(&mut d.text).set(text);
for a in &d.servers {
let Some(run) = a.server.running() else { continue };
if a.opened_gen != Some(run.generation) || run.caps.read().sync == crate::SyncKind::None {
continue;
}
let _ = run.peer.notify(
"textDocument/didChange",
json!({
"textDocument": { "uri": d.uri, "version": d.version }, "contentChanges": [{ "text": text }]
}),
);
}
drop(docs);
self.schedule_pull(id, None, Duration::ZERO);
}
pub(super) fn invalidate_injections(&self, host: DocId) {
self.injections.refreshed.lock().remove(&host);
let old: Vec<_> = self
.injections
.documents
.read()
.iter()
.filter(|(_, d)| d.host == host)
.map(|(id, d)| (*id, d.clone()))
.collect();
if old.is_empty() {
return;
}
for (id, d) in old {
if let Some(d) = self.injections.documents.write().get_mut(&id) {
d.active = false;
}
self.clear_injected_diagnostics(&d);
}
}
pub(super) fn close_injections(&self, host: DocId) {
self.injections.refreshed.lock().remove(&host);
let old: Vec<_> = self
.injections
.documents
.read()
.iter()
.filter(|(_, d)| d.host == host)
.map(|(id, d)| (*id, d.clone()))
.collect();
for (id, d) in old {
self.injections.documents.write().remove(&id);
self.close_document(id);
self.clear_injected_diagnostics(&d);
}
}
pub(super) fn map_injected_location(&self, mut loc: Location) -> Option<Location> {
let docs = self.injections.documents.read();
if let Some(d) = docs.values().find(|d| d.path == loc.path.as_ref()) {
if !d.active {
return None;
}
loc.range = clip(d.injection.range, loc.range)?;
loc.path = d.host_path.clone().into();
loc.uri = None;
Some(loc)
} else {
(!reserved(&loc.path)).then_some(loc)
}
}
pub(super) fn map_injected_edit(&self, edit: &mut WorkspaceEdit) {
let docs = self.injections.documents.read();
edit.files.retain_mut(|f| match f {
FileEdit::Edit { path, edits, version } => {
if let Some(d) = docs.values().find(|d| d.path == path.as_ref()) {
if !d.active {
return false;
}
// Clipping replacements changes their meaning; discard edits crossing a boundary.
edits.retain(|e| confined(d.injection.range, e.range));
*path = d.host_path.clone().into();
*version = Some(d.version as i32);
!edits.is_empty()
} else {
!reserved(path)
}
}
FileEdit::Create { path, .. } | FileEdit::Delete { path, .. } => {
!reserved(path) && !docs.values().any(|d| d.path == path.as_ref())
}
FileEdit::Rename { from, to } => {
!reserved(from)
&& !reserved(to)
&& !docs.values().any(|d| d.path == from.as_ref() || d.path == to.as_ref())
}
});
}
pub(super) fn provides_injected_command(&self, host: DocId, server: Option<ide_core::ServerId>) -> bool {
let ids: Vec<_> = self
.injections
.documents
.read()
.iter()
.filter(|(id, d)| d.host == host || **id == host)
.map(|(id, _)| *id)
.collect();
let docs = self.docs.lock();
ids.iter()
.any(|id| docs.get(id).is_some_and(|d| d.servers.iter().any(|a| server.is_none_or(|s| a.server.id == s))))
}
pub(super) fn tag_injected_command(&self, doc: DocId, server: ide_core::ServerId, command: &mut Option<Command>) {
let Some(original) = command.take() else { return };
if self.is_injected_doc(doc) {
let mut data = Some(serde_json::to_value(&original).expect("command is JSON"));
self.tag_injected_origin(doc, &mut data);
*command = Some(Command {
title: original.title,
command: COMMAND.into(),
arguments: vec![json!({ "origin": data, "server": server })],
});
} else {
*command = Some(original);
}
}
pub(super) fn injected_command(
&self,
host: DocId,
command: Command,
) -> IdeResult<(DocId, Command, Option<ide_core::ServerId>)> {
if command.command != COMMAND {
return Ok((host, command, None));
}
let payload = command.arguments.first().ok_or_else(IdeError::cancelled)?;
let origin = payload.pointer("/origin/$openideaInjection").ok_or_else(IdeError::cancelled)?;
let doc =
origin["doc"].as_u64().and_then(|id| u32::try_from(id).ok()).map(DocId).ok_or_else(IdeError::cancelled)?;
// Acceptance may already have edited the host. Keep the server/document identity;
// execute refreshes its mask first, and cannot revive a disappeared injection.
if !self.injections.documents.read().get(&doc).is_some_and(|d| d.host == host || doc == host) {
return Err(IdeError::cancelled());
}
let command = serde_json::from_value(origin["data"].clone()).map_err(|_| IdeError::cancelled())?;
let server =
payload["server"].as_u64().map(|id| ide_core::ServerId(id as u32)).ok_or_else(IdeError::cancelled)?;
Ok((doc, command, Some(server)))
}
pub(super) fn tag_injected_origin(&self, doc: DocId, data: &mut Option<Value>) {
if let Some(d) = self.injections.documents.read().get(&doc) {
*data = Some(json!({ ORIGIN: { "doc": doc, "version": d.version, "data": data.take() } }));
}
}
pub(super) fn resolve_injected_origin(&self, host: DocId, data: &mut Option<Value>) -> IdeResult<DocId> {
let Some(origin) = data.as_ref().and_then(|v| v.get(ORIGIN)) else { return Ok(host) };
let doc = origin["doc"].as_u64().map(|id| DocId(id as u32)).ok_or_else(IdeError::cancelled)?;
let docs = self.injections.documents.read();
let d = docs
.get(&doc)
.filter(|d| {
(d.host == host || doc == host) && d.active && origin["version"].as_u64() == Some(d.version.into())
})
.ok_or_else(IdeError::cancelled)?;
if self.snapshot(d.host)?.version as u32 != d.version {
return Err(IdeError::cancelled());
}
*data = origin.get("data").filter(|v| !v.is_null()).cloned();
Ok(doc)
}
pub(super) fn bound_completion(&self, doc: DocId, item: &mut CompletionItem) -> bool {
let docs = self.injections.documents.read();
let Some(d) = docs.get(&doc) else { return !self.snapshot(doc).is_ok_and(|s| reserved(&s.path)) };
if !d.active {
return false;
}
for r in [&mut item.replace_range, &mut item.replace_range_tab].into_iter().flatten() {
let Some(clipped) = clip(d.injection.range, *r) else { return false };
*r = clipped;
}
item.additional_edits.retain(|e| confined(d.injection.range, e.range));
drop(docs);
self.tag_injected_command(doc, item.server, &mut item.command);
self.tag_injected_origin(doc, &mut item.data);
true
}
fn clear_injected_diagnostics(&self, d: &Document) {
let servers = self.servers.lock().clone();
for server in servers {
server.set_diagnostics(d.path.clone(), Vec::new());
server.clear_pulled(&d.path);
let items = server.diagnostics_for(&d.host_path);
let enc = server.running().map(|r| r.caps.read().encoding).unwrap_or_default();
self.emit_diagnostics(&server, d.host_path.clone(), items, enc);
}
}
/// One event per host/source includes every fragment and the server's native host diagnostics.
pub(super) fn injected_diagnostics(
&self,
server: &Server,
path: &Path,
enc: Encoding,
native: Vec<lsp_types::Diagnostic>,
) -> Option<(PathBuf, Vec<ide_core::Diagnostic>)> {
let docs: Vec<_> = self.injections.documents.read().values().cloned().collect();
let host_path = if let Some(d) = docs.iter().find(|d| d.path == path) {
d.host_path.clone()
} else if reserved(path) {
return None;
} else {
path.to_owned()
};
let conv = self.conv(enc);
let native = if path == host_path { native } else { server.diagnostics_for(&host_path) };
let mut items: Vec<_> =
native.into_iter().map(|d| convert::diagnostic(&conv, &host_path, d, &server.name)).collect();
for d in docs.iter().filter(|d| d.active && d.host_path == host_path) {
items.extend(server.diagnostics_for(&d.path).into_iter().filter_map(|diag| {
let mut diag = convert::diagnostic(&conv, &d.path, diag, &server.name);
if !confined(d.injection.range, diag.range)
|| (diag.range.is_empty() && !contains(d.injection.range, diag.range.start))
{
return None;
}
diag.source = Some(server.name.clone());
Some(diag)
}));
}
(!reserved(&host_path)).then_some((host_path, items))
}
}
fn uri_is_virtual(path: &Path) -> bool {
ide_core::is_virtual_uri(&path.to_string_lossy())
}
#[cfg(test)]
mod tests {
use super::*;
struct Missing;
impl crate::Launcher for Missing {
fn launch(
&self,
_: &ide_language::LanguageServerConfig,
_: &Path,
_: Arc<dyn ide_jsonrpc::Handler>,
_: Box<dyn Fn(String) + Send + Sync>,
) -> Result<ide_jsonrpc::Peer, crate::LaunchError> {
Err(crate::LaunchError::Missing)
}
}
fn manager() -> (Arc<LspManager>, tempfile::TempDir, Arc<Mutex<Vec<ide_core::IdeEvent>>>) {
let root = tempfile::tempdir().unwrap();
let events = Arc::new(Mutex::new(Vec::new()));
let output = events.clone();
let mgr = LspManager::with_launcher(
root.path().to_path_buf(),
Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
Arc::new(move |e| output.lock().push(e)),
Arc::new(Missing),
);
(mgr, root, events)
}
fn injection(a: u32, b: u32) -> InjectedRange {
InjectedRange { range: Range::new(Pos::new(0, a), Pos::new(0, b)), language: LanguageId::new("sql") }
}
#[test]
fn routing_mapping_edits_and_limits() {
let (mgr, root, _) = manager();
let host = DocId::next();
let path = root.path().join("a.java");
mgr.did_open(host, &path, &LanguageId::plain_text(), 1, "😀 select tail");
mgr.set_injections(host, 1, vec![injection(3, 9)]);
let embedded = mgr.injected_document(host, Pos::new(0, 3));
assert_ne!(host, embedded);
assert_eq!(mgr.injected_document(host, Pos::new(0, 2)), host);
assert_eq!(mgr.injected_document(host, Pos::new(0, 9)), host);
let virtual_path = mgr.snapshot(embedded).unwrap().path;
assert_eq!(virtual_path.parent(), path.parent());
assert_eq!(virtual_path.extension().unwrap(), "sql");
assert!(!virtual_path.exists());
let loc = Location::file(virtual_path.clone(), Range::new(Pos::default(), Pos::new(0, 99)));
let mapped = mgr.map_injected_location(loc).unwrap();
assert_eq!(mapped.path.0, path);
assert_eq!(mapped.range, injection(3, 9).range);
let outside = Location::file(virtual_path.clone(), Range::new(Pos::default(), Pos::new(0, 2)));
assert!(mgr.map_injected_location(outside).is_none());
let real = root.path().join(".real.openidea-injected-123.sql");
std::fs::write(&real, "real file").unwrap();
let other = Location::file(real, Range::default());
assert_eq!(mgr.map_injected_location(other.clone()), Some(other));
let mut edit = WorkspaceEdit {
files: vec![
FileEdit::Edit {
path: virtual_path.clone().into(),
edits: vec![
ide_core::TextEdit { range: injection(3, 9).range, new_text: "SELECT".into() },
ide_core::TextEdit { range: injection(0, 9).range, new_text: "bad".into() },
],
version: Some(999),
},
FileEdit::Create { path: virtual_path.clone().into(), overwrite: true },
FileEdit::Rename { from: path.clone().into(), to: virtual_path.clone().into() },
FileEdit::Delete { path: virtual_path.clone().into(), recursive: false },
],
..Default::default()
};
mgr.map_injected_edit(&mut edit);
assert_eq!(edit.files.len(), 1);
assert!(
matches!(&edit.files[0], FileEdit::Edit { path: p, edits, version: Some(1) } if p.0 == path && edits.len() == 1)
);
mgr.set_injections(host, 0, vec![]);
assert_ne!(mgr.injected_document(host, Pos::new(0, 5)), host, "stale refresh ignored");
mgr.set_injections(host, 1, vec![]);
assert_eq!(mgr.injected_document(host, Pos::new(0, 5)), host);
assert!(mgr.map_injected_location(Location::file(virtual_path, injection(3, 9).range)).is_none());
mgr.did_open(host, &path, &LanguageId::plain_text(), 2, &"a ".repeat(40));
mgr.set_injections(host, 2, (0..40).map(|n| injection(n * 2, n * 2 + 1)).collect());
assert_eq!(mgr.injections.documents.read().len(), 32);
mgr.did_close(host);
assert!(mgr.injections.documents.read().is_empty());
mgr.did_open(host, &path, &LanguageId::plain_text(), 3, &"a".repeat(MAX_INJECTED_DOCUMENT_BYTES + 1));
mgr.set_injections(host, 3, vec![injection(0, 1)]);
assert!(mgr.injections.documents.read().is_empty());
}
#[test]
fn diagnostics_merge_fragments_native_source_and_clear() {
let (mgr, root, events) = manager();
let host = DocId::next();
let path = root.path().join("a.java");
mgr.did_open(host, &path, &LanguageId::plain_text(), 1, "xxsqlxxsql");
mgr.set_injections(host, 1, vec![injection(2, 5), injection(7, 10)]);
let a = mgr.snapshot(mgr.injected_document(host, Pos::new(0, 2))).unwrap();
let b = mgr.snapshot(mgr.injected_document(host, Pos::new(0, 7))).unwrap();
let server = a.servers[0].clone();
let diag = |start, end, message: &str| lsp_types::Diagnostic {
range: lsp_types::Range::new(lsp_types::Position::new(0, start), lsp_types::Position::new(0, end)),
message: message.into(),
source: Some("untrusted-source".into()),
..Default::default()
};
server.set_diagnostics(path.clone(), vec![diag(0, 1, "native")]);
server.set_diagnostics(a.path.clone(), vec![diag(2, 5, "a"), diag(0, 1, "outside"), diag(4, 6, "crosses")]);
let items = server.set_diagnostics(b.path.clone(), vec![diag(7, 10, "b")]);
mgr.emit_diagnostics(&server, b.path, items, Encoding::Utf16);
let latest = || {
events
.lock()
.iter()
.rev()
.find_map(|e| match e {
ide_core::IdeEvent::Diagnostics { path: p, source, items }
if p.0 == path && source == &server.name =>
{
Some(items.clone())
}
_ => None,
})
.unwrap()
};
assert_eq!(latest().iter().map(|d| d.message.as_str()).collect::<Vec<_>>().len(), 3);
assert!(
latest()
.iter()
.filter(|d| d.message != "native")
.all(|d| d.source.as_deref() == Some(server.name.as_str()))
);
mgr.set_injections(host, 1, vec![injection(7, 10)]);
assert_eq!(latest().iter().map(|d| d.message.clone()).collect::<Vec<_>>(), ["native", "b"]);
mgr.set_injections(host, 1, vec![]);
assert_eq!(latest()[0].message, "native");
assert_eq!(latest().len(), 1);
assert!(
events.lock().iter().all(|e| !matches!(e, ide_core::IdeEvent::Diagnostics { path, .. } if reserved(path)))
);
}
#[test]
fn masking_preserves_utf16_crlf_and_line_edges() {
let text = "😀éSELECT\r\n中sql\r\nend";
let range = Range::new(Pos::new(0, 3), Pos::new(1, 4));
assert_eq!(mask(text, range), " SELECT\r\n中sql\r\n ");
assert_eq!(mask(text, range).encode_utf16().count(), text.encode_utf16().count());
assert_eq!(mask("a\nsql\nz", Range::new(Pos::new(1, 0), Pos::new(2, 0))), " \nsql\n ");
assert_eq!(mask("sql", Range::new(Pos::new(0, 0), Pos::new(0, 3))), "sql");
}
#[test]
fn boundaries_are_half_open_and_results_clip() {
let r = Range::new(Pos::new(1, 3), Pos::new(2, 5));
assert!(contains(r, r.start));
assert!(!contains(r, r.end));
assert!(!contains(r, Pos::new(1, 2)));
assert_eq!(clip(r, Range::new(Pos::new(0, 0), Pos::new(3, 0))), Some(r));
assert_eq!(clip(r, Range::point(r.end)), None);
assert_eq!(clip(r, Range::new(Pos::new(0, 0), r.start)), None);
}
}
+131 -37
Переглянути файл
@@ -15,6 +15,7 @@ mod file_ops;
mod file_watch;
mod go_scope;
mod handler;
mod injections;
mod inspect;
pub mod jdtls;
mod launch;
@@ -31,6 +32,7 @@ pub mod types;
mod uri;
mod virtual_doc;
pub use injections::{InjectedRange, InjectionProvider, MAX_INJECTED_DOCUMENT_BYTES};
pub use inspect::{FileInspection, InspectHost, InspectOptions};
pub use launch::{LaunchError, Launcher, ProcessLauncher};
pub use scope::{CandidateFiles, CandidateFn, CandidateQuery, MAX_CANDIDATES};
@@ -196,6 +198,7 @@ pub struct LspManager {
virtual_origins: Mutex<HashMap<String, ide_core::ServerId>>,
/// Contents fetched for virtual URIs.
virtual_docs: Mutex<HashMap<String, VirtualDocument>>,
injections: injections::State,
}
/// Fetched virtual documents kept before the cache is reset.
@@ -361,12 +364,23 @@ impl LspManager {
sink: SharedSink,
launcher: Arc<dyn Launcher>,
) -> Arc<Self> {
Arc::new_cyclic(|me| Self {
Arc::<Self>::new_cyclic(|me| Self {
me: me.clone(),
project_root,
content_roots: RwLock::new(Vec::new()),
languages,
sink,
sink: {
let me = me.clone();
Arc::new(move |event| {
if let Some(mgr) = me.upgrade() {
if let Some(event) = mgr.map_injected_event(event) {
sink.emit(event);
}
} else {
sink.emit(event);
}
})
},
launcher,
runtime: runtime_handle(),
servers: Mutex::new(Vec::new()),
@@ -386,6 +400,7 @@ impl LspManager {
shown_messages: Mutex::new(HashSet::new()),
virtual_origins: Mutex::new(HashMap::new()),
virtual_docs: Mutex::new(HashMap::new()),
injections: injections::State::default(),
})
}
@@ -812,22 +827,27 @@ impl LspManager {
pub(crate) fn conv(&self, enc: Encoding) -> Conv<'_> {
Conv::new(enc, move |p: &Path| self.text_for_path(p))
.with_injections(move |loc| self.map_injected_location(loc), move |edit| self.map_injected_edit(edit))
}
// ---- document sync (driven by ide-workspace's DocumentObserver) ----
pub fn did_open(&self, doc: DocId, path: &Path, language: &LanguageId, version: u32, text: &str) {
let _gate = self.injections.gate.lock();
if self.docs.lock().contains_key(&doc) {
self.did_close(doc);
self.close_injections(doc);
self.close_document(doc);
}
let servers = self.servers_for(language, path);
self.attach(doc, path.to_owned(), uri::path_to_uri(path), language, version, text, servers);
self.schedule_injections(doc);
}
/// Opens a read-only virtual document (`jdt://…`) on the server that
/// returned its URI (`didOpen` only: it is never changed or saved).
pub fn did_open_virtual(&self, doc: DocId, uri: &str, language: &LanguageId, version: u32, text: &str) {
if self.docs.lock().contains_key(&doc) {
self.did_close(doc);
self.close_injections(doc);
self.close_document(doc);
}
let Ok(lsp_uri) = uri.parse::<lsp::Uri>() else {
tracing::debug!("not a valid URI: {uri}");
@@ -887,6 +907,7 @@ impl LspManager {
}
pub fn did_change(&self, doc: DocId, version: u32, changes: &[AppliedChange], full_text: &dyn Fn() -> String) {
let _gate = self.injections.gate.lock();
let mut docs = self.docs.lock();
let Some(d) = docs.get_mut(&doc) else { return };
d.version = version as i32;
@@ -929,9 +950,6 @@ impl LspManager {
tracing::warn!("lsp text copy of {} out of sync; resending full text", d.path.display());
text.set(&full_text());
}
if targets.is_empty() {
return;
}
let full = json!([{ "text": text.as_str() }]);
for (server, run, sync, enc) in targets {
let key = match enc {
@@ -954,6 +972,8 @@ impl LspManager {
}
drop(docs);
self.schedule_pull(doc, None, pull::AFTER_EDIT);
self.invalidate_injections(doc);
self.schedule_injections(doc);
}
/// Sends the documents open on instance `generation` of `server` again, as a `didChange`
@@ -1004,6 +1024,12 @@ impl LspManager {
}
pub fn did_close(&self, doc: DocId) {
let _gate = self.injections.gate.lock();
self.close_injections(doc);
self.close_document(doc);
}
fn close_document(&self, doc: DocId) {
let Some(d) = self.docs.lock().remove(&doc) else { return };
for a in &d.servers {
self.forget_pulled(&a.server, &d.path, a.server.running().as_ref());
@@ -1067,19 +1093,25 @@ impl LspManager {
cancel: Option<&CancellationToken>,
timeout: Duration,
) -> IdeResult<R> {
let params = serde_json::to_value(params).map_err(|e| IdeError::internal(e.to_string()))?;
let stamp = self.injected_request_stamp(&params);
let fut = async {
if t.server.name == "csharp-ls" {
let mut value = t.run.peer.request::<P, Value>(method, params, cancel.cloned()).await?;
let mut value = t.run.peer.request::<Value, Value>(method, params, cancel.cloned()).await?;
virtual_doc::normalize_csharp_uris(&mut value);
serde_json::from_value(value).map_err(|e| RpcError::Protocol(format!("{method}: {e}")))
} else {
t.run.peer.request::<P, R>(method, params, cancel.cloned()).await
t.run.peer.request::<Value, R>(method, params, cancel.cloned()).await
}
};
match tokio::time::timeout(timeout, fut).await {
let result = match tokio::time::timeout(timeout, fut).await {
Ok(r) => r.map_err(|e| rpc_err(&t.server.name, method, e)),
Err(_) => Err(rpc_err(&t.server.name, method, RpcError::Timeout)),
};
if let Some((doc, version)) = stamp {
self.check_injected_request(doc, version)?;
}
result
}
// ---- features ----
@@ -1114,8 +1146,10 @@ impl LspManager {
let conv = self.conv(t.enc());
let list = out.value.get_or_insert(CompletionList { is_incomplete: false, items: Vec::new() });
list.is_incomplete |= incomplete;
list.items
.extend(items.into_iter().map(|i| convert::completion_item(&conv, &snap.path, i, t.server.id)));
list.items.extend(items.into_iter().filter_map(|i| {
let mut item = convert::completion_item(&conv, &snap.path, i, t.server.id);
self.bound_completion(doc, &mut item).then_some(item)
}));
}
Err(e) => out.fail(e),
}
@@ -1157,21 +1191,33 @@ impl LspManager {
out.finish(Vec::new())
}
pub async fn resolve_completion(&self, doc: DocId, item: CompletionItem) -> IdeResult<CompletionItem> {
pub async fn resolve_completion(&self, doc: DocId, mut item: CompletionItem) -> IdeResult<CompletionItem> {
let original = item.clone();
let host_doc = doc;
let doc = self.resolve_injected_origin(doc, &mut item.data)?;
let snap = self.snapshot(doc)?;
let Some(server) = snap.servers.iter().find(|s| s.id == item.server) else { return Ok(item) };
let Some(server) = snap.servers.iter().find(|s| s.id == item.server) else { return Ok(original) };
let Some(t) = self
.ready_targets(std::slice::from_ref(server), |c| c.has_sub("completionProvider", "resolveProvider"))
.await
.pop()
else {
return Ok(item);
return Ok(original);
};
if let Some(command) = item.command.take() {
item.command = Some(self.injected_command(doc, command)?.1);
}
let lsp_item = convert::lsp_completion_item(&snap.text, t.enc(), &item);
let resolved: lsp::CompletionItem =
self.call(&t, "completionItem/resolve", lsp_item, None, DEFAULT_TIMEOUT).await?;
if doc != host_doc {
self.check_injected_request(doc, snap.version)?;
}
let mut out = item;
convert::overlay_completion(&self.conv(t.enc()), &snap.path, &mut out, resolved, false);
if !self.bound_completion(doc, &mut out) {
return Err(IdeError::cancelled());
}
Ok(out)
}
@@ -1188,7 +1234,11 @@ impl LspManager {
// Still loading: no documentation yet, not an error.
Err(e) if e.kind == ErrorKind::TimedOut && t.server.is_loading() => out.value = Some(None),
Ok(Some(h)) => {
if let Some(h) = convert::hover(&self.conv(t.enc()), &snap.path, h) {
if let Some(mut h) = convert::hover(&self.conv(t.enc()), &snap.path, h) {
if let Some(range) = h.range {
let Some(range) = self.clip_injected_range(doc, range) else { continue };
h.range = Some(range);
}
return Ok(Some(h));
}
out.value = Some(None);
@@ -1697,7 +1747,14 @@ impl LspManager {
match r {
Ok(Some(hs)) if !hs.is_empty() => {
let conv = self.conv(t.enc());
return Ok(hs.into_iter().map(|h| convert::highlight(&conv, &snap.path, h)).collect());
return Ok(hs
.into_iter()
.filter_map(|h| {
let mut h = convert::highlight(&conv, &snap.path, h);
h.range = self.clip_injected_range(doc, h.range)?;
Some(h)
})
.collect());
}
Ok(_) => out.value = Some(Vec::new()),
Err(e) => out.fail(e),
@@ -1848,7 +1905,12 @@ impl LspManager {
actions
.unwrap_or_default()
.into_iter()
.map(|a| convert::code_action(&conv, a, t.server.id))
.map(|a| {
let mut action = convert::code_action(&conv, a, t.server.id);
self.tag_injected_origin(doc, &mut action.data);
self.tag_injected_command(doc, action.server, &mut action.command);
action
})
// Servers may ignore `only`, and the kinds kept for this one.
.filter(|a| caps.restriction.keeps_action(a.kind.as_deref())),
);
@@ -1859,7 +1921,10 @@ impl LspManager {
out.finish(Vec::new()).map(|actions| CodeActionQuery { actions, advertised_kinds })
}
pub async fn resolve_code_action(&self, doc: DocId, action: CodeAction) -> IdeResult<CodeAction> {
pub async fn resolve_code_action(&self, doc: DocId, mut action: CodeAction) -> IdeResult<CodeAction> {
let original = action.clone();
let host_doc = doc;
let doc = self.resolve_injected_origin(doc, &mut action.data)?;
let snap = self.snapshot(doc)?;
let servers: Vec<Arc<Server>> = match snap.servers.iter().find(|s| s.id == action.server) {
Some(s) => vec![s.clone()],
@@ -1867,19 +1932,33 @@ impl LspManager {
};
let Some(t) = self.ready_targets(&servers, |c| c.has_sub("codeActionProvider", "resolveProvider")).await.pop()
else {
return Ok(action);
return Ok(original);
};
if let Some(command) = action.command.take() {
action.command = Some(self.injected_command(doc, command)?.1);
}
let resolved: lsp::CodeAction =
self.call(&t, "codeAction/resolve", convert::lsp_code_action(&action), None, DEFAULT_TIMEOUT).await?;
Ok(convert::merge_code_action(&self.conv(t.enc()), action, resolved))
if doc != host_doc {
self.check_injected_request(doc, snap.version)?;
}
let mut action = convert::merge_code_action(&self.conv(t.enc()), action, resolved);
self.tag_injected_origin(doc, &mut action.data);
self.tag_injected_command(doc, action.server, &mut action.command);
Ok(action)
}
pub async fn execute_command(&self, doc: DocId, command: Command) -> IdeResult<()> {
if command.command == injections::COMMAND {
self.refresh_injections(doc).await?;
}
let (doc, command, server) = self.injected_command(doc, command)?;
let servers = match self.snapshot(doc) {
Ok(snap) => snap.servers,
Err(_) => self.servers.lock().clone(),
};
let name = command.command.clone();
let servers: Vec<_> = servers.into_iter().filter(|s| server.is_none_or(|id| s.id == id)).collect();
let targets = self.ready_targets(&servers, |c| c.commands().contains(&name)).await;
let t = targets
.first()
@@ -1893,6 +1972,9 @@ impl LspManager {
/// can carry commands other editors' extensions run themselves after the edit (vtsls'
/// `_typescript.didOrganizeImports`): no server provides those.
pub async fn provides_command(&self, doc: DocId, server: Option<ide_core::ServerId>, name: &str) -> bool {
if name == injections::COMMAND {
return self.provides_injected_command(doc, server);
}
let servers = match self.snapshot(doc) {
Ok(snap) => snap.servers,
Err(_) => self.servers.lock().clone(),
@@ -1921,6 +2003,10 @@ impl LspManager {
answers: Vec<FormAnswer>,
cancel: CancellationToken,
) -> IdeResult<Option<CommandForm>> {
let (doc, command, pinned) = self.injected_command(doc, command)?;
if pinned.is_some_and(|id| id != server) {
return Err(IdeError::cancelled());
}
// Nothing to ask for a command its server doesn't provide (executing it decides).
if !self.provides_command(doc, Some(server), &command.command).await {
return Ok(None);
@@ -1944,17 +2030,19 @@ impl LspManager {
return Err(IdeError::unavailable("unsupported command input type"));
}
}
let mut command = Some(Command {
title: command.title,
command: response
.get("command")
.and_then(Value::as_str)
.ok_or_else(|| IdeError::internal("command form omitted command"))?
.to_owned(),
arguments: serde_json::from_value(response.get("arguments").cloned().unwrap_or(json!([])))
.map_err(parse_error)?,
});
self.tag_injected_command(doc, server, &mut command);
Ok(Some(CommandForm {
command: Command {
title: command.title,
command: response
.get("command")
.and_then(Value::as_str)
.ok_or_else(|| IdeError::internal("command form omitted command"))?
.to_owned(),
arguments: serde_json::from_value(response.get("arguments").cloned().unwrap_or(json!([])))
.map_err(parse_error)?,
},
command: command.expect("resolved command"),
form_fields: serde_json::from_value(fields).map_err(parse_error)?,
form_answers: serde_json::from_value(
response.get("formAnswers").filter(|v| !v.is_null()).cloned().unwrap_or(json!([])),
@@ -1972,6 +2060,13 @@ impl LspManager {
answers: Vec<FormAnswer>,
cancel: CancellationToken,
) -> IdeResult<Vec<PathBuf>> {
if command.command == injections::COMMAND {
self.refresh_injections(doc).await?;
}
let (doc, command, pinned) = self.injected_command(doc, command)?;
if pinned.is_some_and(|id| id != server) {
return Err(IdeError::cancelled());
}
let t = self.command_target(doc, server, &command.command).await?;
let open_created = t.server.name == "gopls" && command.command == "gopls.add_test";
let mut edits = self.applied_edits.subscribe();
@@ -2877,6 +2972,9 @@ impl LspManager {
self.ensure_started(server);
}
}
if allowed != previous {
self.injection_providers_changed();
}
}
/// [`Self::reconfigure`] on the manager's runtime, for callers outside one (file watchers).
@@ -2945,6 +3043,7 @@ impl LspManager {
}
self.attach_fallbacks();
self.detach_shadowed_fallbacks().await;
self.injection_providers_changed();
}
/// A server enabled again shadows the fallbacks attached in its place: they
@@ -3053,13 +3152,8 @@ impl LspManager {
let servers: Vec<Arc<Server>> = self.servers.lock().clone();
for server in servers {
let encoding = server.running().map(|r| r.caps.read().encoding).unwrap_or_default();
let conv = self.conv(encoding);
for (path, items) in server.diagnostics_by_path() {
let items = items.into_iter().map(|d| convert::diagnostic(&conv, &path, d, &server.name)).collect();
server.emit(
&self.sink,
ide_core::IdeEvent::Diagnostics { path: path.into(), source: server.name.clone(), items },
);
self.emit_diagnostics(&server, path, items, encoding);
}
}
}
+4 -4
Переглянути файл
@@ -5,7 +5,7 @@
//! and shown together.
use crate::server::{Running, Server};
use crate::{LspManager, convert, virtual_doc};
use crate::{LspManager, virtual_doc};
use ide_core::{DocId, IdeEvent};
use ide_jsonrpc::RpcError;
use lsp_types as lsp;
@@ -189,8 +189,8 @@ impl LspManager {
items: Vec<lsp::Diagnostic>,
enc: crate::text::Encoding,
) {
let conv = self.conv(enc);
let items = items.into_iter().map(|d| convert::diagnostic(&conv, &path, d, &server.name)).collect();
server.emit(&self.sink, IdeEvent::Diagnostics { path: path.into(), source: server.name.clone(), items });
if let Some((path, items)) = self.injected_diagnostics(server, &path, enc, items) {
server.emit(&self.sink, IdeEvent::Diagnostics { path: path.into(), source: server.name.clone(), items });
}
}
}
-1
Переглянути файл
@@ -50,7 +50,6 @@ impl DocText {
&self.text
}
#[cfg(test)]
pub fn line_count(&self) -> usize {
self.lines.len()
}
+189
Переглянути файл
@@ -5117,3 +5117,192 @@ async fn hierarchy_refactorings_name_the_servers_without_them() {
assert_eq!(e.kind, ide_core::error::ErrorKind::Unavailable);
assert_eq!(e.message, "plain doesn't support Pull Members Up");
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn injected_documents_route_and_resolve_without_exposing_virtual_files() {
for encoding in ["utf-16", "utf-8"] {
let mut caps = incremental_caps();
caps["positionEncoding"] = json!(encoding);
caps["signatureHelpProvider"] = json!({});
for cap in
["declarationProvider", "typeDefinitionProvider", "implementationProvider", "documentHighlightProvider"]
{
caps[cap] = json!(true);
}
let mut h = harness_for("sql", "sql", &[("embedded", caps)], &[]);
let builtins = LanguageRegistry::load(None).unwrap();
let mut sql = builtins.get(&LanguageId::new("sql")).unwrap();
sql.language_servers = vec![server_cfg("embedded")];
let mut native = builtins.get(&LanguageId::plain_text()).unwrap();
native.language_servers = vec![server_cfg("host")];
*h.launcher.state("host").caps.lock() = incremental_caps();
h.launcher.state("host").respond("textDocument/completion", json!([{"label":"native"}]));
let events = h.events.clone();
h.mgr = LspManager::with_launcher(
h.root.clone(),
Arc::new(LanguageRegistry::from_configs(vec![sql, native])),
Arc::new(move |e| events.lock().push(e)),
h.launcher.clone(),
);
let state = h.launcher.state("embedded");
*state.responder.lock() = Some(Arc::new(|_, method, p| {
let whole = json!({"start":{"line":0,"character":0},"end":{"line":0,"character":99}});
let uri = p["textDocument"]["uri"].clone();
Some(match method {
"textDocument/completion" => {
json!([{"label":"one","textEdit":{"range":whole,"newText":"ONE"},"data":{"id":7},"command":{"title":"run","command":"mock.run"}}])
}
"completionItem/resolve" => {
assert_eq!(p["data"], json!({"id":7}));
assert_eq!(p["command"]["command"], "mock.run");
json!({"label":"one","detail":"resolved"})
}
"textDocument/hover" => json!({"contents":"SQL","range":whole}),
"textDocument/signatureHelp" => json!({"signatures":[{"label":"sql()"}]}),
"textDocument/definition"
| "textDocument/declaration"
| "textDocument/typeDefinition"
| "textDocument/implementation" => json!([
{"uri":uri,"range":whole},
{"uri":uri,"range":{"start":{"line":0,"character":0},"end":{"line":0,"character":1}}}
]),
"textDocument/references" => json!([{"uri":uri,"range":whole}]),
"textDocument/documentHighlight" => json!([{"range":whole}]),
"textDocument/codeAction" => json!([{"title":"fix","data":{"uri":uri}}]),
"codeAction/resolve" => json!({"title":"fix","edit":{"documentChanges":[
{"textDocument":{"uri":p["data"]["uri"],"version":1},"edits":[{"range":{"start":{"line":0,"character":4},"end":{"line":0,"character":7}},"newText":"ONE"}]},
{"kind":"create","uri":p["data"]["uri"]}
]},"command":{"title":"run","command":"mock.run"}}),
_ => Value::Null,
})
}));
h.mgr.set_injection_provider(Arc::new(|_, _, _, text| {
text.match_indices("[[")
.filter_map(|(start, _)| {
let end = start + 2 + text[start + 2..].find("]]")?;
Some(ide_lsp::InjectedRange {
range: Range::new(
Pos::new(0, text[..start + 2].encode_utf16().count() as u32),
Pos::new(0, text[..end].encode_utf16().count() as u32),
),
language: LanguageId::new("sql"),
})
})
.collect()
}));
let host = DocId::next();
let path = h.root.join("host.java");
let source = "😀[[one]] [[two]]";
h.mgr.did_open(host, &path, &LanguageId::plain_text(), 1, source);
h.mgr.refresh_injections(host).await.unwrap();
let doc = h.mgr.injected_document(host, Pos::new(0, 5));
let second = h.mgr.injected_document(host, Pos::new(0, 13));
assert_ne!(doc, host);
assert_ne!(doc, second, "separate SQL fragments must not share a document");
assert_eq!(h.mgr.injected_document(host, Pos::new(0, 7)), host);
assert_eq!(
h.mgr.completion(host, Pos::new(0, 1), None, Default::default()).await.unwrap().items[0].label,
"native"
);
let item = h.mgr.completion(doc, Pos::new(0, 5), None, Default::default()).await.unwrap().items.remove(0);
assert_eq!(item.replace_range, Some(rng(0, 4, 0, 7)));
let resolved = h.mgr.resolve_completion(host, item).await.unwrap();
assert_eq!(resolved.detail.as_deref(), Some("resolved"));
h.mgr.execute_command(host, resolved.command.clone().unwrap()).await.unwrap();
assert_eq!(state.requested("workspace/executeCommand")[0]["command"], "mock.run");
assert_eq!(
h.mgr.hover(doc, Pos::new(0, 5), Default::default()).await.unwrap().unwrap().range,
Some(rng(0, 4, 0, 7))
);
assert!(h.mgr.signature_help(doc, Pos::new(0, 5)).await.unwrap().is_some());
for kind in [GotoKind::Definition, GotoKind::Declaration, GotoKind::TypeDefinition, GotoKind::Implementation] {
let locations = h.mgr.goto(doc, Pos::new(0, 5), kind).await.unwrap();
assert_eq!(locations.len(), 1);
assert_eq!(locations[0].path.0, path);
assert_eq!(locations[0].range, rng(0, 4, 0, 7));
}
let refs = h.mgr.references(doc, Pos::new(0, 5), true, false, Default::default()).await.unwrap();
assert_eq!(refs.locations[0].path.0, path);
let highlights = h.mgr.document_highlights(doc, Pos::new(0, 5)).await.unwrap();
assert_eq!(highlights[0].range, rng(0, 4, 0, 7));
let action = h.mgr.code_actions(doc, rng(0, 5, 0, 5), vec![]).await.unwrap().remove(0);
let action = h.mgr.resolve_code_action(host, action).await.unwrap();
let edit = action.edit.unwrap();
assert_eq!(edit.files.len(), 1, "resource operations on virtual paths are dropped");
assert!(
matches!(&edit.files[0],FileEdit::Edit {path:p,edits,..} if p.0 == path && edits[0].range == rng(0,4,0,7))
);
let command = action.command.unwrap();
assert!(h.mgr.provides_command(host, Some(action.server), &command.command).await);
assert!(
h.mgr
.resolve_command(host, action.server, command.clone(), vec![], Default::default())
.await
.unwrap()
.is_none()
);
h.mgr.execute_action_command(host, action.server, command, vec![], Default::default()).await.unwrap();
eventually(|| state.docs.lock().len() == 2).await;
assert!(state.docs.lock().values().any(|t| t == " one "));
assert!(state.docs.lock().values().any(|t| t == " two "));
let virtual_uris: Vec<_> = state.docs.lock().iter().map(|(u, t)| (u.clone(), t.clone())).collect();
for (uri, text) in &virtual_uris {
let col = if text.contains("one") { 4 } else { 12 };
state.peer().notify("textDocument/publishDiagnostics", json!({"uri":uri,"version":1,"diagnostics":[
{"range":{"start":{"line":0,"character":col},"end":{"line":0,"character":col+3}},"message":"embedded"},
{"range":{"start":{"line":0,"character":0},"end":{"line":0,"character":1}},"message":"outside"}
]})).unwrap();
}
let diagnostics = || {
h.events
.lock()
.iter()
.rev()
.find_map(|e| match e {
IdeEvent::Diagnostics { path: p, source, items } if p.0 == path && source == "embedded" => {
Some(items.clone())
}
_ => None,
})
.unwrap_or_default()
};
eventually(|| diagnostics().len() == 2).await;
assert!(diagnostics().iter().all(|d| d.source.as_deref() == Some("embedded")));
h.mgr.did_change(host, 2, &[AppliedChange { range: rng(0, 4, 0, 7), text: "ONE".into() }], &|| {
"😀[[ONE]] [[two]]".into()
});
assert_eq!(h.mgr.injected_document(host, Pos::new(0, 5)), host, "stale ranges cannot route");
h.mgr.refresh_injections(host).await.unwrap();
assert_eq!(h.mgr.injected_document(host, Pos::new(0, 5)), doc);
eventually(|| state.docs.lock().values().any(|t| t == " ONE ")).await;
assert!(h.mgr.resolve_completion(host, resolved).await.is_err(), "old completions cannot resolve after edits");
h.mgr.set_injections(host, 2, vec![]);
eventually(|| diagnostics().is_empty()).await;
assert!(h.events.lock().iter().all(
|e| !matches!(e,IdeEvent::Diagnostics {path,..} if path.0.to_string_lossy().contains(".openidea-injected-"))
));
h.mgr.did_close(host);
eventually(|| state.docs.lock().is_empty()).await;
h.mgr.shutdown_all().await;
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn missing_injected_server_uses_the_normal_single_install_notification() {
let h = harness_for("sql", "sql", &[("embedded", incremental_caps())], &[]);
h.launcher.state("embedded").missing.store(true, Ordering::SeqCst);
let host = DocId::next();
let path = h.root.join("host.java");
h.mgr.did_open(host, &path, &LanguageId::plain_text(), 1, "sql");
let ranges = || vec![ide_lsp::InjectedRange { range: rng(0, 0, 0, 3), language: LanguageId::new("sql") }];
h.mgr.set_injections(host, 1, ranges());
h.wait_status("embedded", ServerStatus::Missing).await;
for version in 2..10 {
h.mgr.did_change(host, version, &[], &|| "sql".into());
h.mgr.set_injections(host, version, ranges());
}
assert_eq!(h.mgr.servers().len(), 1);
assert_eq!(h.statuses("embedded").iter().filter(|s| **s == ServerStatus::Missing).count(), 1);
h.mgr.did_close(host);
h.mgr.shutdown_all().await;
}
+16
Переглянути файл
@@ -1165,6 +1165,22 @@ impl Runtime {
})
.collect())
}
/// Selects tests under the same budget as the test parser.
pub fn select_tests(
&mut self,
config: String,
tests: Vec<Vec<String>>,
invocation: Invocation,
timeout: Duration,
) -> Result<Option<Vec<String>>, CallError> {
if self.exports.test_results.is_none() {
return Err(CallError::missing_export("test-results"));
}
self.call(invocation, timeout, |e, store| {
e.test_results.as_ref().unwrap().call_select_tests(store, &config, &tests)
})
}
/// One editor-budget batch of a plugin test parser.
pub fn parse_test_results(
&mut self,
+2
Переглянути файл
@@ -34,6 +34,8 @@ fn components() -> Vec<PathBuf> {
repo().join("crates/ide-plugin/tests/fixtures/inlay-hints/dist/plugin.wasm"),
repo().join("crates/ide-plugin/tests/fixtures/language-features/dist/plugin.wasm"),
repo().join("crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm"),
repo().join("crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm"),
repo().join("crates/ide-plugin/tests/fixtures/execution/dist/plugin.wasm"),
];
let official = repo().join("plugins/official");
let mut dirs: Vec<_> = std::fs::read_dir(&official).unwrap().map(|e| e.unwrap().path()).collect();
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
b9b06665132bd6db753aa098703f2d83c9185d756114cdd1abb986f9d6d56c06
446ff7b14c2d5b0fca8a3febe489906e9d56fc5b66878c953887e16dd54f5d5a
+9 -1
Переглянути файл
@@ -155,4 +155,12 @@ impl Plugin for Api14 {
host::storage::set("events", &serde_json::to_string(&received).unwrap()).unwrap();
}
}
register_plugin!(Api14);
impl openidea_plugin::TestResults for Api14 {
fn parse(&mut self, _config: &str, _chunk: &str) -> Vec<openidea_plugin::PluginTestEvent> {
vec![]
}
fn select_tests(&mut self, config: &str, tests: &[Vec<String>]) -> Option<Vec<String>> {
(config == "tests").then(|| tests.iter().map(|p| p.join("::")).collect())
}
}
register_plugin!(Api14, test_results);
+1 -1
Переглянути файл
@@ -1 +1 @@
e986322ee0a7e8b09096deee3335e542823ad836cecdf14a4f44e2066fadf7b5
c55acafff3dbe090aac50873d957e73add4db50b4ed3af0def7ec77c1cd1a9d5
+1 -1
Переглянути файл
@@ -1 +1 @@
cb74e35e0b0fa2bf7d46b143190d4e72d90abfa7a95962c037495b722d8c73d3
543e921a71667b481e9d7d3b6cf86bc46113ac7068a902d93063eff85c2c812d
+1 -1
Переглянути файл
@@ -1 +1 @@
7ef1de0b1eb9d70ed3f5ba1dfc8cec6ccf3445ce76ad128f10f3d2456a990c2c
fa9ccf5c4f999031e1fb94b9e42b6caddfd5e5aeb08181660f51488711326550
+1 -1
Переглянути файл
@@ -1 +1 @@
dcca07b99ce7d6691bd501d0e7c80d6f4ce0350b32a3bd7726b13f5b315c3982
69fca6e054ccf188b7cfe23081470676bfbee56f96b0247c7ff67aba93a24d39
+1 -1
Переглянути файл
@@ -1 +1 @@
6ab6593d3d7226a1a52bcdbe827697be39e9ed5117d238ba2366ad1a6911a623
cc2fdbb7953bac992375701812e8c4cf666652e027e8b6ecc68b43e0ae7d7ae1
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
a410bcd828c7b43d550c67c433343d1c8d4a5310b62578fc1d7fec542f2761eb
4e146d6caa1cc114d33ae18f396ac8da4d6391477daa32cc69e6feca087cf20a
+11
Переглянути файл
@@ -89,6 +89,17 @@ impl RunConfigurations for Execution {
}
}
impl TestResults for Execution {
fn select_tests(&mut self, config: &str, tests: &[Vec<String>]) -> Option<Vec<String>> {
match tests.first()?.first()?.as_str() {
"none" => return None,
"trap" => panic!("selection failed"),
"timeout" => loop {
std::hint::spin_loop();
},
_ => {}
}
Some(std::iter::once(config.to_owned()).chain(tests.iter().map(|p| p.join("::"))).collect())
}
fn parse(&mut self, _: &str, chunk: &str) -> Vec<PluginTestEvent> {
if chunk == "trap" {
panic!("parser failed");
+1 -1
Переглянути файл
@@ -1 +1 @@
86238b45b09b0274d59282b35295aaee650e999aa309640d9347787e7d461ec4
cfb6e388588d01fd3f772302049e673729138717ce7b761dfcecc4ee213a8d98
+1 -1
Переглянути файл
@@ -1 +1 @@
d433104828c588baf00dece077a087dc7f4cd78097952adca5b6049e366ca944
6117ebfa5220ab04f03884d589140426d2ee693a23f058e2457952f30314099d
+1 -1
Переглянути файл
@@ -1 +1 @@
4093e1d4791c3786f4b67fd4ef76928fc17048470f858824a29aafd71855c77d
e746d420d5f357e00b523e6e118d283df08e7b5f09f59b672645721a02f6ca46
+1 -1
Переглянути файл
@@ -1 +1 @@
aeb6d2f0a589731a1b7f71c9c71232b72d2535f0f555c4fbdb7101861b906d77
e127b6562e398cdb2d9d748434315ae78e61cfdfa3f1859da2e6eaeb2144030d
+1 -1
Переглянути файл
@@ -1 +1 @@
b723a8826d256fb57f04bbe8aa4b5300c9777f79d889bed2770f6f2bd7a65aa3
6459f7899464237399e33f4190a7526f05a010d6384a36f42c25195202fb6c58
+1 -1
Переглянути файл
@@ -1 +1 @@
31f6c0067f7668235ce7f28cb14f75950549c690a8f191aa63a71fe25f8397c6
15236a23798998a0e1669c0ce657effb88481ef7236f5738519601e23b07dd1f
+1 -1
Переглянути файл
@@ -1 +1 @@
f03ff9487293925027c5681800633d2e0a71ef908db9ea037dff5e4e0a48458e
8af4f2658b074aebdabefbe49d0641da767c109b107ecf182bcb8cb937092b82
+1 -1
Переглянути файл
@@ -1 +1 @@
98a083b972c0a887de07b720c606ffcf13f99d835cfa64d553a1243ffc19e4b1
57a4527c74f62fb98ba388223863d69afdfc9f75b6027af65658f5909379e3c9
+1 -1
Переглянути файл
@@ -1 +1 @@
639a25cbc3aaab3080bf2894bc4710f45a1043a8a0f0f7f8c41ac20253f8bc98
c2a29a1982c278a21a772e440662817b5f096b4740ac99539c5ab2721251acf8
+1 -1
Переглянути файл
@@ -1 +1 @@
741d2909f021ec4c2f572edba0d83bcee4843a1aae4d8a79ea0367419a667640
634b3da9468c13d5a74a90d187f6c510b28abe4684e6072db630b976f331e899
+1 -1
Переглянути файл
@@ -1 +1 @@
1da271855c8e63d9b6873521392bb2e14cb85f9de4fddcc7bce0c80916298caf
b9d5c9b532e022bd4f43ecb80539efd6cab628ecba05c1ecb79d4ba677c1c8c0
+1 -1
Переглянути файл
@@ -1 +1 @@
e14bfd9a7f61a7ff44f656a148ed133e973c66edfb0859bbff4d4cda9663eb3a
787ab4dbe4ef4ee8cd9af98079ae6332aeddacaa3f66fc1b3327f35e76f7ca01
+1 -1
Переглянути файл
@@ -1 +1 @@
1c2f975248675b935adac4ac096d23d3f45ca44a46e9e4a2ee578bb69bb35356
f0771c02543e5c96ae6a4f38402b666ef06d22abc1157dbc963c7fb2baee0221
+1 -1
Переглянути файл
@@ -1 +1 @@
2d566981f7f3aa78fbd6188e2bbdb17e33c01f6863e9b9a0b656f541371374bc
86bd9d7f47e9dd9463bcef0173cd24bac4d83e9172adef3e620acc4abc6bc620
+1 -1
Переглянути файл
@@ -1 +1 @@
69b349e65d32c5b22f7b6d312944e0e7387d1f7b8e46a1e88fcfcd87262ea407
d560db74cda33ff86e7a5329df8f6cd8675f3df0288e427325e0777778f03f44
+1 -1
Переглянути файл
@@ -1 +1 @@
e62e75f6e21f4d3c3797554581b6a78fc75a5362ce32f627c9858dd5f1d4edc5
20b3cfd84d9129dd74b56c8766766fe714df7a5e6e051dc72c379d5fdb59b127
+1 -1
Переглянути файл
@@ -1 +1 @@
c4740acdb3c805e13bf9a0c2e2c2a830336a1085285c39de3dce73a301f70150
d30ffd74e9e444f51024586f9c67cefede44ad89bd251410ea3881bd2255b1d5
+1 -1
Переглянути файл
@@ -1 +1 @@
315d592adb776916170a6c2293379e7a7a086b9ae513dcac4aefad925d91df5d
9a354ee52f1ee1080ce9c687e9fc59e137da8f38c6723316b8aeecb5bdf1e4ad
+1 -1
Переглянути файл
@@ -1 +1 @@
7a88345173c4a77f6f94a047af53a43852adcf7e0377199f670374f296b98b19
ae183781f1fc1639fa7b1b3c4b8ff100e4e25daab69bbf876584050e5363473f
+1 -1
Переглянути файл
@@ -1 +1 @@
c98b94057e62a575d6c4b6c4c92e1e88e101bcef9138683e47b0bebf262e3f63
8a8c92661df8d693d5eabc45946e2d98c9e887090e4233e65e896421c655dcdd
+101 -23
Переглянути файл
@@ -426,11 +426,16 @@ impl ProcessManager {
Ok(match child.stdin.take() {
Some(pipe) if !redirected => {
#[cfg(unix)]
{
let wait_writable = {
use std::os::fd::AsRawFd;
ide_core::input::nonblocking(pipe.as_raw_fd())?;
}
Some(input_writer(id, Box::new(pipe))?)
ide_core::input::nonblocking(pipe.as_raw_fd())?
};
Some(input_writer(
id,
Box::new(pipe),
#[cfg(unix)]
wait_writable,
)?)
}
_ => None,
})
@@ -462,10 +467,24 @@ impl ProcessManager {
let stderr = child.stderr.take();
let result = (|| -> std::io::Result<()> {
if let Some(out) = stdout {
spawn_reader(id, Stream::Stdout, out, tx.clone())?;
spawn_reader(
id,
Stream::Stdout,
out,
tx.clone(),
#[cfg(unix)]
None,
)?;
}
if let Some(err) = stderr {
spawn_reader(id, Stream::Stderr, err, tx.clone())?;
spawn_reader(
id,
Stream::Stderr,
err,
tx.clone(),
#[cfg(unix)]
None,
)?;
}
spawn_pump(rx, on_output.clone(), entry.clone(), sink, options.encoding.clone(), notice)?;
Ok(())
@@ -538,9 +557,13 @@ impl ProcessManager {
cmd.env(k, v);
}
#[cfg(unix)]
if let Some(fd) = pair.master.as_raw_fd() {
ide_core::input::nonblocking(fd)?;
}
let wait_writable = ide_core::input::nonblocking(
pair.master.as_raw_fd().ok_or_else(|| std::io::Error::other("PTY has no file descriptor"))?,
)?;
#[cfg(unix)]
let wait_readable = ide_core::input::readable(
pair.master.as_raw_fd().ok_or_else(|| std::io::Error::other("PTY has no file descriptor"))?,
)?;
let mut child = pair.slave.spawn_command(cmd).map_err(|e| {
let text = e.to_string();
if text.contains("No such file") || text.contains("not found") {
@@ -555,7 +578,13 @@ impl ProcessManager {
let writer = pair.master.take_writer().map_err(|e| IdeError::internal(format!("pty writer: {e}")))?;
let id = RunId::next();
let writer = input_writer(id, writer).inspect_err(|_| {
let writer = input_writer(
id,
writer,
#[cfg(unix)]
wait_writable,
)
.inspect_err(|_| {
let _ = child.kill();
let _ = child.wait();
})?;
@@ -577,8 +606,15 @@ impl ProcessManager {
on_output(OutputChunk::System { text: format!("{}\n", inv.display) });
let (tx, rx) = mpsc::channel();
let result = spawn_reader(id, Stream::Stdout, reader, tx.clone())
.and_then(|_| spawn_pump(rx, on_output, entry.clone(), sink, options.encoding.clone(), None));
let result = spawn_reader(
id,
Stream::Stdout,
reader,
tx.clone(),
#[cfg(unix)]
Some(Box::new(wait_readable)),
)
.and_then(|_| spawn_pump(rx, on_output, entry.clone(), sink, options.encoding.clone(), None));
if let Err(e) = result {
let _ = child.kill();
let _ = child.wait();
@@ -789,11 +825,16 @@ fn run_followup(
Ok(match child.stdin.take() {
Some(pipe) => {
#[cfg(unix)]
{
let wait_writable = {
use std::os::fd::AsRawFd;
ide_core::input::nonblocking(pipe.as_raw_fd())?;
}
Some(input_writer(entry.id, Box::new(pipe))?)
ide_core::input::nonblocking(pipe.as_raw_fd())?
};
Some(input_writer(
entry.id,
Box::new(pipe),
#[cfg(unix)]
wait_writable,
)?)
}
None => None,
})
@@ -805,10 +846,24 @@ fn run_followup(
drop(pid);
let readers = (|| {
if let Some(out) = child.stdout.take() {
spawn_reader(entry.id, Stream::Stdout, out, tx.clone())?;
spawn_reader(
entry.id,
Stream::Stdout,
out,
tx.clone(),
#[cfg(unix)]
None,
)?;
}
if let Some(err) = child.stderr.take() {
spawn_reader(entry.id, Stream::Stderr, err, tx.clone())?;
spawn_reader(
entry.id,
Stream::Stderr,
err,
tx.clone(),
#[cfg(unix)]
None,
)?;
}
Ok::<_, std::io::Error>(())
})();
@@ -982,6 +1037,7 @@ fn spawn_reader(
stream: Stream,
mut pipe: impl Read + Send + 'static,
tx: Sender<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 || {
@@ -995,7 +1051,19 @@ fn spawn_reader(
}
}
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => std::thread::sleep(BATCH_INTERVAL),
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
#[cfg(unix)]
if let Some(wait) = &mut wait_readable {
if let Err(e) = wait()
&& e.kind() != std::io::ErrorKind::Interrupted
{
tracing::warn!(%id, "run read: {e}");
break;
}
continue;
}
std::thread::sleep(BATCH_INTERVAL);
}
#[cfg(unix)]
Err(e) if e.raw_os_error() == Some(libc::EIO) => break,
Err(e) => {
@@ -1218,10 +1286,20 @@ fn signal_number(_description: &str) -> Option<i32> {
None
}
fn input_writer(id: RunId, writer: Box<dyn std::io::Write + Send>) -> std::io::Result<ide_core::input::InputWriter> {
ide_core::input::InputWriter::new(format!("openidea-run-input-{}", id.0), writer, move |e| {
tracing::warn!(%id, "run input: {e}");
})
fn input_writer(
id: RunId,
writer: Box<dyn std::io::Write + Send>,
#[cfg(unix)] wait_writable: impl FnMut() -> std::io::Result<()> + Send + 'static,
) -> std::io::Result<ide_core::input::InputWriter> {
ide_core::input::InputWriter::new(
format!("openidea-run-input-{}", id.0),
writer,
#[cfg(unix)]
wait_writable,
move |e| {
tracing::warn!(%id, "run input: {e}");
},
)
}
#[cfg(test)]
+102 -35
Переглянути файл
@@ -279,11 +279,8 @@ pub fn jdtls_runtime(jdks: &[Jdk], min_java: u32) -> Option<&Jdk> {
/// for 21, but the Eclipse platform it ships moves on (1.63 needs 25), and on
/// an older JDK the server dies resolving its bundles.
pub fn jdtls_min_java(cfg: &LanguageServerConfig) -> u32 {
let search = cfg.env.get("PATH").map(std::ffi::OsString::from).or_else(|| std::env::var_os("PATH"));
let required = search
.and_then(|s| ide_run::which::find_executable(&cfg.command, &s))
.and_then(|exe| dunce::canonicalize(exe).ok())
.and_then(|exe| Some(exe.parent()?.parent()?.to_path_buf()))
let required = crate::jdtls::script_for(cfg)
.and_then(|script| Some(script.parent()?.parent()?.to_path_buf()))
.and_then(|home| bundles_min_java(&home));
required.map_or(JDTLS_MIN_JAVA, |v| v.max(JDTLS_MIN_JAVA))
}
@@ -506,21 +503,31 @@ pub fn configure_jdtls(
}
}
let jdks = all.as_slice();
if cfg.launch_error.is_none() && !cfg.env.contains_key("JAVA_HOME") {
let runtime = match server_jdk {
Some(jdk) => server_jdk_error(jdk, min_java).map_or(Ok(jdk), Err),
None => jdtls_runtime(jdks, min_java).ok_or_else(|| missing_runtime_message(jdks, min_java)),
};
match runtime {
Ok(jdk) => {
cfg.env.insert("JAVA_HOME".to_owned(), jdk.home.to_string_lossy().into_owned());
if cfg.launch_error.is_none() {
// A `JAVA_HOME` the config inherits (e.g. the project's JDK 8 for
// compilation) must not run jdtls: a chosen `server_jdk`, else any
// usable JDK, replaces it when it probes as too old or incomplete for
// the server (issue #2227). A `JAVA_HOME` that cannot be probed is the
// user's call and is left untouched.
let env_jdk = cfg.env.get("JAVA_HOME").and_then(|home| jdk_at(Path::new(home)));
if cfg.env.contains_key("JAVA_HOME") && env_jdk.is_none() {
// Unresolvable explicit value: keep it, jdtls reports what it finds.
} else {
let existing = env_jdk.filter(|jdk| server_jdk_error(jdk, min_java).is_none());
let runtime = if let Some(jdk) = server_jdk {
server_jdk_error(jdk, min_java).map_or(Ok(jdk), Err)
} else if let Some(jdk) = existing.as_ref() {
Ok(jdk)
} else {
jdtls_runtime(jdks, min_java).ok_or_else(|| missing_runtime_message(jdks, min_java))
};
match runtime {
Ok(jdk) => {
cfg.env.insert("JAVA_HOME".to_owned(), jdk.home.to_string_lossy().into_owned());
}
Err(e) => cfg.launch_error = Some(e),
}
Err(e) => cfg.launch_error = Some(e),
}
} else if cfg.launch_error.is_none()
&& let Some(jdk) = cfg.env.get("JAVA_HOME").and_then(|home| jdk_at(Path::new(home)))
{
cfg.launch_error = server_jdk_error(&jdk, min_java);
}
let mut runtimes = runtimes(&project_jdks);
if let Some(project) = project_jdk.or_else(|| pick_jdk(&project_jdks, project_java_version(server_root))) {
@@ -715,6 +722,10 @@ mod tests {
.unwrap();
write_test_java(&home);
std::fs::write(home.join("bin").join(crate::exe("javac")), "").unwrap();
// `jdk_at` reports the canonical home; `configure_jdtls` writes it to
// JAVA_HOME, so tests compare against the same real path (macOS
// /var→/private/var, Windows 8.3 short names).
let home = dunce::canonicalize(home).unwrap();
Jdk { major, home }
}
@@ -833,7 +844,7 @@ mod tests {
"name": "JavaSE-21", "path": pick_jdk(&installed, None).unwrap().home, "default": true
}])
);
assert_eq!(cfg.env["JAVA_HOME"], fixtures.path().join("custom-server-runtime").to_string_lossy());
assert_eq!(cfg.env["JAVA_HOME"], server.home.to_string_lossy());
}
#[test]
@@ -1007,15 +1018,11 @@ mod tests {
);
let opts = serde_json::to_value(cfg.initialization_options.clone().unwrap()).unwrap();
let rt = &opts["settings"]["java"]["configuration"]["runtimes"];
assert_eq!(rt[0], json!({ "name": "JavaSE-1.8", "path": fixtures.path().join("jdk8") }));
assert_eq!(rt[1], json!({ "name": "JavaSE-21", "path": fixtures.path().join("jdk21a") }));
assert_eq!(rt[2], json!({ "name": "JavaSE-25", "path": fixtures.path().join("jdk25"), "default": true }));
assert_eq!(rt[0], json!({ "name": "JavaSE-1.8", "path": jdks[3].home }));
assert_eq!(rt[1], json!({ "name": "JavaSE-21", "path": jdks[1].home }));
assert_eq!(rt[2], json!({ "name": "JavaSE-25", "path": jdks[0].home, "default": true }));
assert_eq!(opts["bundles"], json!(["/tools/java-debug/bin/com.microsoft.java.debug.plugin.jar"]));
assert_eq!(
cfg.env["JAVA_HOME"],
fixtures.path().join("jdk25").to_string_lossy(),
"first JDK new enough to run jdtls"
);
assert_eq!(cfg.env["JAVA_HOME"], jdks[0].home.to_string_lossy(), "first JDK new enough to run jdtls");
assert_eq!(cfg.launch_error, None);
// Deterministic (reconfigure compares configs) and idempotent.
@@ -1049,8 +1056,8 @@ mod tests {
);
let opts = serde_json::to_value(cfg.initialization_options.clone().unwrap()).unwrap();
let rt = &opts["settings"]["java"]["configuration"]["runtimes"];
assert_eq!(rt[1], json!({ "name": "JavaSE-21", "path": fixtures.path().join("jdk21b"), "default": true }));
assert_eq!(cfg.env["JAVA_HOME"], fixtures.path().join("jdk21b").to_string_lossy());
assert_eq!(rt[1], json!({ "name": "JavaSE-21", "path": project.home, "default": true }));
assert_eq!(cfg.env["JAVA_HOME"], project.home.to_string_lossy());
let mut other: LanguageServerConfig = toml::from_str("name = \"pyright\"\ncommand = \"x\"").unwrap();
configure_jdtls(
@@ -1222,11 +1229,71 @@ mod tests {
assert!(err.contains("Download JDK 25"), "{err}");
// Once a JDK 25 has been downloaded, Auto runs jdtls on it.
let downloaded = [installed.as_slice(), &[test_jdk(fixtures.path(), 25, "/tools/jdks/temurin-25")]].concat();
let temurin = test_jdk(fixtures.path(), 25, "/tools/jdks/temurin-25");
let downloaded = [installed.as_slice(), std::slice::from_ref(&temurin)].concat();
let mut cfg = jdtls();
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &downloaded, None, None, 25, &[], None);
assert_eq!(cfg.launch_error, None);
assert_eq!(cfg.env["JAVA_HOME"], fixtures.path().join("tools/jdks/temurin-25").to_string_lossy());
assert_eq!(cfg.env["JAVA_HOME"], temurin.home.to_string_lossy());
}
#[test]
fn issue_2227_a_project_java_home_too_old_for_the_server_is_replaced() {
// A project's JAVA_HOME (JDK 8 for compilation) must not run jdtls when
// the chosen server_jdk — or any usable JDK — is new enough.
let fixtures = tempfile::tempdir().unwrap();
let jdtls = || -> LanguageServerConfig { toml::from_str("name = \"jdtls\"\ncommand = \"jdtls\"").unwrap() };
let project = test_jdk(fixtures.path(), 8, "/jdk8");
let server = test_jdk(fixtures.path(), 25, "/jdk25");
// The chosen server JDK overrides the project's JAVA_HOME.
let mut cfg = jdtls();
cfg.env.insert("JAVA_HOME".into(), project.home.to_string_lossy().into_owned());
configure_jdtls(
&mut cfg,
Path::new("/p"),
Path::new("/data"),
std::slice::from_ref(&project),
None,
Some(&server),
25,
&[],
None,
);
assert_eq!(cfg.launch_error, None);
assert_eq!(cfg.env["JAVA_HOME"], server.home.to_string_lossy());
// Auto picks any usable installed JDK over the stale JAVA_HOME.
let mut cfg = jdtls();
cfg.env.insert("JAVA_HOME".into(), project.home.to_string_lossy().into_owned());
let installed = [project.clone(), server.clone()];
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &installed, None, None, 25, &[], None);
assert_eq!(cfg.launch_error, None);
assert_eq!(cfg.env["JAVA_HOME"], server.home.to_string_lossy());
// A JAVA_HOME new enough for the server stays.
let mut cfg = jdtls();
cfg.env.insert("JAVA_HOME".into(), server.home.to_string_lossy().into_owned());
configure_jdtls(&mut cfg, Path::new("/p"), Path::new("/data"), &installed, None, None, 25, &[], None);
assert_eq!(cfg.launch_error, None);
assert_eq!(cfg.env["JAVA_HOME"], server.home.to_string_lossy());
// Nothing usable to replace it with: the too-old JAVA_HOME loses to the
// same missing-runtime error a missing JAVA_HOME gives.
let mut cfg = jdtls();
cfg.env.insert("JAVA_HOME".into(), project.home.to_string_lossy().into_owned());
configure_jdtls(
&mut cfg,
Path::new("/p"),
Path::new("/data"),
std::slice::from_ref(&project),
None,
None,
25,
&[],
None,
);
assert!(cfg.launch_error.unwrap().contains("JDK 25 or newer"), "auto must say what to install");
}
#[test]
@@ -1288,23 +1355,23 @@ mod tests {
let cfg = run(Some(&jdk(21, "/jdk21")), JDTLS_MIN_JAVA);
assert_eq!(
(cfg.env["JAVA_HOME"].clone(), cfg.launch_error),
(fixtures.path().join("jdk21").to_string_lossy().into_owned(), None)
(jdk(21, "/jdk21").home.to_string_lossy().into_owned(), None)
);
let opts = serde_json::to_value(cfg.initialization_options.unwrap()).unwrap();
let rt = &opts["settings"]["java"]["configuration"]["runtimes"];
assert_eq!(
rt[0],
json!({ "name": "JavaSE-17", "path": fixtures.path().join("jdk17"), "default": true }),
json!({ "name": "JavaSE-17", "path": project.home, "default": true }),
"still compiles on 17"
);
// Not set: the first installed JDK new enough, as before.
assert_eq!(run(None, JDTLS_MIN_JAVA).env["JAVA_HOME"], fixtures.path().join("jdk25").to_string_lossy());
assert_eq!(run(None, JDTLS_MIN_JAVA).env["JAVA_HOME"], jdk(25, "/jdk25").home.to_string_lossy());
// A chosen JDK outside the scanned locations.
let own = jdk(25, "/opt/own-jdk");
let cfg = run(Some(&own), 25);
assert_eq!(cfg.env["JAVA_HOME"], fixtures.path().join("opt/own-jdk").to_string_lossy());
assert_eq!(cfg.env["JAVA_HOME"], own.home.to_string_lossy());
// Too old for this jdtls: the user's choice is not overridden, it is explained.
let old = jdk(21, "/jdk21");
+24 -15
Переглянути файл
@@ -228,6 +228,29 @@ pub fn java_args(install: &JdtlsInstall, java_major: u32, script_args: &[String]
args
}
/// The release script a `jdtls` command on `PATH` resolves to: itself when it
/// already is one, or the script its Scoop shim launches. `None` for a command
/// that is neither a release script nor a jdtls Scoop shim.
///
/// Shared with [`crate::java::jdtls_min_java`], which needs the same install
/// root to read the bundles' required Java version.
pub(crate) fn script_for(cfg: &LanguageServerConfig) -> Option<PathBuf> {
if cfg.name != "jdtls" {
return None;
}
let search = cfg.env.get("PATH").map(std::ffi::OsString::from).or_else(|| std::env::var_os("PATH"));
let script = search.and_then(|s| ide_run::which::find_executable(&cfg.command, &s))?;
let resolved = dunce::canonicalize(script).ok()?;
let name = resolved.file_name().map(|n| n.to_string_lossy().to_ascii_lowercase());
match name.as_deref() {
Some(n) if SCRIPTS.contains(&n) => Some(resolved),
// A scoop shim (`shims\jdtls.exe` from PATHEXT) hides the release
// layout behind itself (issue #794); follow its `.shim` to the script.
Some("jdtls.exe") if cfg!(windows) => shim_target(&resolved),
_ => None,
}
}
/// Scoop shims either point at the release script or run Python with the
/// script in `args`. Paths may be quoted and contain spaces and backslashes.
fn shim_target(shim_exe: &Path) -> Option<PathBuf> {
@@ -263,21 +286,7 @@ pub fn launch_directly(cfg: &mut LanguageServerConfig) {
if cfg.name != "jdtls" || cfg.launch_error.is_some() {
return;
}
let search = cfg.env.get("PATH").map(std::ffi::OsString::from).or_else(|| std::env::var_os("PATH"));
let Some(script) = search.and_then(|s| ide_run::which::find_executable(&cfg.command, &s)) else { return };
let Ok(resolved) = dunce::canonicalize(&script) else { return };
let name = resolved.file_name().map(|n| n.to_string_lossy().to_ascii_lowercase());
let script = match name.as_deref() {
Some(n) if SCRIPTS.contains(&n) => resolved,
// A scoop shim (`shims\jdtls.exe` from PATHEXT) hides the release layout
// behind itself, so the launch ran the shim's own command line and the
// configured JDK never applied (issue #794).
Some("jdtls.exe") if cfg!(windows) => match shim_target(&resolved) {
Some(target) => target,
None => return,
},
_ => return,
};
let Some(script) = script_for(cfg) else { return };
let Some(install) =
jdtls_home(&script).and_then(|h| find_install(&h, std::env::consts::OS, std::env::consts::ARCH))
else {
+42 -11
Переглянути файл
@@ -163,9 +163,13 @@ impl TerminalManager {
apply_powershell_env(&shell, &mut cmd);
#[cfg(unix)]
if let Some(fd) = pair.master.as_raw_fd() {
ide_core::input::nonblocking(fd)?;
}
let wait_writable = ide_core::input::nonblocking(
pair.master.as_raw_fd().ok_or_else(|| std::io::Error::other("PTY has no file descriptor"))?,
)?;
#[cfg(unix)]
let wait_readable = ide_core::input::readable(
pair.master.as_raw_fd().ok_or_else(|| std::io::Error::other("PTY has no file descriptor"))?,
)?;
let mut child = pair
.slave
@@ -180,9 +184,15 @@ impl TerminalManager {
let id = TerminalId::next();
let info = TerminalInfo { id, title: shell_title(&shell), pid: child.process_id() };
let exited = Arc::new(AtomicBool::new(false));
let writer = ide_core::input::InputWriter::new(format!("openidea-term-write-{}", id.0), writer, move |e| {
tracing::warn!(%id, "terminal input: {e}");
})
let writer = ide_core::input::InputWriter::new(
format!("openidea-term-write-{}", id.0),
writer,
#[cfg(unix)]
wait_writable,
move |e| {
tracing::warn!(%id, "terminal input: {e}");
},
)
.inspect_err(|_| {
let _ = child.kill();
let _ = child.wait();
@@ -200,9 +210,15 @@ impl TerminalManager {
self.sessions.lock().insert(id, session);
let (tx, rx) = mpsc::channel::<Msg>();
let spawned = spawn_reader(id, reader, tx.clone())
.and_then(|_| spawn_waiter(id, child, tx))
.and_then(|_| spawn_pump(id, rx, on_output, exited, self.sessions.clone(), sink, Instant::now()));
let spawned = spawn_reader(
id,
reader,
tx.clone(),
#[cfg(unix)]
wait_readable,
)
.and_then(|_| spawn_waiter(id, child, tx))
.and_then(|_| spawn_pump(id, rx, on_output, exited, self.sessions.clone(), sink, Instant::now()));
if let Err(e) = spawned {
if let Some(s) = self.sessions.lock().remove(&id) {
let _ = s.killer.lock().kill();
@@ -407,7 +423,12 @@ fn terminate(session: &Session) {
}
}
fn spawn_reader(id: TerminalId, mut reader: Box<dyn Read + Send>, tx: mpsc::Sender<Msg>) -> std::io::Result<()> {
fn spawn_reader(
id: TerminalId,
mut reader: Box<dyn Read + Send>,
tx: mpsc::Sender<Msg>,
#[cfg(unix)] mut wait_readable: impl FnMut() -> std::io::Result<()> + Send + 'static,
) -> std::io::Result<()> {
std::thread::Builder::new().name(format!("openidea-term-read-{}", id.0)).spawn(move || {
let mut buf = vec![0u8; 16 * 1024];
loop {
@@ -419,7 +440,17 @@ fn spawn_reader(id: TerminalId, mut reader: Box<dyn Read + Send>, tx: mpsc::Send
}
}
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => std::thread::sleep(BATCH_INTERVAL),
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
#[cfg(unix)]
if let Err(e) = wait_readable()
&& e.kind() != std::io::ErrorKind::Interrupted
{
tracing::warn!(%id, "terminal read: {e}");
break;
}
#[cfg(not(unix))]
std::thread::sleep(BATCH_INTERVAL);
}
// EIO is how Linux/macOS report "slave side closed".
#[cfg(unix)]
Err(e) if e.raw_os_error() == Some(libc::EIO) => break,
Бінарний файл не відображається.

До

Ширина:  |  Висота:  |  Розмір: 377 KiB

Після

Ширина:  |  Висота:  |  Розмір: 86 KiB

+2
Переглянути файл
@@ -46,6 +46,8 @@
"@codemirror/lang-html": "^6.4.12",
"@codemirror/lang-java": "^6.0.2",
"@codemirror/lang-javascript": "^6.2.5",
"@codemirror/lang-sass": "^6.0.2",
"@codemirror/lang-vue": "^0.1.3",
"@codemirror/language": "^6.13.1",
"@codemirror/language-data": "^6.5.2",
"@codemirror/legacy-modes": "^6.5.5",
+11
Переглянути файл
@@ -72,6 +72,17 @@
"tabs.openSmallMs": 100,
"tabs.switchP95Ms": 33,
"tabs.switcherP50Ms": 33,
"agentTabs.conversationNodes": 20000,
"agentTabs.rowsAlwaysRendered": 0,
"agentTabs.switchP95Ms": 50,
"agentTabs.switchMainThreadMs": 50,
"agentTabs.switchTbtMs": 50,
"agentTabs.scrollJumps": 0,
"agentTabs.scrollFrameP95Ms": 17.5,
"agentTabs.scrollDroppedFramesPct": 2,
"agentTabs.scrollTbtMs": 50,
"popups.findActionOpenMs": 50,
"popups.findActionQueryMs": 120,
+128 -1
Переглянути файл
@@ -455,7 +455,133 @@ const tabs: Scenario = {
switches.push(await h.measure(() => tab.click(), ".cm-content", `// tab-${i}`));
}
}
return { openSmallMs, ...latencySummary(switches, "switch") };
// The Switcher (Ctrl+Tab) back and forth between the two most recent tabs.
const before = await h.counters();
const switcher: number[] = [];
for (let i = 0; i < 10; i++) {
const tag = i % 2 ? names.length - 1 : names.length - 2;
switcher.push(await h.measure(() => h.pressAction("navigate.switcher"), ".cm-content", `// tab-${tag}`));
await h.page.waitForTimeout(150);
}
const work = Harness.delta(before, await h.counters());
return {
openSmallMs,
...latencySummary(switches, "switch"),
...latencySummary(switcher, "switcher"),
switcherMainThreadMs: work.taskMs / switcher.length,
};
},
};
/**
* Two agent tasks with long conversations (150 turns, 2,100 entries) in editor tabs:
* switching between them with the Switcher (Ctrl+Tab) shows a kept-alive conversation
* again, which must not restyle its whole history; then scrolling up through one.
* Chromium anchors scrolling on its own (WebKit doesn't), so anchoring is turned off
* here: rows that take their real height only once scrolled into view would jump.
*/
const agentTabs: Scenario = {
id: "agentTabs",
title: "Switch between and scroll long agent conversations",
async run(h) {
await h.page.addStyleTag({ content: "* { overflow-anchor: none !important; }" });
await h.page.evaluate(() =>
(
window as never as { __openideaPerf: { runAction(id: string, arg?: unknown): Promise<boolean> } }
).__openideaPerf.runAction("agents.openSampleConversations", { tasks: 2, turns: 150 }),
);
const shown = (n: number) => `[data-editor-focus] span[title="Sample task ${n}"]`;
// Both conversations get their earlier entries painted in background batches, also the
// first one, hidden behind the second as soon as it opened.
await h.page.waitForFunction(
() =>
[...document.querySelectorAll("[data-message]")]
.map((m) => m.parentElement!)
.filter((stream, i, all) => all.indexOf(stream) === i && stream.textContent!.includes("Turn 0:")).length ===
2,
undefined,
{ timeout: 30_000, polling: 200 },
);
// Rows painted while hidden are laid out the first time their conversation shows.
for (const n of [1, 2]) {
await h.page.getByRole("tab", { name: `Sample task ${n}` }).click();
await h.page.locator(shown(n)).waitFor();
await h.page.waitForTimeout(300);
}
// WebKit restyles a hidden conversation in full when it is shown again (Chromium keeps its
// style): what bounds that there is the history's DOM, and rows skipping rendering off screen.
const { conversationNodes, rowsAlwaysRendered } = await h.page.evaluate((selector) => {
const conversation = document.querySelector(selector)!.closest("[data-editor-focus]")!;
const rows = [...conversation.querySelector("[data-message]")!.parentElement!.children];
return {
conversationNodes: conversation.querySelectorAll("*").length,
rowsAlwaysRendered: rows.filter((r) => getComputedStyle(r).contentVisibility !== "auto").length,
};
}, shown(2));
const t0 = await h.now();
const before = await h.counters();
const switches: number[] = [];
for (let i = 0; i < 10; i++) {
switches.push(await h.measure(() => h.pressAction("navigate.switcher"), shown(i % 2 ? 2 : 1)));
await h.page.waitForTimeout(150);
}
const work = Harness.delta(before, await h.counters());
const switchTbtMs = totalBlockingTime(await h.longTasksSince(t0));
// Scrolling up from the end, a step at a time: how far the text under the pointer moves
// beyond the scroll itself.
const scrollJumps = await h.page.evaluate(async (selector) => {
const stream = document
.querySelector(selector)!
.closest("[data-editor-focus]")!
.querySelector("[data-message]")!.parentElement!;
const frame = () => new Promise(requestAnimationFrame);
stream.scrollTop = stream.scrollHeight;
await frame();
await frame();
const top = stream.getBoundingClientRect().top;
let jumps = 0;
for (let i = 0; i < 100 && stream.scrollTop > 0; i++) {
const row = [...stream.children].find((r) => r.getBoundingClientRect().bottom > top + 200)!;
const from = row.getBoundingClientRect().top;
const scrolled = stream.scrollTop;
// A wheel step: the user scrolls, so the conversation stops following its end.
stream.dispatchEvent(new WheelEvent("wheel", { bubbles: true, deltaY: -120 }));
stream.scrollTop -= 120;
const by = scrolled - stream.scrollTop;
await frame();
await frame();
if (Math.abs(row.getBoundingClientRect().top - from - by) > 2) jumps++;
}
stream.scrollTop = stream.scrollHeight;
return jumps;
}, shown(2));
const refresh = await h.refreshMs();
const box = (await h.page.locator("[data-editor-focus]").boundingBox())!;
await h.page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
await h.page.waitForTimeout(200);
const t1 = await h.now();
await h.inPage((p) => p.startFrames());
for (let i = 0; i < 120; i++) {
await h.page.mouse.wheel(0, -120);
await h.page.waitForTimeout(16);
}
await h.page.waitForTimeout(200);
const scroll = frameSummary(await h.inPage((p) => p.stopFrames()), refresh);
return {
conversationNodes,
rowsAlwaysRendered,
...latencySummary(switches, "switch"),
switchMainThreadMs: work.taskMs / switches.length,
switchStyleLayoutMs: work.styleLayoutMs / switches.length,
switchTbtMs,
scrollJumps,
scrollFrameP95Ms: scroll.frameP95Ms,
scrollDroppedFramesPct: scroll.droppedFramesPct,
scrollTbtMs: totalBlockingTime(await h.longTasksSince(t1)),
};
},
};
@@ -606,6 +732,7 @@ export const SCENARIOS: Scenario[] = [
keyRepeat,
scroll,
tabs,
agentTabs,
popups,
toolWindows,
projectTree,
+49 -6
Переглянути файл
@@ -393,7 +393,7 @@ working. New in 1.4:
- [Language features](#additional-language-features-api-14): formatting,
signature help, highlights, links, code lenses, selection ranges, folds,
colors/presentations, symbols, implementation, type definition and gutter
actions; [injections](#embedded-languages-api-14) route plugin providers to
actions; [injections](#embedded-languages-api-14) route providers and language servers to
embedded virtual documents.
- [Snippets](#snippets-api-14) and [menus](#additional-menu-locations-api-14):
numbered placeholders and editor title, main toolbar, Problems and search
@@ -553,6 +553,7 @@ then run `openidea-plugin check`.
| `host::reply_content_tab(request_id, reply)` | `views.reply-content-tab` | API 1.4: reply to an owned action in the originating window. No capability; commands/events only. |
| `RunConfigurations::configurations(root)` | export `run-configurations.configurations` | API 1.4: optional `plugin-run-configurations` world; SDK registration `run_configurations`. Full project list, refreshed on configuration listing. |
| `TestResults::parse(config, chunk)` | export `test-results.parse` | API 1.4: optional `plugin-test-results` world; SDK registration `test_results`. Bounded output batches for `framework = "plugin"`; failures use built-in parsers. |
| `TestResults::select_tests(config, tests)` | export `test-results.select-tests` | API 1.4: full replacement argv for test-tree name paths, or `None` when unsupported (the SDK default). Enables rerunning failed tests and running tree selections. |
| `host::open_location(path, line, column)` | `views.open-location` | Opens a file inside the project in an editor of the invoking window, the caret at `line`/`column` (0-based, UTF-16): a view's links to code. Needs `project.read`. |
| `host::setting(key)`, `setting_bool`, `setting_string`, `setting_number` | `settings.get` | The user's value (project over global) or the schema's default. |
@@ -1118,8 +1119,31 @@ At most 1,000 non-overlapping injection ranges and 32 embedded languages
are routed per document. Earlier ranges in document order win overlaps.
Documents over 2 MiB are excluded. Invalid ranges, self-injections and invalid
language ids are ignored. Injections are not applied recursively. The same
server-side plugin host handles remote editing. **Embedded LSP forwarding is
future host-side work**, not part of 1.4, and needs no WIT change.
server-side plugin host handles remote editing.
When the embedded language has configured language servers, the host also
routes completion (including resolve), hover, signature help, definition,
declaration, type definition, implementation, references, document highlights
and code actions to those servers inside the range. Each range gets its own
masked document, even when several ranges share a language. At most 32 LSP
documents are kept per host document; the same 2 MiB document limit applies.
These documents use non-existent sibling paths with the embedded language's
extension, so servers can discover project configuration. They are never
written to disk. Servers start through the usual settings, project trust and
installation flow; a missing server does not prompt again on each edit.
Edits invalidate old ranges immediately. The host refreshes them after the
300 ms debounce, or before a position request, synchronizes retained documents
with `didChange`, and closes documents when their range disappears, the plugin
is disabled or the host document closes. Results into these documents map back
to the host path and are clipped to the range; locations in other files pass
through. Replacement edits crossing a boundary and resource operations on
virtual paths are dropped. Completion and code-action resolve keep their
originating range/server, and stale results cannot resolve after an edit.
Diagnostics are restricted to each range, labelled with the embedded server's
name and merged with that server's other diagnostics for the host file. They
clear when the range disappears. Formatting and rename use the host server.
Remote projects use this same host-side LSP lifecycle and routing.
### Snippets (API 1.4)
@@ -1628,9 +1652,10 @@ test's parent must already exist. Locations use absolute project-contained paths
zero-based lines and UTF-16 columns. Passed/failed durations are milliseconds.
The host uses the editor-provider soft/hard budget per batch and bounds returned
events to 10,000 / 4 MiB. A missing, failed or invalid parser switches that run to
the built-in parsers; common framework commands retain their existing rerun-failed
filters. Arbitrary frameworks have no failed-test selection protocol in this
export and therefore cannot supply a custom rerun-failed filter.
the built-in parsers. Implement `select_tests(config, tests)` to derive the full
replacement argv for failed tests or test-tree selections; its default returns
`None`. See [Selecting plugin tests](#selecting-plugin-tests-api-14-unreleased)
for the name-path contract and unsupported cases.
`host::open_terminal_session(key, title, &Command::new("tool"))` opens a normal
Terminal tab in this window's project root. Reopening the same key focuses its
@@ -2357,6 +2382,24 @@ its normal editor and project context. No capability is needed. Invalid or
undeclared actions reject the whole notification. Labels are limited to 256
bytes and arguments to 64 KiB. Plain `host::notify` behaves as before.
### Selecting plugin tests (API 1.4, unreleased)
A plugin using `framework = "plugin"` can implement `TestResults::select_tests`
(`test-results.select-tests`) alongside `parse`. It receives the same plugin-local
configuration id as `parse` and a list of test-tree paths: the names from the
plugin's `test-start` events, from parent suite to test, exactly as shown in the
tree. Return the **full replacement argument list**, including any required base
arguments, to run only those tests. `None` (the Rust SDK default), errors and
call timeouts leave test selection unsupported. An empty argument list is a
supported selection. The IDE preserves the configuration's command, environment,
working directory and run target.
This enables **Rerun Failed Tests** and the test tree's **Run** / **Debug** entries.
Calls use the test parser's bounded background budget and run on the plugin's
host, including remote projects. See `official/test-runner` for an example.
This export is added to the existing interface while 1.4 is unreleased; released
export interfaces remain frozen under the rules above.
### Plugin-provided run targets (API 1.4)
`host::register_run_target(project, target)` registers or replaces a read-only,
+1 -1
Переглянути файл
@@ -1 +1 @@
acb5f0a97061616d5bdcf7193d8fbe45c27818663dc0a9eab2e8203589492919
34bea4bf36b7a814dafe02aaee02fe3354a667d1c8ca66f238de00322d0a035a
+1 -1
Переглянути файл
@@ -1 +1 @@
aaa3cdd1595ba8aeabae6472f7f1ef635bd3115662d64d9284152747edfb6b16
fdd68915997803652ad6f5c549107b043b9001ad4e176d2473d9b37469fbe1cc
+1 -1
Переглянути файл
@@ -1 +1 @@
7d09b4e0e3edfbed92be8efaba47d468b7707d6164abf45b0bec495ac454f4dd
ad3fe934d30b48d53097bf4dee36a091b2410c0325924702c66e717405b58203
+1 -1
Переглянути файл
@@ -1 +1 @@
929b309e182c078790940244429b9872d8c7723c0bc25a07b152c83300905c47
5710601823307d167805a7ca20e7498fb9c37082b20df7fd1f86e1cd66b438f3
+1 -1
Переглянути файл
@@ -1 +1 @@
5099f6ceba7936a9b54340a4ce0c9b50a49962dd96053c850c010ea5c803c6a2
1a486ceda9986bc253a0098c983f755c8860e6b7a3f2d7f0284b3b928b4e6c9e
+1 -1
Переглянути файл
@@ -1 +1 @@
6deb9876934b6e21bd99c791f2a86167f1d67e808fbb1cc514c7e621514b654c
13f27c819384f92e406bf7226a46d3fe5b063e850db3d64916e661e1a63f345a
+1 -1
Переглянути файл
@@ -1 +1 @@
5c2f5a254b25ba018369366df87707b423e77a573fcb73cc3c74b1f321f5aa61
c7b2b471f26201c037522ee4a5b086d1c8ef88fbbb3f11f7279ad1a7185bdbae
+1 -1
Переглянути файл
@@ -1 +1 @@
cb4ed7e9d793df4219e92edd5d64616db65411cb77e111df862ca8237f647efb
82c71af4a1f771dbd16a4c8f71b9bd6a6a53d82bd92958d4862467237b82d228
+1 -1
Переглянути файл
@@ -1 +1 @@
f43f1e52813a5f992c3d06cbe03aa26092dd56db45322b090906dfbb8d08b1ab
65096a9b6331af9d40049801547e99e2fa1d5ae0f1065f6931af0aee8d2f24a7
+1 -1
Переглянути файл
@@ -1 +1 @@
656b51f57467a75b5416575871a5722e4f44be98407f6bfd0e6fa1e44f0bfa80
cf8d21da412fd64f1f42c72b13be762ff1bcd43dd19965fc1fce805c5e1012ae
+1 -1
Переглянути файл
@@ -1 +1 @@
bafe2cfc88d8c1272eea289d3d804287d56159b1c5893147b73a6be88e00370f
1ea1d7116e6b943e42580e43cb13199b6e48fc5acdf9784c4864adb7433ebb59
+1 -1
Переглянути файл
@@ -1 +1 @@
ee5d474028c7068b06771efa5e8e2fa710cd0108d53737a36d8bf9f0f3490c08
05ff46a6c1af09b84f9a931d8956d79fbad9507dcff708ba021e074c55c062e2
+1 -1
Переглянути файл
@@ -1 +1 @@
867fc7bba0e795155e96c39f5a05cc3a08a3b6809c4e3922437e393d65f6d829
26e57f5294b40bc31d9283843b2fcf6ad09d475fd160d61ddd3d420e54880a24
+5 -1
Переглянути файл
@@ -10,7 +10,7 @@ The gutter command appends the test name as a filter to `run.start`. The fake
executable prints a deliberately tiny `start NAME` / `pass NAME` protocol;
`test-results.parse` retains split lines and emits stable test ids. Replace
that protocol/parser and executable to integrate a real framework. This is an
API example, not a general test framework or a custom rerun-failed contract.
API example for integrating a test framework.
Build from the repository root:
@@ -23,3 +23,7 @@ cargo run -p ide-host --bin openidea-plugin -- check plugins/official/test-runne
Install the built package folder through Settings › Plugins › Install from
Disk. See the [plugin guide](../../README.md#api-14) and
[official/community policy](../../README.md#81-official-and-community-plugins).
`test-results.select-tests` returns the selected names as the complete argv for
`openidea-example-tests`, enabling Rerun Failed Tests and Run from the test tree.
It returns `None` for unknown configurations or paths this example cannot filter.
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
b7aaac21c6c34d9d722aa23c13c66e61ef11028f038fa877fe67d03b03c18483
0d2c1140fe718d06e08af903ee94bfe87cd04de77c1299f6f5c337042c6f6197
+7 -1
Переглянути файл
@@ -5,6 +5,12 @@ while IFS= read -r line; do
'test '*) name=${line#test } ;;
*) continue ;;
esac
[ -z "$1" ] || [ "$1" = "$name" ] || continue
if [ "$#" -gt 0 ]; then
selected=0
for test in "$@"; do
[ "$test" != "$name" ] || selected=1
done
[ "$selected" -eq 1 ] || continue
fi
printf 'start %s\npass %s\n' "$name" "$name"
done < example.tests
+12
Переглянути файл
@@ -48,6 +48,12 @@ impl LanguageFeatures for TestRunner {
}
}
impl TestResults for TestRunner {
fn select_tests(&mut self, config: &str, tests: &[Vec<String>]) -> Option<Vec<String>> {
if config != "tests" || tests.is_empty() || tests.iter().any(|p| p.len() != 1) {
return None;
}
Some(tests.iter().map(|p| p[0].clone()).collect())
}
fn parse(&mut self, _config: &str, chunk: &str) -> Vec<PluginTestEvent> {
self.pending.push_str(chunk);
let mut events = vec![];
@@ -92,6 +98,12 @@ mod tests {
mock.set_run_configurations(plugin.configurations("/project"));
plugin.run_command("test", &mock.invocation(), Some("adds")).unwrap();
assert_eq!(mock.configuration_runs()[0].2, vec!["adds"]);
assert_eq!(
plugin.select_tests("tests", &[vec!["adds".into()], vec!["subs".into()]]),
Some(vec!["adds".into(), "subs".into()])
);
assert_eq!(plugin.select_tests("unknown", &[vec!["adds".into()]]), None);
assert_eq!(plugin.select_tests("tests", &[vec!["suite".into(), "adds".into()]]), None);
assert!(plugin.parse("tests", "sta").is_empty());
let events = plugin.parse("tests", "rt adds\npass adds\n");
assert!(matches!(&events[..], [PluginTestEvent::TestStarted(_), PluginTestEvent::Passed(_)]));
+1 -1
Переглянути файл
@@ -1 +1 @@
66e92c09c0050dbf4c302793eea5048e21d1c91b9b44811b5f7edbae6eaa9075
f4251a1cad1d5cea54559baca12d84fdf175e65db85ee3f4d29e381e045c40fb
Створено
+6
Переглянути файл
@@ -23,6 +23,12 @@ importers:
'@codemirror/lang-javascript':
specifier: ^6.2.5
version: 6.2.5
'@codemirror/lang-sass':
specifier: ^6.0.2
version: 6.0.2
'@codemirror/lang-vue':
specifier: ^0.1.3
version: 0.1.3
'@codemirror/language':
specifier: ^6.13.1
version: 6.13.1
+4
Переглянути файл
@@ -158,6 +158,10 @@ pub trait RunConfigurations {
/// Parses bounded test output batches; register with test_results.
pub trait TestResults {
fn parse(&mut self, config: &str, chunk: &str) -> Vec<PluginTestEvent>;
/// Full replacement argv for test-tree name paths, or None when filtering is unsupported.
fn select_tests(&mut self, _config: &str, _tests: &[Vec<String>]) -> Option<Vec<String>> {
None
}
}
impl crate::Event {
+9
Переглянути файл
@@ -1101,6 +1101,12 @@ pub mod __rt {
})
.collect()
}
pub fn select_tests<T: Plugin + crate::TestResults + Default>(
config: &str,
tests: &[Vec<String>],
) -> Option<Vec<String>> {
with::<T, _>(|p| p.select_tests(config, tests))
}
pub fn test_results<T: Plugin + crate::TestResults + Default>(
config: &str,
chunk: &str,
@@ -1321,6 +1327,9 @@ macro_rules! __test_results_exports {
fn parse(config: String, chunk: String) -> Vec<$crate::test_results_bindings::exports::openidea::plugin::test_results::TestEvent> {
$crate::__rt::test_results::<$plugin>(&config, &chunk)
}
fn select_tests(config: String, tests: Vec<Vec<String>>) -> Option<Vec<String>> {
$crate::__rt::select_tests::<$plugin>(&config, &tests)
}
}
$crate::test_results_bindings::__export_tests_world!($component with_types_in $crate::test_results_bindings);
};
+11
Переглянути файл
@@ -53,3 +53,14 @@ fn run_targets_require_a_program_grant_and_are_project_scoped() {
host::unregister_run_target(&project, "ddev");
assert!(mock.run_targets().is_empty());
}
#[test]
fn parsers_can_keep_the_default_unsupported_test_selection() {
struct Parser;
impl TestResults for Parser {
fn parse(&mut self, _: &str, _: &str) -> Vec<PluginTestEvent> {
vec![]
}
}
assert_eq!(Parser.select_tests("tests", &[vec!["Suite".into(), "Test".into()]]), None);
}
+5 -1
Переглянути файл
@@ -1,6 +1,10 @@
package openidea:[email protected];
/// Embedded languages. This host routes plugin providers, not embedded LSP servers.
/// Embedded languages. The host routes plugin providers and configured language
/// servers inside these ranges, preserving host-document UTF-16 coordinates.
/// Each LSP range gets its own masked, in-memory sibling document (at most 32
/// per host document, documents over 2 MiB excluded). No file is written.
/// Formatting and rename continue to use the host language's server.
interface injections {
/// A versioned document snapshot. Coordinates are zero-based UTF-16.
record document { path: string, language: string, version: u64, text: string }
+3
Переглянути файл
@@ -47,4 +47,7 @@ interface test-results {
}
/// Parses one bounded output batch; failures fall back to built-in parsers.
parse: func(config: string, chunk: string) -> list<test-event>;
/// Selects test-tree name paths (parents then test), using the same config id as parse.
/// Returns the full replacement argument list, or none when filtering is unsupported.
select-tests: func(config: string, tests: list<list<string>>) -> option<list<string>>;
}
+1 -1
Переглянути файл
@@ -220,7 +220,7 @@ async function smoke(language: string) {
// Rerun Failed Tests runs that one test only.
const rerunOutput: string[] = [];
const before = useRun.getState().sessions.find((s) => s.id === id)!.startedAt;
expect(rerunFailed(id), "Rerun Failed Tests is offered").toBe(true);
expect(await rerunFailed(id), "Rerun Failed Tests is offered").toBe(true);
const ended = () => {
const s = useRun.getState().sessions.find((s) => s.id === id)!;
return s.startedAt > before && s.endedAt !== null && s.endedAt >= s.startedAt;
+1
Переглянути файл
@@ -514,6 +514,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
plugin::plugin_terminal_session_spawn,
plugin::plugin_terminal_session_close,
plugin::plugin_parse_test_results,
plugin::plugin_select_tests,
plugin::plugin_content_tab_action,
plugin::plugin_choose_program,
plugin::plugin_program,
+16
Переглянути файл
@@ -963,6 +963,22 @@ pub fn plugin_content_tab_action(
state.plugins.content_tab_action(window.label(), &plugin_id, action)
}
/// Selects test-tree paths in an owned plugin test configuration.
#[tauri::command]
#[specta::specta]
pub async fn plugin_select_tests(
window: Window,
state: State<'_, AppState>,
config: String,
tests: Vec<Vec<String>>,
) -> IdeResult<Option<Vec<String>>> {
let plugins = state.plugins.clone();
let client = window.label().to_owned();
tokio::task::spawn_blocking(move || plugins.select_tests(&client, &config, tests))
.await
.map_err(|e| ide_core::IdeError::internal(e.to_string()))?
}
/// Parses one batch of an owned test configuration's output.
#[tauri::command]
#[specta::specta]
+2
Переглянути файл
@@ -1145,6 +1145,8 @@ export const commands = {
pluginTerminalSessionClose: (operation: string) => typedError<null, IdeError>(__TAURI_INVOKE("plugin_terminal_session_close", { operation })),
/** Parses one batch of an owned test configuration's output. */
pluginParseTestResults: (config: string, chunk: string) => typedError<PluginTestEvent[] | null, IdeError>(__TAURI_INVOKE("plugin_parse_test_results", { config, chunk })),
/** Selects test-tree paths in an owned plugin test configuration. */
pluginSelectTests: (config: string, tests: string[][]) => typedError<string[] | null, IdeError>(__TAURI_INVOKE("plugin_select_tests", { config, tests })),
/** Dispatches a wasm content editor action through the owning plugin's event handler. */
pluginContentTabAction: (pluginId: string, action: ContentTabAction) => typedError<null, IdeError>(__TAURI_INVOKE("plugin_content_tab_action", { pluginId, action })),
/** Re-approves a plugin's executable, globally or for this window's project. */
+6
Переглянути файл
@@ -131,6 +131,12 @@ const OWN_MODES = [
extensions: ["astro"],
load: () => import("./astro").then((m) => m.astro()),
}),
// Overrides the language-data Vue mode so `<style lang="scss">` highlights.
LanguageDescription.of({
name: "Vue",
extensions: ["vue"],
load: () => import("./vue").then((m) => m.vueLanguage()),
}),
LanguageDescription.of({
name: "YAML",
alias: ["yml"],
+26
Переглянути файл
@@ -0,0 +1,26 @@
import { describe, expect, it } from "vitest";
import { findLanguageDescription, loadSupport } from "./languages";
describe("vue language mode", () => {
it('highlights SCSS inside <style lang="scss">', async () => {
const desc = findLanguageDescription("Vue", "/p/a.vue")!;
expect(desc?.name).toBe("Vue");
const support = await loadSupport(desc);
const src = `<template><div/></template>\n` + `<style lang="scss">\n.a { .b { color: red; } $c: 1; }\n</style>`;
const tree = support!.language.parser.parse(src).toString();
// SCSS-only syntax that plain CSS can't parse: a nested rule and a $-variable.
expect(tree).toContain("SassVariableName");
// The nested .b ruleset only parses under the Sass grammar.
expect(tree).toMatch(/RuleSet\(ClassSelector.*RuleSet\(ClassSelector/s);
});
it("still parses a plain <style> block as CSS", async () => {
const support = await loadSupport(findLanguageDescription("Vue", "/p/a.vue")!);
const tree = support!.language.parser
.parse(`<template><div/></template><style>.a { color: red; }</style>`)
.toString();
expect(tree).toContain("StyleSheet");
expect(tree).toContain("Declaration");
expect(tree).not.toContain("SassVariableName");
});
});
+27
Переглянути файл
@@ -0,0 +1,27 @@
/**
* Vue single-file components: `@codemirror/lang-vue`'s parser over an HTML
* base that also highlights `<style lang="scss|sass">` with the Sass grammar —
* stock `vue()` parses every `<style>` as plain CSS, which loses the SCSS
* colours.
*/
import { LanguageSupport } from "@codemirror/language";
import { html } from "@codemirror/lang-html";
import { sassLanguage } from "@codemirror/lang-sass";
import { vue } from "@codemirror/lang-vue";
export function vueLanguage(): LanguageSupport {
return vue({
base: html({
selfClosingTags: true,
// `<style>` without `lang` (or with `lang="css"`) keeps HTML's own CSS
// nesting; only an explicit SCSS/Sass dialect re-parses it.
nestedLanguages: [
{
tag: "style",
attrs: (a) => a.lang === "scss" || a.lang === "sass",
parser: sassLanguage.parser,
},
],
}),
});
}
+5
Переглянути файл
@@ -118,6 +118,11 @@
}
.conversationRow {
min-width: 0;
contain-intrinsic-size: auto 120px;
}
/* Laid out once, an off-screen row skips rendering at its remembered size (`useOffscreenRows`). */
.conversationRow[data-measured] {
content-visibility: auto;
}
/* Keep turns distinct and the work within a turn close to its author. */
.stream > * + * {
+178 -47
Переглянути файл
@@ -1,15 +1,18 @@
/** An agent task as an editor tab: the conversation, a composer and the task's changed files. */
import {
createContext,
Fragment,
memo,
startTransition,
useCallback,
useContext,
useEffect,
useLayoutEffect,
useMemo,
useRef,
useState,
type ReactElement,
type ReactNode,
type RefObject,
} from "react";
import clsx from "clsx";
@@ -189,16 +192,18 @@ function TaskSession({ id, docked }: { id: string; docked: boolean }) {
docked={docked}
/>
{view && <SubagentBar task={task} path={path} cards={cards} onNavigate={setPath} />}
<Stream
key={view ?? ""}
task={task}
entries={viewEntries ?? null}
subagent={view ? (cards.at(-1) ?? null) : null}
onOpenSubagent={openSubagent}
finding={finding && shown}
findFocus={findFocus}
onCloseFind={() => setFinding(false)}
/>
<FoldedContent.Provider value={finding && shown}>
<Stream
key={view ?? ""}
task={task}
entries={viewEntries ?? null}
subagent={view ? (cards.at(-1) ?? null) : null}
onOpenSubagent={openSubagent}
finding={finding && shown}
findFocus={findFocus}
onCloseFind={() => setFinding(false)}
/>
</FoldedContent.Provider>
{view ? (
<div className={styles.readOnly}>
<T>Subagents take their instructions from the agent that started them.</T>
@@ -457,6 +462,65 @@ function SubagentBar({
);
}
/**
* Lets the rows of a long conversation skip rendering while off screen (`data-measured`, see
* the CSS), so showing the tab again or restyling it costs what is on screen, not the whole
* history. A row skips only once it was laid out: it keeps its real height, and scrolling up
* doesn't jump (WebKit has no scroll anchoring). A new width lays them out again once it
* settles; Find in Conversation (`enabled` false) needs every row laid out.
*/
function useOffscreenRows(ref: RefObject<HTMLElement | null>, visible: boolean, enabled: boolean) {
// The width the marked rows were laid out at.
const width = useRef(0);
useEffect(() => {
const el = ref.current;
if (!el) return;
const unmark = () => {
for (const row of el.querySelectorAll(`:scope > .${styles.conversationRow}[data-measured]`)) {
row.removeAttribute("data-measured");
}
};
if (!enabled) return unmark();
if (!visible) return;
let frame = 0;
let timer: number | undefined;
const mark = () => {
cancelAnimationFrame(frame);
// The next frame lays the new rows out (and remembers their size); mark them after it.
frame = requestAnimationFrame(() => {
frame = requestAnimationFrame(() => {
for (const row of el.querySelectorAll(`:scope > .${styles.conversationRow}:not([data-measured])`)) {
row.setAttribute("data-measured", "");
}
});
});
};
const remeasure = () => {
if (el.clientWidth === width.current) return;
width.current = el.clientWidth;
unmark();
};
remeasure();
mark();
const rows = new MutationObserver(mark);
rows.observe(el, { childList: true });
const resize = new ResizeObserver(() => {
window.clearTimeout(timer);
timer = window.setTimeout(() => {
remeasure();
mark();
}, 200);
});
resize.observe(el);
return () => {
cancelAnimationFrame(frame);
window.clearTimeout(timer);
rows.disconnect();
resize.disconnect();
};
}, [ref, visible, enabled]);
}
interface StreamProps {
task: AgentTask;
entries: AgentEntry[] | null;
@@ -489,6 +553,12 @@ function Stream({ task, entries, subagent, onOpenSubagent, finding, findFocus, o
// Keep a process run intact so prepending never replaces the anchored row.
while (entries && start > 0 && isProcessEntry(entries[start]!) && isProcessEntry(entries[start - 1]!)) start--;
const dragging = useRef(false);
// When the user last scrolled the conversation (wheel, touch, keys, the scrollbar, Find):
// only that leaves the end. WebKit also moves the offset back on its own while rows lay out.
const userScrolled = useRef(-Infinity);
const markUserScroll = useCallback(() => {
userScrolled.current = performance.now();
}, []);
// Earlier entries are prepended above the view: remember where the first painted row is
// so the content stays put and the scrollbar doesn't jump under the pointer.
const anchor = useRef<{ el: Element; top: number } | null>(null);
@@ -540,6 +610,7 @@ function Stream({ task, entries, subagent, onOpenSubagent, finding, findFocus, o
}, [start]);
// Hidden behind another tab, it has no layout to scroll; shown again, it follows the end again.
const visible = useEditorShown();
useOffscreenRows(ref, visible, !finding);
/** A diagram that drew after the last streamed chunk grows the conversation: keep following. */
const onDiagramDrawn = useCallback(() => {
const el = ref.current;
@@ -636,7 +707,13 @@ function Stream({ task, entries, subagent, onOpenSubagent, finding, findFocus, o
[task, turns, replies, times, lastIndex, busy, onOpenSubagent, onDiagramDrawn],
);
return (
<div className={styles.streamArea}>
<div
className={styles.streamArea}
onWheel={markUserScroll}
onTouchMove={markUserScroll}
onKeyDown={markUserScroll}
onPointerDown={markUserScroll}
>
{finding && <FindBar streamRef={ref} focus={findFocus} onClose={onCloseFind} />}
<div
ref={ref}
@@ -645,7 +722,12 @@ function Stream({ task, entries, subagent, onOpenSubagent, finding, findFocus, o
tabIndex={-1}
onScroll={(e) => {
const el = e.currentTarget;
position.current = { top: el.scrollTop, stick: el.scrollHeight - el.scrollTop - el.clientHeight < 40 };
const atEnd = el.scrollHeight - el.scrollTop - el.clientHeight < 40;
const byUser = dragging.current || performance.now() - userScrolled.current < 500;
const stick = atEnd || (position.current.stick && !byUser);
// Still following: back to the end the offset was moved away from.
if (stick && !atEnd) el.scrollTop = el.scrollHeight;
position.current = { top: el.scrollTop, stick };
positions.set(key, position.current);
setAway(!position.current.stick);
// Reached the top of what is painted: fetch the earlier entries, but only
@@ -1015,19 +1097,23 @@ const Entry = memo(function Entry({
case "thought":
return (
<div className={styles.process}>
<details className={styles.thought}>
<summary>
{working ? (
<Spinner size={12} />
) : (
<Icon name="chevron-right" size={12} className={styles.thoughtChevron} />
)}
<T>{working ? "Thinking" : "Reasoning"}</T>
</summary>
<Fold
className={styles.thought}
summary={
<summary>
{working ? (
<Spinner size={12} />
) : (
<Icon name="chevron-right" size={12} className={styles.thoughtChevron} />
)}
<T>{working ? "Thinking" : "Reasoning"}</T>
</summary>
}
>
<div className={styles.thoughtBody}>
<Markdown text={entry.text} cwd={task.cwd} onDiagramDrawn={onDiagramDrawn} />
</div>
</details>
</Fold>
</div>
);
case "tool":
@@ -1383,14 +1469,18 @@ const ProcessRun = memo(function ProcessRun({
tools.length > 0 ? `${tools.length} ${tx(tools.length === 1 ? "tool call" : "tool calls")}` : null,
].filter(Boolean);
return (
<details className={clsx(styles.processRun, styles.process)}>
<summary className={styles.processSummary}>
<Icon name="chevron-right" size={12} className={styles.processChevron} />
{working && <Spinner size={12} />}
<span>{parts.join(" · ")}</span>
{added > 0 && <span className={styles.added}>+{added}</span>}
{removed > 0 && <span className={styles.removed}>−{removed}</span>}
</summary>
<Fold
className={clsx(styles.processRun, styles.process)}
summary={
<summary className={styles.processSummary}>
<Icon name="chevron-right" size={12} className={styles.processChevron} />
{working && <Spinner size={12} />}
<span>{parts.join(" · ")}</span>
{added > 0 && <span className={styles.added}>+{added}</span>}
{removed > 0 && <span className={styles.removed}>−{removed}</span>}
</summary>
}
>
<div className={styles.processBody}>
{row.entries.map(({ index, entry }) =>
entry.type === "tool" ? (
@@ -1400,10 +1490,38 @@ const ProcessRun = memo(function ProcessRun({
),
)}
</div>
</details>
</Fold>
);
});
/** Set while Find in Conversation is open: folded sections render their content, so it is found. */
const FoldedContent = createContext(false);
/**
* A collapsed section that renders its content only once opened: most of a long conversation
* stays folded, and keeping it out of the DOM keeps showing and restyling the tab cheap.
*/
function Fold({
className,
open,
summary,
children,
}: {
className?: string;
open?: boolean;
summary: ReactElement;
children: ReactNode;
}) {
const always = useContext(FoldedContent);
const [expanded, setExpanded] = useState(!!open);
return (
<details className={className} open={open || undefined} onToggle={(e) => setExpanded(e.currentTarget.open)}>
{summary}
{(expanded || open || always) && children}
</details>
);
}
const ToolEntry = memo(function ToolEntry({
task,
entry,
@@ -1443,13 +1561,18 @@ const ToolEntry = memo(function ToolEntry({
);
return (
<div className={styles.process}>
<details className={styles.toolDetails} open={liveTool(entry) || undefined}>
<summary className={styles.tool}>
<Icon name="chevron-right" size={12} className={styles.toolChevron} />
{head}
</summary>
<Fold
className={styles.toolDetails}
open={liveTool(entry)}
summary={
<summary className={styles.tool}>
<Icon name="chevron-right" size={12} className={styles.toolChevron} />
{head}
</summary>
}
>
<pre className={styles.output}>{entry.output}</pre>
</details>
</Fold>
</div>
);
});
@@ -1532,22 +1655,30 @@ function SubagentCard({
</div>
)}
{entry.prompt && (
<details className={styles.subagentSection}>
<summary>
<T>Task</T>
</summary>
<Fold
className={styles.subagentSection}
summary={
<summary>
<T>Task</T>
</summary>
}
>
<div className={styles.thoughtText}>{entry.prompt}</div>
</details>
</Fold>
)}
{entry.reply && (
<details className={styles.subagentSection}>
<summary>
<T>Result</T>
</summary>
<Fold
className={styles.subagentSection}
summary={
<summary>
<T>Result</T>
</summary>
}
>
<div className={styles.subagentReply}>
<AgentReply text={entry.reply} cwd={task.cwd} task={task} onDiagramDrawn={onDiagramDrawn} />
</div>
</details>
</Fold>
)}
</div>
);
+16
Переглянути файл
@@ -45,6 +45,22 @@ export function activate(): () => void {
sync(useProject.getState().project?.root);
const disposers = [
activateSettingsPages(),
// The performance harness (`perf/`): long conversations to switch between and scroll.
import.meta.env.DEV || import.meta.env.MODE === "perf"
? registerActions([
{
id: "agents.openSampleConversations",
title: "Open Sample Conversations",
category: "Agents",
hidden: true,
run: async ({ arg }) => {
const { tasks = 2, turns = 150 } = (arg ?? {}) as { tasks?: number; turns?: number };
const { openSampleConversations } = await import("./sampleConversation");
openSampleConversations(tasks, turns);
},
},
])
: () => {},
useProject.subscribe((s, prev) => {
if (s.project?.root !== prev.project?.root || s.project?.trusted !== prev.project?.trusted) sync(s.project?.root);
}),
+108
Переглянути файл
@@ -0,0 +1,108 @@
/**
* Agent tasks with long generated conversations, opened as editor tabs: what the
* performance harness (`perf/`) switches between and scrolls. Dev and perf builds only.
*/
import type { AgentEntry, AgentTask } from "@/bindings";
import { useProject } from "@/platform/project";
import { openTask, useAgents } from "./store";
function task(id: string, title: string, cwd: string): AgentTask {
return {
id,
title,
provider: "claude",
model: null,
status: "ready",
isolation: "worktree",
cwd,
branch: null,
base: null,
baseCommit: null,
error: null,
createdMs: null,
updatedMs: null,
config: [],
commands: [],
usage: null,
queue: [],
};
}
/** A turn as agents work: a request, reasoning, a run of tool calls, then a reply with code. */
function turn(cwd: string, i: number): AgentEntry[] {
const file = (k: number) => `${cwd}/src/orders/Order${(i + k) % 40}.kt`;
const tools: AgentEntry[] = Array.from({ length: 10 }, (_, k) => {
// Tool titles as agents report them (commands and paths, not UI text).
const command = k % 3 === 2 ? `Edit ${file(k)}` : k % 3 === 1 ? `Read ${file(k)}` : `grep -rn "order${i}" src`;
return {
type: "tool",
id: `tool-${i}-${k}`,
title: command,
kind: k % 3 === 2 ? "edit" : k % 3 === 1 ? "read" : "execute",
status: "completed",
locations: [],
output: Array.from(
{ length: 12 },
(_, l) => `${file(l)}:${l * 7 + 3}: val order${i} = repository.find(id${l})`,
).join("\n"),
diffs: k % 3 === 2 ? [{ path: file(k), added: 4 + (k % 5), removed: 2 }] : [],
};
});
// What a user and an agent wrote (conversation content, not UI text).
const request = `Turn ${i}: make the order service retry failed payments and cover it with tests`;
const reasoning = `The payment client throws on timeouts; retrying belongs in the service (turn ${i}).`;
return [
{
type: "user",
text: request,
attachments: [],
sentMs: null,
doneMs: null,
},
{
type: "thought",
text: reasoning,
},
...tools,
{
type: "agent",
text: [
`## Turn ${i}`,
"",
`Payments now retry **three times** with backoff before the order fails. Changed \`OrderService.kt\` and added tests:`,
"",
"- `retries` on timeouts, not on declined cards",
"- waits 200 ms, then 400 ms, then 800 ms",
"- logs each attempt with the order id",
"",
"```kotlin",
`suspend fun pay${i}(order: Order): Receipt =`,
" retry(times = 3, initialDelay = 200.milliseconds) {",
" payments.charge(order.id, order.total)",
" }",
"```",
"",
"| Case | Before | After |",
"|---|---|---|",
"| Timeout | failed | retried |",
"| Declined | failed | failed |",
].join("\n"),
},
];
}
/** Opens `count` tasks of `turns` turns each (14 entries a turn), the last one shown. */
export function openSampleConversations(count: number, turns: number) {
const cwd = useProject.getState().project?.root ?? "/";
const entries = Array.from({ length: turns }, (_, i) => turn(cwd, i)).flat();
const s = useAgents.getState();
const tasks = new Map(s.tasks);
const all = new Map(s.entries);
const ids = Array.from({ length: count }, (_, n) => `sample-${n + 1}`);
ids.forEach((id, n) => {
tasks.set(id, task(id, `Sample task ${n + 1}`, cwd));
all.set(id, entries);
});
useAgents.setState({ tasks, entries: all });
for (const id of ids) openTask(id);
}
Loaded 100 of 129 files, more files were not shown because too many files have changed in this diff. Show more