дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-28 21:42:27 +02:00
Порівняти коміти
17
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
1fd65bd01a | ||
|
|
2cb6322172 | ||
|
|
212ee03d71 | ||
|
|
b721fe09db | ||
|
|
6ffb4c22f0 | ||
|
|
dc38b0b081 | ||
|
|
3cbc9d7f75 | ||
|
|
2ec2a6c262 | ||
|
|
11dca3ab42 | ||
|
|
f9044dcc00 | ||
|
|
a7d7293b2f | ||
|
|
a5280c50f7 | ||
|
|
dd0578979a | ||
|
|
e96b0483ac | ||
|
|
608b292510 | ||
|
|
dd6d83fd2c | ||
|
|
b89febd61f |
No files matched your search
Створено
+17
@@ -4156,6 +4156,8 @@ dependencies = [
|
||||
"ide-vcs",
|
||||
"ide-vfs",
|
||||
"parking_lot",
|
||||
"rustix",
|
||||
"semver",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"specta",
|
||||
@@ -4357,6 +4359,20 @@ dependencies = [
|
||||
"which",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ide-drag-out"
|
||||
version = "0.1.49"
|
||||
dependencies = [
|
||||
"gtk",
|
||||
"objc2 0.6.5",
|
||||
"objc2-app-kit 0.3.2",
|
||||
"objc2-foundation 0.3.2",
|
||||
"raw-window-handle",
|
||||
"tempfile",
|
||||
"windows",
|
||||
"windows-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ide-extension"
|
||||
version = "0.1.49"
|
||||
@@ -6698,6 +6714,7 @@ dependencies = [
|
||||
"ide-dap",
|
||||
"ide-db",
|
||||
"ide-docker",
|
||||
"ide-drag-out",
|
||||
"ide-extension",
|
||||
"ide-fonts",
|
||||
"ide-github",
|
||||
|
||||
@@ -38,6 +38,7 @@ ide-web = { path = "crates/ide-web" }
|
||||
ide-spell = { path = "crates/ide-spell" }
|
||||
ide-agent = { path = "crates/ide-agent" }
|
||||
ide-clipboard = { path = "crates/ide-clipboard" }
|
||||
ide-drag-out = { path = "crates/ide-drag-out" }
|
||||
ide-fonts = { path = "crates/ide-fonts" }
|
||||
ide-ssh = { path = "crates/ide-ssh" }
|
||||
ide-remote = { path = "crates/ide-remote" }
|
||||
|
||||
@@ -25,6 +25,10 @@ dunce.workspace = true
|
||||
uuid.workspace = true
|
||||
tempfile.workspace = true
|
||||
which = "8"
|
||||
semver = "1"
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
rustix = { version = "1", features = ["fs"] }
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { workspace = true, features = ["test-util"] }
|
||||
@@ -0,0 +1,395 @@
|
||||
//! Checks and updates only the global npm installation selected by the agent launcher.
|
||||
use crate::{AgentManager, AgentSource, provider};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult, error::ErrorKind};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
use specta::Type;
|
||||
use std::{
|
||||
fs, io,
|
||||
path::{Path, PathBuf},
|
||||
process::Command,
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
pub struct AgentCliOffer {
|
||||
pub current: String,
|
||||
pub latest: String,
|
||||
pub prefix: PathBuf,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(tag = "status", rename_all = "camelCase")]
|
||||
pub enum AgentCliUpdateResult {
|
||||
Available(AgentCliOffer),
|
||||
Permission(AgentCliOffer),
|
||||
Current { current: String },
|
||||
Channel { current: String },
|
||||
Updated { current: String },
|
||||
Unmanaged,
|
||||
Error { code: String },
|
||||
}
|
||||
|
||||
pub(crate) fn package(id: &str) -> Option<&'static str> {
|
||||
Some(match id {
|
||||
"claude" => "@anthropic-ai/claude-code",
|
||||
"codex" => "@openai/codex",
|
||||
"gemini" => "@google/gemini-cli",
|
||||
"opencode" => "opencode-ai",
|
||||
"copilot" => "@github/copilot",
|
||||
"qwen" => "@qwen-code/qwen-code",
|
||||
"auggie" => "@augmentcode/auggie",
|
||||
"qoder" => "@qoder-ai/qodercli",
|
||||
"omp" => "@oh-my-pi/pi-coding-agent",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
impl AgentManager {
|
||||
pub fn cli_update(
|
||||
&self,
|
||||
id: &str,
|
||||
offer: Option<&AgentCliOffer>,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<AgentCliUpdateResult> {
|
||||
let spec = self.shared.spec(id).ok_or_else(|| IdeError::invalid(format!("unknown agent {id}")))?;
|
||||
let (Some(pkg), Some(builtin)) = (package(id), provider::builtin_spec(id)) else {
|
||||
return Ok(AgentCliUpdateResult::Unmanaged);
|
||||
};
|
||||
if spec.source != AgentSource::Builtin {
|
||||
return Ok(AgentCliUpdateResult::Unmanaged);
|
||||
}
|
||||
let Ok(npm) = which::which("npm") else { return Ok(AgentCliUpdateResult::Unmanaged) };
|
||||
let program = spec.resolve_for_launch(&self.shared.paths.project_root).command;
|
||||
match maintain(&npm, Path::new(&program), &builtin.command, pkg, offer, cancel) {
|
||||
Err(e) if e.kind == ErrorKind::Unavailable => Ok(AgentCliUpdateResult::Error { code: e.message }),
|
||||
result => result,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Installation {
|
||||
modules: PathBuf,
|
||||
folder: PathBuf,
|
||||
link: PathBuf,
|
||||
}
|
||||
|
||||
impl Installation {
|
||||
fn at(prefix: &Path, pkg: &str, bin: &str) -> Self {
|
||||
let modules = prefix.join(if cfg!(windows) { "node_modules" } else { "lib/node_modules" });
|
||||
let link = if cfg!(windows) { prefix.join(format!("{bin}.cmd")) } else { prefix.join("bin").join(bin) };
|
||||
Self { folder: modules.join(pkg), modules, link }
|
||||
}
|
||||
|
||||
fn version(&self, program: &Path, pkg: &str, bin: &str) -> IdeResult<Option<String>> {
|
||||
if !program.is_absolute() || !self.folder.try_exists()? || !self.link.try_exists()? || !program.try_exists()? {
|
||||
return Ok(None);
|
||||
}
|
||||
let folder = dunce::canonicalize(&self.folder)?;
|
||||
if fs::symlink_metadata(&self.folder)?.is_symlink()
|
||||
|| dunce::canonicalize(program)? != dunce::canonicalize(&self.link)?
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
let manifest = self.folder.join("package.json");
|
||||
if !manifest.try_exists()? {
|
||||
return Ok(None);
|
||||
}
|
||||
let manifest: Value = serde_json::from_slice(&fs::read(manifest)?)
|
||||
.map_err(|_| IdeError::invalid("Invalid npm package manifest"))?;
|
||||
let entry = manifest["bin"].as_str().or_else(|| manifest["bin"][bin].as_str());
|
||||
let Some(entry) = entry.filter(|_| manifest["name"] == pkg) else { return Ok(None) };
|
||||
let Some(version) = manifest["version"].as_str() else {
|
||||
return Err(IdeError::invalid("Missing npm package version"));
|
||||
};
|
||||
let entry = folder.join(entry);
|
||||
if !entry.try_exists()? {
|
||||
return Ok(None);
|
||||
}
|
||||
let entry = dunce::canonicalize(entry)?;
|
||||
if !entry.starts_with(&folder) {
|
||||
return Ok(None);
|
||||
}
|
||||
#[cfg(unix)]
|
||||
let owns = fs::symlink_metadata(&self.link)?.is_symlink() && dunce::canonicalize(&self.link)? == entry;
|
||||
#[cfg(windows)]
|
||||
let owns = {
|
||||
let prefix = dunce::canonicalize(self.link.parent().unwrap())?;
|
||||
let Ok(target) = entry.strip_prefix(prefix) else { return Ok(None) };
|
||||
let needle = format!("%dp0%\\{}\"", target.display()).to_lowercase();
|
||||
fs::read_to_string(&self.link)?.replace('/', "\\").to_lowercase().contains(&needle)
|
||||
};
|
||||
Ok(owns.then(|| version.to_owned()))
|
||||
}
|
||||
|
||||
fn writable(&self) -> io::Result<bool> {
|
||||
for dir in [&*self.folder, self.folder.parent().unwrap(), &self.modules, self.link.parent().unwrap()] {
|
||||
#[cfg(unix)]
|
||||
let access: io::Result<()> =
|
||||
rustix::fs::accessat(rustix::fs::CWD, dir, rustix::fs::Access::WRITE_OK, rustix::fs::AtFlags::empty())
|
||||
.map_err(Into::into);
|
||||
#[cfg(windows)]
|
||||
let access = tempfile::tempfile_in(dir).map(drop);
|
||||
match access {
|
||||
Err(e) if matches!(e.kind(), io::ErrorKind::PermissionDenied | io::ErrorKind::ReadOnlyFilesystem) => {
|
||||
return Ok(false);
|
||||
}
|
||||
other => other?,
|
||||
}
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
|
||||
fn stable(version: &str) -> Option<semver::Version> {
|
||||
semver::Version::parse(version).ok().filter(|v| v.pre.is_empty() && v.build.is_empty())
|
||||
}
|
||||
|
||||
fn maintain(
|
||||
npm: &Path,
|
||||
program: &Path,
|
||||
bin: &str,
|
||||
pkg: &str,
|
||||
approved: Option<&AgentCliOffer>,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<AgentCliUpdateResult> {
|
||||
use AgentCliUpdateResult::*;
|
||||
let run = |args: &[&str]| {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let mut cmd = Command::new(npm);
|
||||
cmd.args(args)
|
||||
.current_dir(npm.parent().unwrap())
|
||||
.env("NPM_CONFIG_UPDATE_NOTIFIER", "false")
|
||||
.env("NPM_CONFIG_LOGLEVEL", "error");
|
||||
ide_tools::run_streamed(cmd, cancel, &|_| {}).map_err(|e| {
|
||||
if e.kind == ErrorKind::Cancelled {
|
||||
return e;
|
||||
}
|
||||
// npm diagnostics can contain private registry URLs; expose only known codes.
|
||||
let code = e
|
||||
.message
|
||||
.split(|c: char| !c.is_ascii_alphanumeric() && c != '_')
|
||||
.find(|w| {
|
||||
matches!(
|
||||
*w,
|
||||
"EACCES"
|
||||
| "EPERM"
|
||||
| "EROFS"
|
||||
| "ENOTFOUND"
|
||||
| "EAI_AGAIN"
|
||||
| "ETIMEDOUT"
|
||||
| "E404"
|
||||
| "E401"
|
||||
| "E403"
|
||||
)
|
||||
})
|
||||
.unwrap_or("npm");
|
||||
IdeError::unavailable(code)
|
||||
})
|
||||
};
|
||||
let output = run(&["prefix", "-g"])?;
|
||||
let prefix = Path::new(output.trim_end());
|
||||
if !prefix.is_absolute() {
|
||||
return Err(IdeError::invalid("Invalid npm global prefix"));
|
||||
}
|
||||
let installation = Installation::at(prefix, pkg, bin);
|
||||
let Some(current) = installation.version(program, pkg, bin)? else { return Ok(Unmanaged) };
|
||||
let latest: String = serde_json::from_str(&run(&["view", &format!("{pkg}@latest"), "version", "--json"])?)
|
||||
.map_err(|_| IdeError::invalid("Invalid npm version response"))?;
|
||||
let (Some(before), Some(after)) = (stable(¤t), stable(&latest)) else {
|
||||
return Ok(Channel { current });
|
||||
};
|
||||
if before >= after {
|
||||
return Ok(Current { current });
|
||||
}
|
||||
let offer = AgentCliOffer { current, latest, prefix: prefix.to_owned() };
|
||||
if !installation.writable()? {
|
||||
return Ok(Permission(offer));
|
||||
}
|
||||
if approved != Some(&offer) {
|
||||
return Ok(Available(offer));
|
||||
}
|
||||
run(&[
|
||||
"install",
|
||||
"-g",
|
||||
"--prefix",
|
||||
prefix.to_str().unwrap(),
|
||||
"--no-audit",
|
||||
"--no-fund",
|
||||
&format!("{pkg}@{}", offer.latest),
|
||||
])?;
|
||||
if installation.version(program, pkg, bin)?.as_ref() != Some(&offer.latest) {
|
||||
return Err(IdeError::invalid("npm installation verification failed"));
|
||||
}
|
||||
Ok(Updated { current: offer.latest })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
use tempfile::TempDir;
|
||||
|
||||
const PKG: &str = "@anthropic-ai/claude-code";
|
||||
|
||||
struct Fixture {
|
||||
root: TempDir,
|
||||
install: Installation,
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
fn new() -> Self {
|
||||
let root = tempfile::Builder::new().prefix("全局 prefix ").tempdir().unwrap();
|
||||
let install = Installation::at(root.path(), PKG, "claude");
|
||||
fs::create_dir_all(&install.folder).unwrap();
|
||||
fs::create_dir_all(install.link.parent().unwrap()).unwrap();
|
||||
fs::write(install.folder.join("entry.js"), "").unwrap();
|
||||
#[cfg(unix)]
|
||||
std::os::unix::fs::symlink(install.folder.join("entry.js"), &install.link).unwrap();
|
||||
#[cfg(windows)]
|
||||
fs::write(&install.link, r#"@"%dp0%\node_modules\@anthropic-ai\claude-code\entry.js""#).unwrap();
|
||||
let fixture = Self { root, install };
|
||||
fixture.manifest(PKG, "2.1.9");
|
||||
fixture
|
||||
}
|
||||
|
||||
fn manifest(&self, name: &str, version: &str) {
|
||||
fs::write(
|
||||
self.install.folder.join("package.json"),
|
||||
json!({"name":name,"version":version,"bin":{"claude":"entry.js"}}).to_string(),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
fn version(&self) -> Option<String> {
|
||||
self.install.version(&self.install.link, PKG, "claude").unwrap()
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn npm(&self, script: &str) -> PathBuf {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let path = self.root.path().join("npm");
|
||||
fs::write(&path, format!("#!/bin/sh\nset -eu\n{script}\n")).unwrap();
|
||||
fs::set_permissions(&path, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
path
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn requires_the_selected_install_and_its_exact_package_entry() {
|
||||
let f = Fixture::new();
|
||||
assert_eq!(f.version().as_deref(), Some("2.1.9"));
|
||||
let other = f.root.path().join("other");
|
||||
fs::write(&other, "").unwrap();
|
||||
assert_eq!(f.install.version(&other, PKG, "claude").unwrap(), None);
|
||||
f.manifest("other-package", "2.1.9");
|
||||
assert_eq!(f.version(), None);
|
||||
f.manifest(PKG, "2.1.9");
|
||||
fs::remove_file(&f.install.link).unwrap();
|
||||
#[cfg(unix)]
|
||||
std::os::unix::fs::symlink(&other, &f.install.link).unwrap();
|
||||
#[cfg(windows)]
|
||||
fs::write(&f.install.link, r#"@"%dp0%\other""#).unwrap();
|
||||
assert_eq!(f.version(), None);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
const NPM: &str = r#"case "$1" in
|
||||
prefix) pwd -P ;;
|
||||
view) cat latest ;;
|
||||
install)
|
||||
test "$2" = "-g" && test "$3" = "--prefix" && test "$4" = "$(pwd -P)"
|
||||
test "$7" = "@anthropic-ai/[email protected]"
|
||||
cp updated.json "$4/lib/node_modules/@anthropic-ai/claude-code/package.json"
|
||||
touch installed ;;
|
||||
*) exit 2 ;;
|
||||
esac"#;
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn installs_only_the_confirmed_offer_and_rechecks_ownership() {
|
||||
use AgentCliUpdateResult::*;
|
||||
let f = Fixture::new();
|
||||
let npm = f.npm(NPM);
|
||||
let cancel = CancellationToken::new();
|
||||
let run =
|
||||
|offer: Option<&AgentCliOffer>| maintain(&npm, &f.install.link, "claude", PKG, offer, &cancel).unwrap();
|
||||
let latest = f.root.path().join("latest");
|
||||
fs::write(&latest, r#""2.1.12""#).unwrap();
|
||||
let Available(offer) = run(None) else { panic!("expected an offer") };
|
||||
for different in [
|
||||
AgentCliOffer { prefix: PathBuf::from("/other"), ..offer.clone() },
|
||||
AgentCliOffer { current: "2.0.0".into(), ..offer.clone() },
|
||||
] {
|
||||
assert_eq!(run(Some(&different)), Available(offer.clone()));
|
||||
}
|
||||
fs::write(&latest, r#""2.2.0""#).unwrap();
|
||||
assert!(matches!(run(Some(&offer)), Available(new) if new.latest == "2.2.0"));
|
||||
fs::write(&latest, r#""2.0.0""#).unwrap();
|
||||
assert!(matches!(run(Some(&offer)), Current { .. }));
|
||||
fs::write(&latest, r#""2.2.0-beta.1""#).unwrap();
|
||||
assert!(matches!(run(Some(&offer)), Channel { .. }));
|
||||
fs::write(&latest, r#""2.1.12""#).unwrap();
|
||||
f.manifest("other-package", "2.1.9");
|
||||
assert_eq!(run(Some(&offer)), Unmanaged);
|
||||
assert!(!f.root.path().join("installed").exists());
|
||||
f.manifest(PKG, "2.1.12");
|
||||
fs::copy(f.install.folder.join("package.json"), f.root.path().join("updated.json")).unwrap();
|
||||
f.manifest(PKG, "2.1.9");
|
||||
assert_eq!(run(Some(&offer)), Updated { current: "2.1.12".into() });
|
||||
assert!(f.root.path().join("installed").exists());
|
||||
assert_eq!(run(None), Current { current: "2.1.12".into() });
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn permission_failure_never_starts_an_install() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let f = Fixture::new();
|
||||
let npm = f.npm(NPM);
|
||||
fs::write(f.root.path().join("latest"), r#""2.1.12""#).unwrap();
|
||||
let run = |offer: Option<&AgentCliOffer>| {
|
||||
maintain(&npm, &f.install.link, "claude", PKG, offer, &CancellationToken::new()).unwrap()
|
||||
};
|
||||
let AgentCliUpdateResult::Available(offer) = run(None) else { panic!("expected an offer") };
|
||||
fs::set_permissions(&f.install.folder, fs::Permissions::from_mode(0o555)).unwrap();
|
||||
// root can write even when no mode bit grants write permission.
|
||||
if tempfile::tempfile_in(&f.install.folder).is_err() {
|
||||
assert_eq!(run(Some(&offer)), AgentCliUpdateResult::Permission(offer));
|
||||
}
|
||||
fs::set_permissions(&f.install.folder, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
assert!(!f.root.path().join("installed").exists());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn cancellation_stops_a_running_npm_process() {
|
||||
use std::time::{Duration, Instant};
|
||||
let f = Fixture::new();
|
||||
let npm = f.npm(
|
||||
r#"case "$1" in
|
||||
prefix) pwd -P ;;
|
||||
view) echo '"2.1.12"' ;;
|
||||
install) touch started; exec sleep 30 ;;
|
||||
esac"#,
|
||||
);
|
||||
let cancel = CancellationToken::new();
|
||||
let AgentCliUpdateResult::Available(offer) =
|
||||
maintain(&npm, &f.install.link, "claude", PKG, None, &cancel).unwrap()
|
||||
else {
|
||||
panic!("expected an offer")
|
||||
};
|
||||
let started = f.root.path().join("started");
|
||||
std::thread::scope(|s| {
|
||||
let op = s.spawn(|| maintain(&npm, &f.install.link, "claude", PKG, Some(&offer), &cancel));
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
while !started.exists() && Instant::now() < deadline {
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
cancel.cancel();
|
||||
assert!(started.exists());
|
||||
assert_eq!(op.join().unwrap().unwrap_err().kind, ErrorKind::Cancelled);
|
||||
});
|
||||
assert_eq!(f.version().as_deref(), Some("2.1.9"));
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@
|
||||
mod acp;
|
||||
mod async_questions;
|
||||
mod catalogs;
|
||||
mod cli_update;
|
||||
mod config;
|
||||
mod conversation;
|
||||
mod elicitation;
|
||||
@@ -27,6 +28,7 @@ mod timeline;
|
||||
mod worktree;
|
||||
|
||||
pub use catalogs::AgentCatalogs;
|
||||
pub use cli_update::{AgentCliOffer, AgentCliUpdateResult};
|
||||
pub use external::ExternalSession;
|
||||
pub use model::*;
|
||||
|
||||
|
||||
@@ -614,6 +614,9 @@ pub struct AgentProvider {
|
||||
pub command_read_only_reason: Option<AgentCommandReadOnlyReason>,
|
||||
/// Whether the command was found (on `PATH`).
|
||||
pub installed: bool,
|
||||
/// The built-in command can be owned by a global npm package.
|
||||
#[serde(default)]
|
||||
pub can_check_cli_update: bool,
|
||||
/// Environment variables it starts with (from its agent file).
|
||||
pub env: BTreeMap<String, String>,
|
||||
/// Settings (models, modes…) the agent offered last time it ran; empty before its first session.
|
||||
|
||||
@@ -373,6 +373,7 @@ pub(crate) fn describe(spec: &ProviderSpec) -> AgentProvider {
|
||||
command_editable: reason.is_none(),
|
||||
command_read_only_reason: reason,
|
||||
installed: installed(&spec.command),
|
||||
can_check_cli_update: spec.source == AgentSource::Builtin && crate::cli_update::package(&spec.id).is_some(),
|
||||
env: spec.env.iter().cloned().collect(),
|
||||
config: vec![],
|
||||
thought_levels: BTreeMap::new(),
|
||||
|
||||
@@ -15,6 +15,7 @@ pub mod inspection_settings;
|
||||
pub mod ipc_path;
|
||||
pub mod java_runtime;
|
||||
pub mod jsonc;
|
||||
pub mod memory;
|
||||
pub mod output_encoding;
|
||||
pub mod platform;
|
||||
pub mod process;
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
//! Returning freed heap pages to the OS.
|
||||
|
||||
/// Hands pages the allocator has freed but kept back to the OS. Call after a burst of
|
||||
/// short-lived allocations (a full index scan); until then they still count towards the
|
||||
/// process's memory footprint.
|
||||
pub fn release_free_pages() {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
unsafe extern "C" {
|
||||
fn malloc_zone_pressure_relief(zone: *mut std::ffi::c_void, goal: usize) -> usize;
|
||||
}
|
||||
// SAFETY: a null zone covers every zone; a zero goal releases as much as possible.
|
||||
unsafe { malloc_zone_pressure_relief(std::ptr::null_mut(), 0) };
|
||||
}
|
||||
#[cfg(all(target_os = "linux", target_env = "gnu"))]
|
||||
// SAFETY: malloc_trim only returns free memory to the OS.
|
||||
unsafe {
|
||||
libc::malloc_trim(0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
[package]
|
||||
name = "ide-drag-out"
|
||||
description = "OS file drags out of an app window, so file managers and transfer clients copy the files: GTK on Linux, OLE on Windows, AppKit on macOS"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
gtk = "0.18"
|
||||
|
||||
[target.'cfg(any(windows, target_os = "macos"))'.dependencies]
|
||||
raw-window-handle = "0.6"
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows = { version = "0.62", features = [
|
||||
"Win32_Foundation",
|
||||
"Win32_Graphics_Gdi",
|
||||
"Win32_System_Com",
|
||||
"Win32_System_Com_StructuredStorage",
|
||||
"Win32_System_Memory",
|
||||
"Win32_System_Ole",
|
||||
"Win32_System_SystemServices",
|
||||
"Win32_UI_Shell",
|
||||
"Win32_UI_Shell_Common",
|
||||
] }
|
||||
# `#[implement]` expands to paths into `windows_core`.
|
||||
windows-core = "0.62"
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
objc2 = { version = "0.6", default-features = false, features = ["std"] }
|
||||
objc2-foundation = { version = "0.3", default-features = false, features = ["std", "NSArray", "NSGeometry", "NSObject", "NSString", "NSURL"] }
|
||||
objc2-app-kit = { version = "0.3", default-features = false, features = [
|
||||
"std",
|
||||
"objc2-core-foundation",
|
||||
"NSApplication",
|
||||
"NSDragging",
|
||||
"NSDraggingItem",
|
||||
"NSDraggingSession",
|
||||
"NSEvent",
|
||||
"NSGraphics",
|
||||
"NSGraphicsContext",
|
||||
"NSImage",
|
||||
"NSPasteboard",
|
||||
"NSPasteboardItem",
|
||||
"NSResponder",
|
||||
"NSView",
|
||||
"NSWindow",
|
||||
"NSWorkspace",
|
||||
] }
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
@@ -0,0 +1,122 @@
|
||||
//! macOS: an AppKit dragging session with one pasteboard item per path, each a file URL.
|
||||
|
||||
use super::Outcome;
|
||||
use objc2::rc::Retained;
|
||||
use objc2::runtime::ProtocolObject;
|
||||
use objc2::{AnyThread, DefinedClass, MainThreadMarker, MainThreadOnly, define_class, msg_send};
|
||||
use objc2_app_kit::{
|
||||
NSApplication, NSDragOperation, NSDraggingContext, NSDraggingItem, NSDraggingSession, NSDraggingSource, NSEvent,
|
||||
NSEventModifierFlags, NSEventType, NSPasteboardItem, NSPasteboardTypeFileURL, NSView, NSWorkspace,
|
||||
};
|
||||
use objc2_foundation::{NSArray, NSObject, NSObjectProtocol, NSPoint, NSRect, NSSize, NSString, NSURL};
|
||||
use raw_window_handle::{HasWindowHandle, RawWindowHandle};
|
||||
use std::cell::Cell;
|
||||
use std::io;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// The size of each file's icon under the pointer, in points.
|
||||
const ICON_SIZE: f64 = 32.0;
|
||||
|
||||
/// Starts dragging `paths` (see [`super::local_paths`]) from `window`, each shown with its
|
||||
/// Finder icon; `done` runs on the main thread when the drag ends.
|
||||
pub fn start<W: HasWindowHandle>(
|
||||
window: &W,
|
||||
paths: Vec<PathBuf>,
|
||||
done: impl FnOnce(Outcome) + 'static,
|
||||
) -> io::Result<()> {
|
||||
let mtm = MainThreadMarker::new().ok_or_else(|| io::Error::other("a drag starts on the main thread"))?;
|
||||
let RawWindowHandle::AppKit(handle) =
|
||||
window.window_handle().map_err(|error| io::Error::other(error.to_string()))?.as_raw()
|
||||
else {
|
||||
return Err(io::Error::other("not an AppKit window"));
|
||||
};
|
||||
// SAFETY: the handle names this window's view, alive while `window` is borrowed.
|
||||
let view = unsafe { handle.ns_view.cast::<NSView>().as_ref() };
|
||||
let window = view.window().ok_or_else(|| io::Error::other("the view has no window"))?;
|
||||
let content = window.contentView().ok_or_else(|| io::Error::other("the window has no content view"))?;
|
||||
// In window coordinates, which are the content view's.
|
||||
let pointer = window.mouseLocationOutsideOfEventStream();
|
||||
let frame = NSRect::new(
|
||||
NSPoint::new(pointer.x - ICON_SIZE / 2.0, pointer.y - ICON_SIZE / 2.0),
|
||||
NSSize::new(ICON_SIZE, ICON_SIZE),
|
||||
);
|
||||
|
||||
let workspace = NSWorkspace::sharedWorkspace();
|
||||
let mut items = Vec::with_capacity(paths.len());
|
||||
for path in &paths {
|
||||
let path = NSString::from_str(&path.to_string_lossy());
|
||||
let url = NSURL::fileURLWithPath(&path)
|
||||
.absoluteString()
|
||||
.ok_or_else(|| io::Error::other(format!("not a file URL: {path}")))?;
|
||||
let item = NSPasteboardItem::new();
|
||||
if !item.setString_forType(&url, unsafe { NSPasteboardTypeFileURL }) {
|
||||
return Err(io::Error::other(format!("cannot put {path} on the pasteboard")));
|
||||
}
|
||||
let drag_item =
|
||||
NSDraggingItem::initWithPasteboardWriter(NSDraggingItem::alloc(), ProtocolObject::from_ref(&*item));
|
||||
let icon = workspace.iconForFile(&path);
|
||||
unsafe { drag_item.setDraggingFrame_contents(frame, Some(&icon)) };
|
||||
items.push(drag_item);
|
||||
}
|
||||
|
||||
// The session starts from a drag event at the pointer: the web view's own mouse events
|
||||
// went to WebKit, and the current event may be a later one.
|
||||
let timestamp = NSApplication::sharedApplication(mtm).currentEvent().map_or(0.0, |event| event.timestamp());
|
||||
let event = NSEvent::mouseEventWithType_location_modifierFlags_timestamp_windowNumber_context_eventNumber_clickCount_pressure(
|
||||
NSEventType::LeftMouseDragged,
|
||||
pointer,
|
||||
NSEventModifierFlags::empty(),
|
||||
timestamp,
|
||||
window.windowNumber(),
|
||||
None,
|
||||
0,
|
||||
1,
|
||||
1.0,
|
||||
)
|
||||
.ok_or_else(|| io::Error::other("cannot make the drag event"))?;
|
||||
let source = DragSource::new(Box::new(done), mtm);
|
||||
content.beginDraggingSessionWithItems_event_source(
|
||||
&NSArray::from_retained_slice(&items),
|
||||
&event,
|
||||
ProtocolObject::from_ref(&*source),
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
type Done = Box<dyn FnOnce(Outcome)>;
|
||||
|
||||
struct Ivars {
|
||||
done: Cell<Option<Done>>,
|
||||
}
|
||||
|
||||
define_class!(
|
||||
#[unsafe(super(NSObject))]
|
||||
#[thread_kind = MainThreadOnly]
|
||||
#[name = "OpenIdeaDragOutSource"]
|
||||
#[ivars = Ivars]
|
||||
struct DragSource;
|
||||
|
||||
unsafe impl NSObjectProtocol for DragSource {}
|
||||
|
||||
unsafe impl NSDraggingSource for DragSource {
|
||||
#[unsafe(method(draggingSession:sourceOperationMaskForDraggingContext:))]
|
||||
fn operation_mask(&self, session: &NSDraggingSession, _context: NSDraggingContext) -> NSDragOperation {
|
||||
session.setAnimatesToStartingPositionsOnCancelOrFail(true);
|
||||
NSDragOperation::Copy
|
||||
}
|
||||
|
||||
#[unsafe(method(draggingSession:endedAtPoint:operation:))]
|
||||
fn ended(&self, _session: &NSDraggingSession, _point: NSPoint, operation: NSDragOperation) {
|
||||
if let Some(done) = self.ivars().done.take() {
|
||||
done(if operation == NSDragOperation::None { Outcome::Cancelled } else { Outcome::Dropped });
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
impl DragSource {
|
||||
fn new(done: Done, mtm: MainThreadMarker) -> Retained<Self> {
|
||||
let this = Self::alloc(mtm).set_ivars(Ivars { done: Cell::new(Some(done)) });
|
||||
unsafe { msg_send![super(this), init] }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
//! OS file drags out of an app window: the app the files are dropped on (Explorer,
|
||||
//! Finder, a file manager, an SFTP client such as Xftp) copies them, as when they are
|
||||
//! dragged from IDEA's Project view (#2867).
|
||||
//!
|
||||
//! Linux starts a GTK drag offering `text/uri-list`, Windows an OLE `DoDragDrop` of a
|
||||
//! `CF_HDROP` data object, macOS an AppKit dragging session of file URLs. A drag is
|
||||
//! always a copy, never a move, so no target can take project files away.
|
||||
//!
|
||||
//! [`start`] runs on the UI thread while the primary button is still held. It returns
|
||||
//! once the drag has begun (Linux, macOS) or ended (Windows); `done` gets the outcome
|
||||
//! when it ends, or is dropped without being called when the backend lost track of it.
|
||||
|
||||
use std::io;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// How a drag ended.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Outcome {
|
||||
/// A target accepted the drop.
|
||||
Dropped,
|
||||
/// Released where nothing accepted it, or cancelled with Escape.
|
||||
Cancelled,
|
||||
}
|
||||
|
||||
/// The paths a drag may carry: at least one, each an absolute path to a file or folder
|
||||
/// on this machine. A remote project's paths name files on its server and fail here.
|
||||
/// Windows also refuses paths of `MAX_PATH` or more: Explorer can't copy from them.
|
||||
/// Network shares (`\\server\share\…`) are local paths here and drag like any other.
|
||||
pub fn local_paths<S: Into<PathBuf>>(paths: impl IntoIterator<Item = S>) -> io::Result<Vec<PathBuf>> {
|
||||
let paths: Vec<PathBuf> = paths.into_iter().map(Into::into).collect();
|
||||
if paths.is_empty() {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidInput, "no files to drag"));
|
||||
}
|
||||
for path in &paths {
|
||||
if !path.is_absolute() || std::fs::symlink_metadata(path).is_err() {
|
||||
return Err(io::Error::new(io::ErrorKind::NotFound, format!("not a local file: {}", path.display())));
|
||||
}
|
||||
if cfg!(windows) && !fits_max_path(path) {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
format!("path too long to drag: {}", path.display()),
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(paths)
|
||||
}
|
||||
|
||||
/// Whether `path` is shorter than Windows' `MAX_PATH` (260 UTF-16 units with the NUL).
|
||||
fn fits_max_path(path: &std::path::Path) -> bool {
|
||||
path.as_os_str().to_string_lossy().encode_utf16().count() < 260
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
pub use gtk_impl::start;
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
mod gtk_impl {
|
||||
use super::Outcome;
|
||||
use gtk::glib::{self, SignalHandlerId};
|
||||
use gtk::prelude::*;
|
||||
use gtk::{TargetList, gdk};
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::io;
|
||||
use std::path::PathBuf;
|
||||
use std::rc::Rc;
|
||||
|
||||
/// Starts dragging `paths` (see [`super::local_paths`]) from `window`; `done` runs on
|
||||
/// the UI thread when the drag ends.
|
||||
pub fn start(
|
||||
window: >k::ApplicationWindow,
|
||||
paths: Vec<PathBuf>,
|
||||
done: impl FnOnce(Outcome) + 'static,
|
||||
) -> io::Result<()> {
|
||||
// `file://` URIs with every reserved or non-ASCII byte escaped.
|
||||
let uris = paths
|
||||
.iter()
|
||||
.map(|path| glib::filename_to_uri(path, None).map(|uri| uri.to_string()))
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.map_err(|error| io::Error::new(io::ErrorKind::InvalidInput, error.to_string()))?;
|
||||
let targets = TargetList::new(&[]);
|
||||
targets.add_uri_targets(0);
|
||||
// The button that started the drag (1), not its mask: GTK ends the drag on that
|
||||
// button's release.
|
||||
let context = window
|
||||
.drag_begin_with_coordinates(&targets, gdk::DragAction::COPY, 1, None, -1, -1)
|
||||
.ok_or_else(|| io::Error::other("the window system refused to start a drag"))?;
|
||||
|
||||
let outcome = Rc::new(Cell::new(Outcome::Cancelled));
|
||||
context.connect_drop_performed({
|
||||
let outcome = outcome.clone();
|
||||
move |_, _| outcome.set(Outcome::Dropped)
|
||||
});
|
||||
let handlers: Rc<RefCell<Vec<SignalHandlerId>>> = Rc::default();
|
||||
let data = window.connect_drag_data_get({
|
||||
let context = context.clone();
|
||||
move |_, ctx, selection, _, _| {
|
||||
if *ctx == context {
|
||||
let uris: Vec<&str> = uris.iter().map(String::as_str).collect();
|
||||
selection.set_uris(&uris);
|
||||
}
|
||||
}
|
||||
});
|
||||
// The target asks for the data after the drop (XDND is asynchronous), so the data
|
||||
// handler stays connected until `drag-end`, which GTK emits last.
|
||||
let done = Cell::new(Some(done));
|
||||
let end = window.connect_drag_end({
|
||||
let handlers = handlers.clone();
|
||||
move |window, ctx| {
|
||||
if *ctx != context {
|
||||
return;
|
||||
}
|
||||
for handler in handlers.borrow_mut().drain(..) {
|
||||
window.disconnect(handler);
|
||||
}
|
||||
if let Some(done) = done.take() {
|
||||
done(outcome.get());
|
||||
}
|
||||
}
|
||||
});
|
||||
handlers.borrow_mut().extend([data, end]);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
mod ole;
|
||||
#[cfg(windows)]
|
||||
pub use ole::start;
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
mod appkit;
|
||||
#[cfg(target_os = "macos")]
|
||||
pub use appkit::start;
|
||||
|
||||
/// The `CF_HDROP` file list: each path in UTF-16 with `/` as `\\`, NUL-terminated, and a
|
||||
/// second NUL after the last.
|
||||
#[cfg(any(windows, test))]
|
||||
fn hdrop_file_list<P: IntoIterator<Item = u16>>(paths: impl IntoIterator<Item = P>) -> Vec<u16> {
|
||||
let mut list = Vec::new();
|
||||
for path in paths {
|
||||
list.extend(path.into_iter().map(|unit| if unit == u16::from(b'/') { u16::from(b'\\') } else { unit }));
|
||||
list.push(0);
|
||||
}
|
||||
list.push(0);
|
||||
list
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn accepts_existing_absolute_files_and_folders() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let file = dir.path().join("a b ü.txt");
|
||||
std::fs::write(&file, "x").unwrap();
|
||||
let paths = local_paths([file.clone(), dir.path().to_path_buf()]).unwrap();
|
||||
assert_eq!(paths, vec![file, dir.path().to_path_buf()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn measures_max_path_in_utf16_units() {
|
||||
let path = |len: usize| PathBuf::from(format!("C:/{}", "中".repeat(len - 3)));
|
||||
assert!(fits_max_path(&path(259)));
|
||||
assert!(!fits_max_path(&path(260)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lists_hdrop_files_double_nul_terminated() {
|
||||
let list = hdrop_file_list(["C:/a b/ü.txt", r"\\nas\share\中"].map(str::encode_utf16));
|
||||
let expected: Vec<u16> = "C:\\a b\\ü.txt\0\\\\nas\\share\\中\0\0".encode_utf16().collect();
|
||||
assert_eq!(list, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_an_empty_drag() {
|
||||
assert_eq!(local_paths(Vec::<PathBuf>::new()).unwrap_err().kind(), io::ErrorKind::InvalidInput);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_relative_and_missing_paths() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let file = dir.path().join("a.txt");
|
||||
std::fs::write(&file, "x").unwrap();
|
||||
// One path that is not local fails the whole drag: none of it is half-copied.
|
||||
for bad in [PathBuf::from("a.txt"), dir.path().join("missing.txt")] {
|
||||
assert_eq!(local_paths([file.clone(), bad]).unwrap_err().kind(), io::ErrorKind::NotFound);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
//! Windows: OLE `DoDragDrop` of a data object that serves the paths as `CF_HDROP`.
|
||||
|
||||
use super::{Outcome, hdrop_file_list};
|
||||
use raw_window_handle::HasWindowHandle;
|
||||
use std::io;
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
use std::path::PathBuf;
|
||||
use windows::Win32::Foundation::{
|
||||
DRAGDROP_S_CANCEL, DRAGDROP_S_DROP, DRAGDROP_S_USEDEFAULTCURSORS, DV_E_FORMATETC, E_NOTIMPL, GlobalFree, HGLOBAL,
|
||||
OLE_E_ADVISENOTSUPPORTED, S_OK,
|
||||
};
|
||||
use windows::Win32::System::Com::{
|
||||
DATADIR_GET, DVASPECT_CONTENT, FORMATETC, IAdviseSink, IDataObject, IDataObject_Impl, IEnumFORMATETC,
|
||||
IEnumSTATDATA, STGMEDIUM, STGMEDIUM_0, TYMED_HGLOBAL,
|
||||
};
|
||||
use windows::Win32::System::Memory::{GHND, GlobalAlloc, GlobalLock, GlobalUnlock};
|
||||
use windows::Win32::System::Ole::{
|
||||
CF_HDROP, DROPEFFECT, DROPEFFECT_COPY, DROPEFFECT_NONE, DoDragDrop, IDropSource, IDropSource_Impl, OleInitialize,
|
||||
OleUninitialize,
|
||||
};
|
||||
use windows::Win32::System::SystemServices::{MK_LBUTTON, MODIFIERKEYS_FLAGS};
|
||||
use windows::Win32::UI::Shell::{DROPFILES, SHCreateDataObject, SHCreateStdEnumFmtEtc};
|
||||
use windows::core::{BOOL, Error, HRESULT, Ref, Result, implement};
|
||||
|
||||
/// Drags `paths` (see [`super::local_paths`]) until the button is released, then calls
|
||||
/// `done` and returns. `DoDragDrop` runs its own message loop, so the window keeps painting.
|
||||
pub fn start<W: HasWindowHandle>(
|
||||
_window: &W,
|
||||
paths: Vec<PathBuf>,
|
||||
done: impl FnOnce(Outcome) + 'static,
|
||||
) -> io::Result<()> {
|
||||
let files = hdrop_file_list(paths.iter().map(|path| path.as_os_str().encode_wide()));
|
||||
// The window's event loop has initialised OLE on this thread already; this takes a
|
||||
// reference that `OleUninitialize` gives back.
|
||||
unsafe { OleInitialize(None) }.map_err(io::Error::other)?;
|
||||
let outcome = drag(files);
|
||||
unsafe { OleUninitialize() };
|
||||
done(outcome.map_err(io::Error::other)?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn drag(files: Vec<u16>) -> Result<Outcome> {
|
||||
// Formats other than `CF_HDROP` (the drag image, drop descriptions the shell sets on
|
||||
// the source's data object) are kept by a plain shell data object.
|
||||
let inner: IDataObject = unsafe { SHCreateDataObject(None, None, None::<&IDataObject>) }?;
|
||||
let data: IDataObject = DataObject { files, inner }.into();
|
||||
let source: IDropSource = DropSource.into();
|
||||
let mut effect = DROPEFFECT_NONE;
|
||||
match unsafe { DoDragDrop(&data, &source, DROPEFFECT_COPY, &mut effect) } {
|
||||
DRAGDROP_S_DROP if effect != DROPEFFECT_NONE => Ok(Outcome::Dropped),
|
||||
DRAGDROP_S_DROP | DRAGDROP_S_CANCEL => Ok(Outcome::Cancelled),
|
||||
error => Err(Error::from_hresult(error)),
|
||||
}
|
||||
}
|
||||
|
||||
#[implement(IDropSource)]
|
||||
struct DropSource;
|
||||
|
||||
impl IDropSource_Impl for DropSource_Impl {
|
||||
fn QueryContinueDrag(&self, escape_pressed: BOOL, keys: MODIFIERKEYS_FLAGS) -> HRESULT {
|
||||
if escape_pressed.as_bool() {
|
||||
DRAGDROP_S_CANCEL
|
||||
} else if keys & MK_LBUTTON == MODIFIERKEYS_FLAGS(0) {
|
||||
DRAGDROP_S_DROP
|
||||
} else {
|
||||
S_OK
|
||||
}
|
||||
}
|
||||
|
||||
fn GiveFeedback(&self, _effect: DROPEFFECT) -> HRESULT {
|
||||
DRAGDROP_S_USEDEFAULTCURSORS
|
||||
}
|
||||
}
|
||||
|
||||
#[implement(IDataObject)]
|
||||
struct DataObject {
|
||||
/// The `DROPFILES` file list ([`hdrop_file_list`]).
|
||||
files: Vec<u16>,
|
||||
inner: IDataObject,
|
||||
}
|
||||
|
||||
const HDROP: FORMATETC = FORMATETC {
|
||||
cfFormat: CF_HDROP.0,
|
||||
ptd: std::ptr::null_mut(),
|
||||
dwAspect: DVASPECT_CONTENT.0,
|
||||
lindex: -1,
|
||||
tymed: TYMED_HGLOBAL.0 as u32,
|
||||
};
|
||||
|
||||
fn is_hdrop(format: *const FORMATETC) -> bool {
|
||||
unsafe { format.as_ref() }.is_some_and(|format| {
|
||||
format.cfFormat == HDROP.cfFormat && format.dwAspect == HDROP.dwAspect && format.tymed & HDROP.tymed != 0
|
||||
})
|
||||
}
|
||||
|
||||
impl DataObject {
|
||||
/// A new `DROPFILES` block; the receiver frees it.
|
||||
fn hdrop(&self) -> Result<HGLOBAL> {
|
||||
let header = size_of::<DROPFILES>();
|
||||
let size = header + std::mem::size_of_val(self.files.as_slice());
|
||||
unsafe {
|
||||
let handle = GlobalAlloc(GHND, size)?;
|
||||
let block = GlobalLock(handle).cast::<u8>();
|
||||
if block.is_null() {
|
||||
let error = Error::from_thread();
|
||||
let _ = GlobalFree(Some(handle));
|
||||
return Err(error);
|
||||
}
|
||||
block.cast::<DROPFILES>().write_unaligned(DROPFILES {
|
||||
pFiles: header as u32,
|
||||
fWide: true.into(),
|
||||
..Default::default()
|
||||
});
|
||||
std::ptr::copy_nonoverlapping(self.files.as_ptr().cast::<u8>(), block.add(header), size - header);
|
||||
// Fails with no error once the lock count is back to zero, which it is.
|
||||
let _ = GlobalUnlock(handle);
|
||||
Ok(handle)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl IDataObject_Impl for DataObject_Impl {
|
||||
fn GetData(&self, format: *const FORMATETC) -> Result<STGMEDIUM> {
|
||||
if !is_hdrop(format) {
|
||||
return unsafe { self.inner.GetData(format) };
|
||||
}
|
||||
Ok(STGMEDIUM {
|
||||
tymed: TYMED_HGLOBAL.0 as u32,
|
||||
u: STGMEDIUM_0 { hGlobal: self.hdrop()? },
|
||||
pUnkForRelease: std::mem::ManuallyDrop::new(None),
|
||||
})
|
||||
}
|
||||
|
||||
fn GetDataHere(&self, format: *const FORMATETC, medium: *mut STGMEDIUM) -> Result<()> {
|
||||
if is_hdrop(format) {
|
||||
return Err(DV_E_FORMATETC.into());
|
||||
}
|
||||
unsafe { self.inner.GetDataHere(format, medium) }
|
||||
}
|
||||
|
||||
fn QueryGetData(&self, format: *const FORMATETC) -> HRESULT {
|
||||
if is_hdrop(format) { S_OK } else { unsafe { self.inner.QueryGetData(format) } }
|
||||
}
|
||||
|
||||
fn GetCanonicalFormatEtc(&self, format: *const FORMATETC, canonical: *mut FORMATETC) -> HRESULT {
|
||||
unsafe { self.inner.GetCanonicalFormatEtc(format, canonical) }
|
||||
}
|
||||
|
||||
fn SetData(&self, format: *const FORMATETC, medium: *const STGMEDIUM, release: BOOL) -> Result<()> {
|
||||
unsafe { self.inner.SetData(format, medium, release.as_bool()) }
|
||||
}
|
||||
|
||||
fn EnumFormatEtc(&self, direction: u32) -> Result<IEnumFORMATETC> {
|
||||
if direction != DATADIR_GET.0 as u32 {
|
||||
return Err(E_NOTIMPL.into());
|
||||
}
|
||||
unsafe { SHCreateStdEnumFmtEtc(&[HDROP]) }
|
||||
}
|
||||
|
||||
fn DAdvise(&self, _format: *const FORMATETC, _advf: u32, _sink: Ref<IAdviseSink>) -> Result<u32> {
|
||||
Err(OLE_E_ADVISENOTSUPPORTED.into())
|
||||
}
|
||||
|
||||
fn DUnadvise(&self, _connection: u32) -> Result<()> {
|
||||
Err(OLE_E_ADVISENOTSUPPORTED.into())
|
||||
}
|
||||
|
||||
fn EnumDAdvise(&self) -> Result<IEnumSTATDATA> {
|
||||
Err(OLE_E_ADVISENOTSUPPORTED.into())
|
||||
}
|
||||
}
|
||||
@@ -5,10 +5,10 @@ use crate::Host;
|
||||
use crate::agent_secrets::{AgentSecrets, Kept};
|
||||
use ide_agent::registry::{AgentRegistry, RegistryPaths};
|
||||
use ide_agent::{
|
||||
AcpImportOutcome, AgentAcceptOutcome, AgentChange, AgentChanges, AgentChangesView, AgentCommand, AgentContextUsage,
|
||||
AgentEntry, AgentEvent, AgentModelCatalog, AgentProbe, AgentPrompt, AgentProvider, AgentQueued, AgentTask,
|
||||
CustomAgentInput, ExternalSession, McpExternalSource, McpImportSelection, McpProbeResult, McpScope, McpServer,
|
||||
McpServerInput, McpTransport, NewAgentTask,
|
||||
AcpImportOutcome, AgentAcceptOutcome, AgentChange, AgentChanges, AgentChangesView, AgentCliOffer,
|
||||
AgentCliUpdateResult, AgentCommand, AgentContextUsage, AgentEntry, AgentEvent, AgentModelCatalog, AgentProbe,
|
||||
AgentPrompt, AgentProvider, AgentQueued, AgentTask, CustomAgentInput, ExternalSession, McpExternalSource,
|
||||
McpImportSelection, McpProbeResult, McpScope, McpServer, McpServerInput, McpTransport, NewAgentTask,
|
||||
};
|
||||
use ide_command::command;
|
||||
use ide_core::error::ErrorKind;
|
||||
@@ -359,6 +359,50 @@ pub async fn agent_rollback(host: &Host, window: &str, task: String, turns: u32)
|
||||
host.project(window)?.agents.rollback(&task, turns).await
|
||||
}
|
||||
|
||||
/// Checks the selected installation without modifying it.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn agent_cli_update_check(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
provider: String,
|
||||
request: RequestId,
|
||||
) -> IdeResult<AgentCliUpdateResult> {
|
||||
cli_update(host, window, provider, None, request).await
|
||||
}
|
||||
|
||||
/// Installs the exact version offered if the selected installation still matches.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn agent_cli_update(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
provider: String,
|
||||
offer: AgentCliOffer,
|
||||
request: RequestId,
|
||||
) -> IdeResult<AgentCliUpdateResult> {
|
||||
cli_update(host, window, provider, Some(offer), request).await
|
||||
}
|
||||
|
||||
async fn cli_update(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
provider: String,
|
||||
offer: Option<AgentCliOffer>,
|
||||
request: RequestId,
|
||||
) -> IdeResult<AgentCliUpdateResult> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
let installing = offer.as_ref().map(|_| Installing::begin(&provider)).transpose()?;
|
||||
let cancel = host.begin_project_request(window, request);
|
||||
let result = tokio::task::spawn_blocking(move || {
|
||||
let _installing = installing;
|
||||
project.agents.cli_update(&provider, offer.as_ref(), &cancel)
|
||||
})
|
||||
.await
|
||||
.map_err(join_err);
|
||||
host.end_request(request);
|
||||
result?
|
||||
}
|
||||
|
||||
/// What the agent reports about itself when it starts (no session: no MCP servers, hooks
|
||||
/// or sign-in run). Remembered until `refresh`.
|
||||
#[command(trust = trusted)]
|
||||
@@ -1102,6 +1146,8 @@ ide_command::domain!(
|
||||
agent_cancel,
|
||||
agent_context_usage,
|
||||
agent_changes,
|
||||
agent_cli_update,
|
||||
agent_cli_update_check,
|
||||
agent_commands,
|
||||
agent_create,
|
||||
agent_delete,
|
||||
|
||||
@@ -13,6 +13,9 @@ const FILES: TableDefinition<&str, &[u8]> = TableDefinition::new("files");
|
||||
const META: TableDefinition<&str, &[u8]> = TableDefinition::new("meta");
|
||||
/// Bump when [`FileRecord`] or its encoding changes. 4: a symbol's base names.
|
||||
const SCHEMA: &str = "openidea-index-4";
|
||||
/// redb's page cache, which otherwise grows to 1 GiB. Queries run on the in-memory snapshot;
|
||||
/// the database is read once at startup and written incrementally.
|
||||
const DB_CACHE_BYTES: usize = 64 * 1024 * 1024;
|
||||
|
||||
/// The real Git directory for a checkout/worktree (`root/.git` may be a file
|
||||
/// containing `gitdir: ...`).
|
||||
@@ -389,7 +392,7 @@ impl Store {
|
||||
|
||||
fn open_db(&self) -> Result<Database> {
|
||||
let file = self.snapshot.with_file_name("index.redb");
|
||||
let db = match Database::create(&file) {
|
||||
let db = match Database::builder().set_cache_size(DB_CACHE_BYTES).create(&file) {
|
||||
Ok(db) => db,
|
||||
Err(redb::DatabaseError::DatabaseAlreadyOpen) => {
|
||||
return Err(format!("{} is in use", file.display()));
|
||||
@@ -398,7 +401,7 @@ impl Store {
|
||||
tracing::warn!("index cache {} unreadable ({e}); rebuilding", file.display());
|
||||
let _ = std::fs::remove_file(&file);
|
||||
let _ = std::fs::remove_file(&self.snapshot);
|
||||
Database::create(&file).map_err(err)?
|
||||
Database::builder().set_cache_size(DB_CACHE_BYTES).create(&file).map_err(err)?
|
||||
}
|
||||
};
|
||||
let valid = {
|
||||
|
||||
@@ -472,6 +472,8 @@ impl Shared {
|
||||
|
||||
fn full_scan(&self, found: Option<Vec<Found>>, guard: SystemTime) {
|
||||
self.scan(None, found, guard);
|
||||
// Parsing every file churns through far more memory than the index keeps.
|
||||
ide_core::memory::release_free_pages();
|
||||
}
|
||||
|
||||
fn scan(&self, dirs: Option<&[PathBuf]>, prewalked: Option<Vec<Found>>, guard: SystemTime) -> Option<ScanCounts> {
|
||||
|
||||
@@ -197,28 +197,62 @@ fn software_term(lower: &str) -> bool {
|
||||
.is_some_and(|w| ["s", "x", "z", "ch", "sh"].iter().any(|e| w.ends_with(e)) && plural_of(w))
|
||||
}
|
||||
|
||||
/// Words of a custom dictionary file: a plain word list or a Hunspell `.dic`
|
||||
/// (leading count line and `/FLAGS` ignored). Cached by modification time.
|
||||
fn dictionary_file(path: &Path) -> Arc<HashSet<String>> {
|
||||
type Cache = HashMap<PathBuf, (Option<SystemTime>, Arc<HashSet<String>>)>;
|
||||
static CACHE: OnceLock<Mutex<Cache>> = OnceLock::new();
|
||||
let modified = std::fs::metadata(path).and_then(|m| m.modified()).ok();
|
||||
let mut cache = CACHE.get_or_init(Default::default).lock();
|
||||
if let Some((at, words)) = cache.get(path)
|
||||
&& *at == modified
|
||||
{
|
||||
return words.clone();
|
||||
}
|
||||
let words: HashSet<String> = match std::fs::read_to_string(path) {
|
||||
Ok(text) => parse_word_list(&text),
|
||||
Err(e) => {
|
||||
tracing::debug!("custom dictionary {}: {e}", path.display());
|
||||
HashSet::new()
|
||||
/// A custom dictionary: a word list, or a Hunspell dictionary with its affix rules.
|
||||
enum CustomDictionary {
|
||||
Words(HashSet<String>),
|
||||
Hunspell(Box<spellbook::Dictionary>),
|
||||
}
|
||||
|
||||
impl CustomDictionary {
|
||||
/// Whether the lowercased `lower` is a word of it, in any case style.
|
||||
fn contains(&self, lower: &str) -> bool {
|
||||
match self {
|
||||
Self::Words(words) => words.contains(lower),
|
||||
Self::Hunspell(dict) => {
|
||||
dict.check(lower) || dict.check(&capitalize(lower)) || dict.check(&lower.to_uppercase())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The `.aff` next to a Hunspell `.dic` (`de_DE.dic` → `de_DE.aff`), if there is one.
|
||||
fn affix_file(path: &Path) -> Option<PathBuf> {
|
||||
if !path.extension().is_some_and(|e| e.eq_ignore_ascii_case("dic")) {
|
||||
return None;
|
||||
}
|
||||
["aff", "AFF"].into_iter().map(|ext| path.with_extension(ext)).find(|aff| aff.is_file())
|
||||
}
|
||||
|
||||
/// A custom dictionary file: a Hunspell `.dic` with the `.aff` beside it, with
|
||||
/// its affix, compounding and case rules; otherwise a plain word list (a `.dic`
|
||||
/// alone: leading count line and `/FLAGS` ignored). Cached by modification time.
|
||||
fn dictionary_file(path: &Path) -> Arc<CustomDictionary> {
|
||||
type Stamp = (Option<SystemTime>, Option<SystemTime>);
|
||||
type Cache = HashMap<PathBuf, (Stamp, Arc<CustomDictionary>)>;
|
||||
static CACHE: OnceLock<Mutex<Cache>> = OnceLock::new();
|
||||
let modified = |p: &Path| std::fs::metadata(p).and_then(|m| m.modified()).ok();
|
||||
let aff = affix_file(path);
|
||||
let stamp = (modified(path), aff.as_deref().and_then(modified));
|
||||
if let Some((at, dict)) = CACHE.get_or_init(Default::default).lock().get(path)
|
||||
&& *at == stamp
|
||||
{
|
||||
return dict.clone();
|
||||
}
|
||||
let read = |p: &Path| {
|
||||
std::fs::read_to_string(p).map_err(|e| tracing::debug!("custom dictionary {}: {e}", p.display())).ok()
|
||||
};
|
||||
let words = Arc::new(words);
|
||||
cache.insert(path.to_path_buf(), (modified, words.clone()));
|
||||
words
|
||||
let text = read(path).unwrap_or_default();
|
||||
let hunspell = aff.as_deref().and_then(read).and_then(|aff| {
|
||||
spellbook::Dictionary::new(&aff, &text)
|
||||
.map_err(|e| tracing::warn!("Hunspell dictionary {}: {e}", path.display()))
|
||||
.ok()
|
||||
});
|
||||
let dict = Arc::new(match hunspell {
|
||||
Some(dict) => CustomDictionary::Hunspell(Box::new(dict)),
|
||||
None => CustomDictionary::Words(parse_word_list(&text)),
|
||||
});
|
||||
CACHE.get_or_init(Default::default).lock().insert(path.to_path_buf(), (stamp, dict.clone()));
|
||||
dict
|
||||
}
|
||||
|
||||
/// Lowercased words of a word list / Hunspell `.dic` text.
|
||||
@@ -238,7 +272,7 @@ pub fn parse_word_list(text: &str) -> HashSet<String> {
|
||||
#[derive(Default)]
|
||||
pub struct Speller {
|
||||
accepted: HashSet<String>,
|
||||
custom: Vec<Arc<HashSet<String>>>,
|
||||
custom: Vec<Arc<CustomDictionary>>,
|
||||
}
|
||||
|
||||
impl Speller {
|
||||
@@ -351,16 +385,31 @@ impl Speller {
|
||||
&& !near_word(lower, |w| english().check(w))
|
||||
}
|
||||
|
||||
/// Replacements for `word`, best first, in the word's case style.
|
||||
/// Replacements for `word`, best first, in the word's case style: from the
|
||||
/// English dictionary and the custom Hunspell dictionaries, the closest first.
|
||||
pub fn suggest(&self, word: &str, limit: usize) -> Vec<String> {
|
||||
let hunspell = self.custom.iter().filter_map(|d| match d.as_ref() {
|
||||
CustomDictionary::Hunspell(dict) => Some(dict.as_ref()),
|
||||
CustomDictionary::Words(_) => None,
|
||||
});
|
||||
let dicts: Vec<&spellbook::Dictionary> = std::iter::once(english()).chain(hunspell).collect();
|
||||
let mut out = Vec::new();
|
||||
english().suggest(word, &mut out);
|
||||
if out.is_empty() && word.chars().next().is_some_and(char::is_uppercase) {
|
||||
english().suggest(&word.to_lowercase(), &mut out);
|
||||
out = out.into_iter().map(|s| capitalize(&s)).collect();
|
||||
for dict in &dicts {
|
||||
let mut found = Vec::new();
|
||||
dict.suggest(word, &mut found);
|
||||
if found.is_empty() && word.chars().next().is_some_and(char::is_uppercase) {
|
||||
dict.suggest(&word.to_lowercase(), &mut found);
|
||||
found = found.into_iter().map(|s| capitalize(&s)).collect();
|
||||
}
|
||||
out.extend(found);
|
||||
}
|
||||
let mut seen = HashSet::new();
|
||||
out.retain(|s| s != word && seen.insert(s.clone()));
|
||||
if dicts.len() > 1 {
|
||||
// Stable: within a distance each dictionary keeps its own order, English first.
|
||||
let lower = word.to_lowercase();
|
||||
out.sort_by_key(|s| edit_distance(&lower, &s.to_lowercase()));
|
||||
}
|
||||
out.truncate(limit);
|
||||
out
|
||||
}
|
||||
@@ -416,6 +465,22 @@ impl Speller {
|
||||
}
|
||||
}
|
||||
|
||||
/// Levenshtein distance in characters.
|
||||
fn edit_distance(a: &str, b: &str) -> usize {
|
||||
let b: Vec<char> = b.chars().collect();
|
||||
let mut row: Vec<usize> = (0..=b.len()).collect();
|
||||
for (i, ca) in a.chars().enumerate() {
|
||||
let mut diagonal = row[0];
|
||||
row[0] = i + 1;
|
||||
for (j, cb) in b.iter().enumerate() {
|
||||
let next = (row[j + 1] + 1).min(row[j] + 1).min(diagonal + usize::from(ca != *cb));
|
||||
diagonal = row[j + 1];
|
||||
row[j + 1] = next;
|
||||
}
|
||||
}
|
||||
row[b.len()]
|
||||
}
|
||||
|
||||
fn capitalize(s: &str) -> String {
|
||||
let mut chars = s.chars();
|
||||
chars.next().into_iter().flat_map(char::to_uppercase).chain(chars).collect()
|
||||
@@ -736,6 +801,36 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hunspell_custom_dictionaries_use_their_affix_rules() {
|
||||
let dir = std::env::temp_dir().join(format!("ide-spell-hunspell-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let dic = dir.join("de_TEST.dic");
|
||||
std::fs::write(&dic, "3\nhaus/NZ\ntür/NZ\nschlüssel/Z\n").unwrap();
|
||||
std::fs::write(
|
||||
dir.join("de_TEST.aff"),
|
||||
"SET UTF-8\nTRY esianrtolcdugmphbyfvkwzäöüß\nCOMPOUNDFLAG Z\nSFX N Y 1\nSFX N 0 en .\n",
|
||||
)
|
||||
.unwrap();
|
||||
let s = Speller::new::<&str>([], std::slice::from_ref(&dic));
|
||||
// Affix rules, compounds and case styles of the .aff, not just the listed stems.
|
||||
for word in ["haus", "Haus", "hausen", "türen", "Haustür", "schlüsselhaus"] {
|
||||
assert!(s.is_correct(word), "{word}");
|
||||
}
|
||||
assert!(!s.is_correct("hauz"));
|
||||
assert!(!s.is_correct("schlüsselen"));
|
||||
assert!(s.suggest("Hauss", 5).iter().any(|w| w == "Haus"), "{:?}", s.suggest("Hauss", 5));
|
||||
// English still checks and suggests.
|
||||
assert!(s.is_correct("message"));
|
||||
assert!(s.suggest("mesage", 5).iter().any(|w| w == "message"));
|
||||
// Without its .aff, a .dic is a word list.
|
||||
std::fs::remove_file(dir.join("de_TEST.aff")).unwrap();
|
||||
let words = Speller::new::<&str>([], std::slice::from_ref(&dic));
|
||||
assert!(words.is_correct("haus"));
|
||||
assert!(!words.is_correct("hausen"));
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn utf16_ranges() {
|
||||
let s = Speller::default();
|
||||
|
||||
@@ -19,6 +19,9 @@ const MESSAGES: TableDefinition<&str, &str> = TableDefinition::new("messages-v1"
|
||||
const MAX_MEMORY_COMMITS: usize = 4096;
|
||||
const MAX_MEMORY_MESSAGES: usize = 1024;
|
||||
const MAX_DIRTY_BATCH: usize = 16_384;
|
||||
/// redb's page cache, which otherwise grows to 1 GiB per repository. Hot commits are already
|
||||
/// kept in `memory`.
|
||||
const DB_CACHE_BYTES: usize = 32 * 1024 * 1024;
|
||||
|
||||
pub(crate) struct IndexedRow {
|
||||
pub id: ObjectId,
|
||||
@@ -269,7 +272,11 @@ impl LogIndex {
|
||||
let path = dir.join("commits.redb");
|
||||
let mut databases = DATABASES.get_or_init(Mutex::default).lock().unwrap_or_else(|p| p.into_inner());
|
||||
self.db = databases.get(&path).and_then(Weak::upgrade).or_else(|| {
|
||||
let db = Arc::new(std::fs::create_dir_all(dir).ok().and_then(|_| Database::create(&path).ok())?);
|
||||
let db = Arc::new(
|
||||
std::fs::create_dir_all(dir)
|
||||
.ok()
|
||||
.and_then(|_| Database::builder().set_cache_size(DB_CACHE_BYTES).create(&path).ok())?,
|
||||
);
|
||||
drop_stale_tables(&db);
|
||||
databases.insert(path, Arc::downgrade(&db));
|
||||
Some(db)
|
||||
|
||||
@@ -86,6 +86,7 @@ Each crate's `lib.rs` opens with a module doc comment describing its contract; r
|
||||
| -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `ide-cli` | The `openidea` command: argument parsing, the request it sends to a running app over a local socket, installing it on `PATH`. |
|
||||
| `ide-clipboard` | The OS clipboard's file list (Windows `CF_HDROP`, macOS `NSPasteboard` file URLs) for copying files between the Project view and the file manager. |
|
||||
| `ide-drag-out` | OS file drags out of a window (GTK, OLE, AppKit), so files dragged from the Project view to another app are copied there. |
|
||||
| `ide-fonts` | Installed font families for the font pickers, via CoreText, DirectWrite or fontconfig. |
|
||||
| `src-tauri` (package `openidea`) | The desktop shell: `AppState`, Tauri commands, the event sink, windows, menus, the remote-development client, the `openidea-plugin` URL scheme for plugin web views. Glue only. |
|
||||
|
||||
|
||||
@@ -125,7 +125,7 @@ Tasks are saved per project and survive restarts. When the agent supports resumi
|
||||
|
||||
**Settings › Tools › Agents** (also **More Agents…** in the agent picker) has two tabs:
|
||||
|
||||
- **Built-in**: for each built-in agent, whether its executable was found on `PATH`, a field to point at a **Custom executable**, **Environment variables** for the agent process (written as `NAME=value; OTHER=value`; the values are kept in the OS credential store) and how to sign in. Changes apply to new sessions.
|
||||
- **Built-in**: for each built-in agent, whether its executable was found on `PATH`, a field to point at a **Custom executable**, **Environment variables** for the agent process (written as `NAME=value; OTHER=value`; the values are kept in the OS credential store) and how to sign in. Changes apply to new sessions. When the agent is a global npm install (such as Claude Code, Codex or Gemini CLI), **Check for updates** compares it with npm's latest stable release and **Update to…** updates that installation.
|
||||
- **ACP Registry**: agents published in the [ACP Registry](https://agentclientprotocol.com). Search, **Install**, **Update** and **Remove**. Installed agents are kept in OpenIDEA's data directory; downloads are checked against the registry's SHA-256 when it provides one.
|
||||
|
||||
**Settings › Tools › Agents › Chat** chooses what the task header shows: **Context window usage**, **Time spent on the task**, **Usage limits** (when the agent reports them, such as Claude Code) and **Session cost**.
|
||||
|
||||
@@ -112,7 +112,7 @@ The debugger adds attach-only types such as **Remote JVM Debug**, **Go Remote**,
|
||||
### Common fields
|
||||
|
||||
- **Run on**: the local machine, or an SSH host defined in **Settings › Build, Execution, Deployment › Run Targets**. Debugging is not available on run targets. See [SSH](/en/guide/remote/ssh).
|
||||
- **Working directory**: relative to the project root; empty means the project root.
|
||||
- **Working directory**: relative to the project root; empty means the project root. It may use the path macros `$PROJECT_DIR$`, `$ContentRoot$`, `$MODULE_DIR$`, `$MODULE_WORKING_DIR$` and `$USER_HOME$`, expanded when the configuration starts, so a shared configuration works on every machine.
|
||||
- **Environment variables**: `VAR=value` pairs separated by `;`. The list button opens the **Environment Variables** dialog, where **Include system environment variables** can be turned off.
|
||||
- **Debug adapter**: which debugger **Debug** uses for this configuration (for example `debugpy`, `js-debug`, `codelldb`, `delve`).
|
||||
|
||||
|
||||
@@ -23,7 +23,7 @@ Only types you add appear here: choose **Add Service › Run Configuration Type*
|
||||
- Configuration actions: **Run** (or **Rerun**), **Debug**, **Stop**, **Open in Browser**, **Update Application** (for configurations that support it).
|
||||
- Context menu: **Show in Run Tool Window**, **Show in Debug Tool Window**, **Edit Configuration…**, **Remove from Services**.
|
||||
|
||||
A configuration that ran shows its console in the detail pane. Reorder configurations within a group by dragging them or with **Move Up** / **Move Down**; the order is saved per project.
|
||||
A configuration that ran shows its console in the detail pane; one debugged from here shows the whole debugger there (Threads & Variables, Console, Memory), and a breakpoint keeps the Services tool window in front. Reorder configurations within a group by dragging them or with **Move Up** / **Move Down**; the order is saved per project.
|
||||
|
||||
## Docker
|
||||
|
||||
|
||||
@@ -86,6 +86,7 @@ Cargo workspace 由 `crates/*` 加 `src-tauri` 组成(见根目录 `Cargo.toml
|
||||
| ------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `ide-cli` | `openidea` 命令:参数解析、通过本地 socket 发给运行中应用的请求、安装到 `PATH`。 |
|
||||
| `ide-clipboard` | 操作系统剪贴板里的文件列表(Windows `CF_HDROP`、macOS `NSPasteboard` 文件 URL),用于 Project 视图与文件管理器之间复制文件。 |
|
||||
| `ide-drag-out` | 从窗口发起操作系统文件拖放(GTK、OLE、AppKit),从 Project 视图拖到其他程序的文件由该程序复制。 |
|
||||
| `ide-fonts` | 已安装的字体族,供字体选择器使用,分别通过 CoreText、DirectWrite 或 fontconfig 获取。 |
|
||||
| `src-tauri`(包名 `openidea`) | 桌面外壳:`AppState`、Tauri 命令、事件 sink、窗口、菜单、远程开发客户端、插件 Web 视图用的 `openidea-plugin` URL scheme。只做胶水。 |
|
||||
|
||||
|
||||
@@ -125,7 +125,7 @@ agent 运行过一个任务后,新任务会以它自动批准所有操作的
|
||||
|
||||
**设置 › 工具 › 智能体**(也可以在 agent 选择器中点 **更多 Agent…**)有两个标签页:
|
||||
|
||||
- **内置**:每个内置 agent 的可执行文件是否在 `PATH` 中找到、指定 **自定义可执行文件** 的输入框、传给 agent 进程的 **环境变量**(格式为 `NAME=value; OTHER=value`;这些值保存在系统凭据存储中)以及登录方式。改动对新会话生效。
|
||||
- **内置**:每个内置 agent 的可执行文件是否在 `PATH` 中找到、指定 **自定义可执行文件** 的输入框、传给 agent 进程的 **环境变量**(格式为 `NAME=value; OTHER=value`;这些值保存在系统凭据存储中)以及登录方式。改动对新会话生效。如果 agent 是 npm 全局安装(例如 Claude Code、Codex、Gemini CLI),**检查更新** 会与 npm 的最新稳定版比较,点击 **更新至…** 即可更新这份安装。
|
||||
- **ACP 注册表**:[ACP Registry](https://agentclientprotocol.com) 中发布的 agent,可以搜索、**安装**、**更新** 和 **移除**。安装的 agent 保存在 OpenIDEA 的数据目录中;注册表提供 SHA-256 时会校验下载内容。
|
||||
|
||||
**设置 › 工具 › 智能体 › 聊天** 决定任务标题栏显示哪些信息:**上下文窗口用量**、**任务耗时**、**用量限额**(agent 报告时,例如 Claude Code)和 **会话花费**。
|
||||
|
||||
@@ -108,7 +108,7 @@ description: "创建、编辑和启动运行配置,从装订区运行代码,
|
||||
### 通用字段
|
||||
|
||||
- **运行于**:本地计算机,或在 **设置 › 构建、执行、部署 › 运行目标** 中添加的 SSH 主机。运行目标上不支持调试。参见 [SSH](/zh/guide/remote/ssh)。
|
||||
- **工作目录**:相对于项目根目录,留空即项目根目录。
|
||||
- **工作目录**:相对于项目根目录,留空即项目根目录。可以使用路径宏 `$PROJECT_DIR$`、`$ContentRoot$`、`$MODULE_DIR$`、`$MODULE_WORKING_DIR$` 和 `$USER_HOME$`,在配置启动时展开,因此共享的配置在每台机器上都能用。
|
||||
- **环境变量**:`VAR=value` 形式,用 `;` 分隔。点旁边的列表按钮打开“环境变量”对话框,可以关闭 **包括系统环境变量**。
|
||||
- **调试适配器**:按“调试”时这个配置使用哪个调试器(如 `debugpy`、`js-debug`、`codelldb`、`delve`)。
|
||||
|
||||
|
||||
@@ -23,7 +23,7 @@ description: "在服务工具窗口中管理运行配置、Docker 容器、镜
|
||||
- 配置操作:**运行**(或 **重新运行**)、**调试**、**停止**、**在浏览器中打开**、**更新应用**(仅支持的配置)。
|
||||
- 右键菜单:**在运行工具窗口中显示**、**在调试工具窗口中显示**、**编辑配置…**、**从服务中移除**。
|
||||
|
||||
运行过的配置会在详情区显示其控制台。在同一分组内可以拖动或用 **上移** / **下移** 调整顺序,顺序按项目保存。
|
||||
运行过的配置会在详情区显示其控制台;从这里调试的配置在详情区显示完整的调试器(线程和变量、控制台、内存),命中断点时停留在服务工具窗口。在同一分组内可以拖动或用 **上移** / **下移** 调整顺序,顺序按项目保存。
|
||||
|
||||
## Docker
|
||||
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
import type { AgentEntry, AgentTask } from "../src/bindings";
|
||||
import { expect, test } from "./fixtures";
|
||||
|
||||
const first: AgentTask = {
|
||||
id: "context-first",
|
||||
title: "First conversation",
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
isolation: "local",
|
||||
model: null,
|
||||
cwd: "/dev/acme-api",
|
||||
branch: null,
|
||||
base: null,
|
||||
baseCommit: null,
|
||||
error: null,
|
||||
createdMs: 0,
|
||||
updatedMs: 0,
|
||||
config: [],
|
||||
commands: [],
|
||||
usage: null,
|
||||
queue: [],
|
||||
};
|
||||
const second: AgentTask = { ...first, id: "context-second", title: "Second conversation" };
|
||||
|
||||
for (const active of ["conversation", "file"] as const) {
|
||||
test(`an agent context menu keeps the current ${active} open`, async ({ workbench: page }) => {
|
||||
await page.getByRole("treeitem", { name: "README.md", exact: true }).dblclick();
|
||||
await expect(page.getByRole("tab", { name: "README.md", exact: true })).toBeVisible();
|
||||
await page.evaluate(
|
||||
async ({ first, second }) => {
|
||||
const storePath = "/src/features/agents/store.ts";
|
||||
const ipcPath = "/src/platform/ipc.ts";
|
||||
const contributionsPath = "/src/workbench/contributions.ts";
|
||||
const store = await import(storePath);
|
||||
const { commands } = await import(ipcPath);
|
||||
const { toolWindowService } = await import(contributionsPath);
|
||||
commands.agentChanges = async () => ({ status: "ok", data: [] });
|
||||
const entries: AgentEntry[] = [{ type: "agent", text: "The active conversation stays here." }];
|
||||
store.useAgents.setState({
|
||||
loaded: true,
|
||||
error: null,
|
||||
providers: [],
|
||||
tasks: new Map([
|
||||
[first.id, first],
|
||||
[second.id, second],
|
||||
]),
|
||||
entries: new Map([
|
||||
[first.id, entries],
|
||||
[second.id, []],
|
||||
]),
|
||||
composers: new Map([[first.id, { text: "Keep this unsent draft", files: [], images: [] }]]),
|
||||
unread: new Set(),
|
||||
docked: null,
|
||||
homeOpen: false,
|
||||
sessionLocation: "editor",
|
||||
});
|
||||
toolWindowService().show("agents", true);
|
||||
store.openTask(first.id);
|
||||
},
|
||||
{ first, second },
|
||||
);
|
||||
const firstTab = page.getByRole("tab", { name: first.title, exact: true });
|
||||
const fileTab = page.getByRole("tab", { name: "README.md", exact: true });
|
||||
await expect(firstTab).toHaveAttribute("aria-selected", "true");
|
||||
if (active === "file") await fileTab.click();
|
||||
const current = active === "file" ? fileTab : firstTab;
|
||||
const target = page.getByRole("tree", { name: "Agent tasks" }).getByText(second.title, { exact: true });
|
||||
await target.click({ button: "right" });
|
||||
await expect(page.getByRole("menuitem", { name: "Rename…", exact: true })).toBeVisible();
|
||||
await expect(current).toHaveAttribute("aria-selected", "true");
|
||||
await expect(page.getByRole("tab", { name: second.title, exact: true })).toHaveCount(0);
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(current).toHaveAttribute("aria-selected", "true");
|
||||
await expect
|
||||
.poll(() =>
|
||||
page.evaluate(async (id) => {
|
||||
const storePath = "/src/features/agents/store.ts";
|
||||
return (await import(storePath)).composerDraft(id).text;
|
||||
}, first.id),
|
||||
)
|
||||
.toBe("Keep this unsent draft");
|
||||
await target.click();
|
||||
await expect(page.getByRole("tab", { name: second.title, exact: true })).toHaveAttribute("aria-selected", "true");
|
||||
});
|
||||
}
|
||||
@@ -666,12 +666,24 @@ test("dragging the Markdown split divider resizes and reflows editor and preview
|
||||
const box = (await handle.boundingBox())!;
|
||||
const startX = box.x + box.width / 2;
|
||||
const midY = box.y + box.height / 2;
|
||||
const cursorAt = (x: number) =>
|
||||
page.evaluate(({ x, y }) => getComputedStyle(document.elementFromPoint(x, y)!).cursor, { x, y: midY });
|
||||
|
||||
await page.mouse.move(startX + 40, midY);
|
||||
await page.mouse.move(startX, midY);
|
||||
expect(await cursorAt(startX)).toMatch(/resize$/);
|
||||
await page.mouse.move(startX - 5, midY);
|
||||
expect(await cursorAt(startX - 5)).not.toMatch(/resize$/);
|
||||
|
||||
await page.mouse.move(startX, midY);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(startX - 180, midY, { steps: 6 });
|
||||
await expect(handle).toHaveAttribute("data-separator", "active");
|
||||
const sourceX = (await editor.boundingBox())!.x + 60;
|
||||
expect(await cursorAt(sourceX)).toMatch(/resize$/);
|
||||
await page.mouse.up();
|
||||
await page.mouse.move(sourceX, midY);
|
||||
expect(await cursorAt(sourceX)).toBe("text");
|
||||
|
||||
await expect.poll(async () => (await editor.boundingBox())!.width).toBeLessThan(initialEditor - 150);
|
||||
await expect.poll(async () => (await preview.boundingBox())!.width).toBeGreaterThan(initialPreview + 150);
|
||||
|
||||
@@ -17,7 +17,7 @@ func main() {
|
||||
[[language-servers]]
|
||||
name = "gopls"
|
||||
command = "gopls"
|
||||
initialization-options = { semanticTokens = true, vulncheck = "Imports" }
|
||||
initialization-options = { semanticTokens = true, vulncheck = "Imports", hints = { constantValues = true } }
|
||||
root-markers = ["go.work", "go.mod"]
|
||||
install-hint = "go install golang.org/x/tools/gopls@latest"
|
||||
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
diff --git a/dist/index.cjs b/dist/index.cjs
|
||||
index 4172cb0f2befc00da9ae09eb3486cae743403a97..ed3c542377fc6dff0195dd9116c16464fb615919 100644
|
||||
--- a/dist/index.cjs
|
||||
+++ b/dist/index.cjs
|
||||
@@ -208,7 +208,9 @@ class Stack {
|
||||
if (index > 0 && (this.buffer[index - 4] != 0 /* Term.Err */ || this.buffer[index - 1] < 0)) {
|
||||
let mustMove = false;
|
||||
for (let scan = index; scan > 0 && this.buffer[scan - 2] > end; scan -= 4) {
|
||||
- if (this.buffer[scan - 1] >= 0) {
|
||||
+ // Reused skipped nodes after the end must be moved out too.
|
||||
+ if (this.buffer[scan - 1] >= 0 ||
|
||||
+ this.buffer[scan - 1] == -1 && this.p.reused[this.buffer[scan - 4]].type.isSkipped) {
|
||||
mustMove = true;
|
||||
break;
|
||||
}
|
||||
@@ -278,7 +280,11 @@ class Stack {
|
||||
this.p.reused.push(value);
|
||||
index++;
|
||||
}
|
||||
- let end = this.reducePos = this.pos = start + value.length;
|
||||
+ // A reused skipped node (a comment) is not part of the node being
|
||||
+ // reduced: like a shifted skipped token, it leaves reducePos alone.
|
||||
+ let end = this.pos = start + value.length;
|
||||
+ if (!value.type.isSkipped)
|
||||
+ this.reducePos = end;
|
||||
this.pushState(next, start);
|
||||
this.buffer.push(index, start, end, -1 /* size == -1 means this is a reused value */);
|
||||
if (this.curContext)
|
||||
diff --git a/dist/index.js b/dist/index.js
|
||||
index 8fd3f87829c312b93ce022867fd17bf34da0dbc0..f67b16d2f46d683f12ddc81534efbf50925e7c65 100644
|
||||
--- a/dist/index.js
|
||||
+++ b/dist/index.js
|
||||
@@ -206,7 +206,9 @@ class Stack {
|
||||
if (index > 0 && (this.buffer[index - 4] != 0 /* Term.Err */ || this.buffer[index - 1] < 0)) {
|
||||
let mustMove = false;
|
||||
for (let scan = index; scan > 0 && this.buffer[scan - 2] > end; scan -= 4) {
|
||||
- if (this.buffer[scan - 1] >= 0) {
|
||||
+ // Reused skipped nodes after the end must be moved out too.
|
||||
+ if (this.buffer[scan - 1] >= 0 ||
|
||||
+ this.buffer[scan - 1] == -1 && this.p.reused[this.buffer[scan - 4]].type.isSkipped) {
|
||||
mustMove = true;
|
||||
break;
|
||||
}
|
||||
@@ -276,7 +278,11 @@ class Stack {
|
||||
this.p.reused.push(value);
|
||||
index++;
|
||||
}
|
||||
- let end = this.reducePos = this.pos = start + value.length;
|
||||
+ // A reused skipped node (a comment) is not part of the node being
|
||||
+ // reduced: like a shifted skipped token, it leaves reducePos alone.
|
||||
+ let end = this.pos = start + value.length;
|
||||
+ if (!value.type.isSkipped)
|
||||
+ this.reducePos = end;
|
||||
this.pushState(next, start);
|
||||
this.buffer.push(index, start, end, -1 /* size == -1 means this is a reused value */);
|
||||
if (this.curContext)
|
||||
Створено
+27
-26
@@ -9,6 +9,7 @@ overrides:
|
||||
|
||||
patchedDependencies:
|
||||
'@codemirror/view': 0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5
|
||||
'@lezer/lr': 1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8
|
||||
|
||||
importers:
|
||||
|
||||
@@ -82,7 +83,7 @@ importers:
|
||||
version: 1.2.5
|
||||
'@lezer/lr':
|
||||
specifier: ^1.4.11
|
||||
version: 1.4.11
|
||||
version: 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
'@plutojl/lang-julia':
|
||||
specifier: ^1.2.0
|
||||
version: 1.2.0
|
||||
@@ -2408,7 +2409,7 @@ snapshots:
|
||||
'@codemirror/language': 6.13.1
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
'@codemirror/[email protected]':
|
||||
dependencies:
|
||||
@@ -2467,7 +2468,7 @@ snapshots:
|
||||
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
'@codemirror/[email protected]':
|
||||
dependencies:
|
||||
@@ -2480,7 +2481,7 @@ snapshots:
|
||||
'@codemirror/language': 6.13.1
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
'@codemirror/[email protected]':
|
||||
dependencies:
|
||||
@@ -2491,7 +2492,7 @@ snapshots:
|
||||
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
'@codemirror/[email protected]':
|
||||
dependencies:
|
||||
@@ -2539,7 +2540,7 @@ snapshots:
|
||||
'@codemirror/state': 6.7.6
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
'@codemirror/[email protected]':
|
||||
dependencies:
|
||||
@@ -2548,14 +2549,14 @@ snapshots:
|
||||
'@codemirror/language': 6.13.1
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
'@codemirror/[email protected]':
|
||||
dependencies:
|
||||
'@codemirror/language': 6.13.1
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
'@codemirror/[email protected]':
|
||||
dependencies:
|
||||
@@ -2573,7 +2574,7 @@ snapshots:
|
||||
'@codemirror/state': 6.7.6
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
'@lezer/yaml': 1.0.4
|
||||
|
||||
'@codemirror/[email protected]':
|
||||
@@ -2609,7 +2610,7 @@ snapshots:
|
||||
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
style-mod: 4.1.4
|
||||
|
||||
'@codemirror/[email protected]':
|
||||
@@ -2745,24 +2746,24 @@ snapshots:
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
'@lezer/[email protected]':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
'@lezer/[email protected]':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/lr': 1.4.11
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
'@lezer/[email protected]':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
'@lezer/[email protected]':
|
||||
dependencies:
|
||||
@@ -2772,27 +2773,27 @@ snapshots:
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
'@lezer/[email protected]':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
'@lezer/[email protected]':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
'@lezer/[email protected]':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
'@lezer/[email protected]':
|
||||
'@lezer/[email protected](patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
|
||||
@@ -2805,37 +2806,37 @@ snapshots:
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
'@lezer/[email protected]':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
'@lezer/[email protected]':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
'@lezer/[email protected]':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
'@lezer/[email protected]':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
'@lezer/[email protected]':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
'@marijn/[email protected]': {}
|
||||
|
||||
@@ -3101,7 +3102,7 @@ snapshots:
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11
|
||||
'@lezer/lr': 1.4.11(patch_hash=1561ac9e9bbbc302f48ea274ae33602e598a7833edaadd7031559c893c7853b8)
|
||||
|
||||
'@replit/[email protected]': {}
|
||||
|
||||
|
||||
@@ -5,3 +5,4 @@ overrides:
|
||||
mermaid>katex: ^0.18.2
|
||||
patchedDependencies:
|
||||
"@codemirror/view": patches/@codemirror__view.patch
|
||||
"@lezer/lr": patches/@lezer__lr.patch
|
||||
@@ -41,6 +41,7 @@ ide-core.workspace = true
|
||||
ide-cli.workspace = true
|
||||
dunce.workspace = true
|
||||
ide-clipboard.workspace = true
|
||||
ide-drag-out.workspace = true
|
||||
ide-fonts.workspace = true
|
||||
ide-text.workspace = true
|
||||
ide-vfs.workspace = true
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
//! Native window drag started from the web title bar.
|
||||
//! Native drags started from the web UI: the window from its title bar, files out to other apps.
|
||||
|
||||
use ide_command::desktop_command;
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use std::path::PathBuf;
|
||||
use tauri::WebviewWindow;
|
||||
|
||||
/// Starts dragging `window` while the primary mouse button is still down; returns whether a drag began.
|
||||
@@ -20,4 +21,41 @@ pub fn window_start_drag(window: WebviewWindow) -> IdeResult<bool> {
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
ide_command::desktop_domain!(window_start_drag);
|
||||
/// Drags `paths` (local files and folders) out of `window` while the primary mouse button is
|
||||
/// still down, so the app they are dropped on copies them (#2867). Resolves when the drag ends,
|
||||
/// with whether a target took the files.
|
||||
#[desktop_command(trust = always)]
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn window_drag_files(window: WebviewWindow, paths: Vec<PathBuf>) -> IdeResult<bool> {
|
||||
let paths = ide_drag_out::local_paths(paths)?;
|
||||
let (started_tx, started_rx) = tokio::sync::oneshot::channel();
|
||||
let (done_tx, done_rx) = tokio::sync::oneshot::channel();
|
||||
let source = window.clone();
|
||||
window
|
||||
.run_on_main_thread(move || {
|
||||
let done = move |outcome| {
|
||||
let _ = done_tx.send(outcome);
|
||||
};
|
||||
// A tap WebKit delivered late: nothing is held, so the drag would never end.
|
||||
#[cfg(target_os = "macos")]
|
||||
if objc2_app_kit::NSEvent::pressedMouseButtons() & 1 == 0 {
|
||||
let _ = started_tx.send(Ok(()));
|
||||
return;
|
||||
}
|
||||
#[cfg(target_os = "linux")]
|
||||
let started = source
|
||||
.gtk_window()
|
||||
.map_err(|error| std::io::Error::other(error.to_string()))
|
||||
.and_then(|gtk_window| ide_drag_out::start(>k_window, paths, done));
|
||||
#[cfg(any(windows, target_os = "macos"))]
|
||||
let started = ide_drag_out::start(&source, paths, done);
|
||||
let _ = started_tx.send(started);
|
||||
})
|
||||
.map_err(|error| IdeError::internal(format!("Cannot start a drag on the main thread: {error}")))?;
|
||||
started_rx.await.map_err(|error| IdeError::internal(error.to_string()))??;
|
||||
// Dropped without an outcome when the drag never began or its backend lost it.
|
||||
Ok(matches!(done_rx.await, Ok(ide_drag_out::Outcome::Dropped)))
|
||||
}
|
||||
|
||||
ide_command::desktop_domain!(window_start_drag, window_drag_files);
|
||||
@@ -6,6 +6,8 @@ agent_archive always project_host bin
|
||||
agent_base_text trusted project_host bindings async
|
||||
agent_cancel always project_host bindings sync
|
||||
agent_changes trusted project_host bindings async
|
||||
agent_cli_update trusted project_host bindings async
|
||||
agent_cli_update_check trusted project_host bindings async
|
||||
agent_commands always project_host bindings async
|
||||
agent_context_usage trusted project_host bindings async
|
||||
agent_create trusted project_host bindings async
|
||||
@@ -728,6 +730,7 @@ web_url always project_host bin
|
||||
window_close_context always desktop bindings sync
|
||||
window_complete_launch always desktop bindings sync
|
||||
window_cycle always desktop bindings sync
|
||||
window_drag_files always desktop bindings async
|
||||
window_flash_taskbar always desktop bindings sync
|
||||
window_group_cancel_close always desktop bindings sync
|
||||
window_group_close always desktop bindings sync
|
||||
|
||||
@@ -33,6 +33,10 @@ export const commands = {
|
||||
"group" |
|
||||
/** What the last turn changed, against the checkout as that turn started. */
|
||||
"lastTurn" | null) => typedError<AgentChange[], IdeError>(__TAURI_INVOKE("agent_changes", { task, view })),
|
||||
/** Installs the exact version offered if the selected installation still matches. */
|
||||
agentCliUpdate: (provider: string, offer: AgentCliOffer, request: RequestId) => typedError<AgentCliUpdateResult, IdeError>(__TAURI_INVOKE("agent_cli_update", { provider, offer, request })),
|
||||
/** Checks the selected installation without modifying it. */
|
||||
agentCliUpdateCheck: (provider: string, request: RequestId) => typedError<AgentCliUpdateResult, IdeError>(__TAURI_INVOKE("agent_cli_update_check", { provider, request })),
|
||||
/**
|
||||
* Slash commands to complete for `provider` in `task`'s directory, or in the project
|
||||
* before a task exists (skills and custom commands on disk included).
|
||||
@@ -1935,6 +1939,12 @@ export const commands = {
|
||||
windowCompleteLaunch: () => typedError<null, IdeError>(__TAURI_INVOKE("window_complete_launch")),
|
||||
/** Focuses the next / previous window (⌘` / ⇧⌘`). */
|
||||
windowCycle: (forward: boolean) => __TAURI_INVOKE<void>("window_cycle", { forward }),
|
||||
/**
|
||||
* Drags `paths` (local files and folders) out of `window` while the primary mouse button is
|
||||
* still down, so the app they are dropped on copies them (#2867). Resolves when the drag ends,
|
||||
* with whether a target took the files.
|
||||
*/
|
||||
windowDragFiles: (paths: string[]) => typedError<boolean, IdeError>(__TAURI_INVOKE("window_drag_files", { paths })),
|
||||
/**
|
||||
* Flash (`true`) or stop flashing (`false`) this window's taskbar button, like IDEA when a
|
||||
* breakpoint is hit while the window is in the background (macOS bounces the dock icon,
|
||||
@@ -2204,6 +2214,18 @@ export type AgentChangesView =
|
||||
/** What the last turn changed, against the checkout as that turn started. */
|
||||
"lastTurn";
|
||||
|
||||
export type AgentCliOffer = {
|
||||
current: string,
|
||||
latest: string,
|
||||
prefix: string,
|
||||
};
|
||||
|
||||
export type AgentCliUpdateResult = {
|
||||
status: "available",
|
||||
} & AgentCliOffer | {
|
||||
status: "permission",
|
||||
} & AgentCliOffer | ({ status: "current"; current: string }) & { code?: never } | ({ status: "channel"; current: string }) & { code?: never } | ({ status: "updated"; current: string }) & { code?: never } | ({ status: "unmanaged" }) & { code?: never; current?: never } | ({ status: "error"; code: string }) & { current?: never };
|
||||
|
||||
export type AgentCommand = {
|
||||
/** Without the leading `/`. */
|
||||
name: string,
|
||||
@@ -2560,6 +2582,8 @@ export type AgentProvider = {
|
||||
commandReadOnlyReason: AgentCommandReadOnlyReason | null,
|
||||
/** Whether the command was found (on `PATH`). */
|
||||
installed: boolean,
|
||||
/** The built-in command can be owned by a global npm package. */
|
||||
canCheckCliUpdate?: boolean,
|
||||
/** Environment variables it starts with (from its agent file). */
|
||||
env: { [key in string]: string },
|
||||
/** Settings (models, modes…) the agent offered last time it ran; empty before its first session. */
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { ensureSyntaxTree, syntaxTree } from "@codemirror/language";
|
||||
import { javascript } from "@codemirror/lang-javascript";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
|
||||
/** Functions with long doc comments: re-parsing reuses a whole comment as one node. */
|
||||
const source = Array.from(
|
||||
{ length: 5 },
|
||||
(_, i) =>
|
||||
`/**\n${Array.from({ length: 40 }, (_, j) => ` * line ${j} of the comment on f${i}\n`).join("")} */\n` +
|
||||
`export const f${i} = (a, b = {}) => {\n // body\n if (a) return b\n return a\n}\n\n`,
|
||||
).join("");
|
||||
|
||||
describe("incremental parsing (#4468)", () => {
|
||||
it("keeps a reused comment out of the declaration before it", () => {
|
||||
let state = EditorState.create({ doc: source, extensions: [javascript()] });
|
||||
ensureSyntaxTree(state, state.doc.length, 5000);
|
||||
// Reindenting, as a formatter does.
|
||||
const at = source.indexOf(" // body");
|
||||
state = state.update({ changes: { from: at, to: at + 4, insert: " " } }).state;
|
||||
const tree = ensureSyntaxTree(state, state.doc.length, 5000) ?? syntaxTree(state);
|
||||
const fresh = javascript().language.parser.parse(state.doc.toString());
|
||||
expect(tree.toString()).toBe(fresh.toString());
|
||||
expect(tree.topNode.firstChild?.name).toBe("BlockComment");
|
||||
expect(tree.topNode.firstChild?.from).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -21,6 +21,7 @@ import clsx from "clsx";
|
||||
import { Button, Dialog, Icon, IconButton, Input, List, ProgressBar, SearchField, Select, Spinner, T } from "@/ui";
|
||||
import { useSettingsForm } from "@/workbench/contributions";
|
||||
import { confirm } from "@/workbench/messages";
|
||||
import { LocalCliUpdate } from "./LocalCliUpdate";
|
||||
import { isPerModelOption } from "./composerModel";
|
||||
import { providerIcon, slugifyId } from "./model";
|
||||
import {
|
||||
@@ -854,6 +855,9 @@ function ProviderSettings({
|
||||
const envEditable = agent.commandReadOnlyReason !== "registry" && agent.commandReadOnlyReason !== "customAgent";
|
||||
return (
|
||||
<>
|
||||
{value.trim() === current && agent.installed && agent.canCheckCliUpdate && (
|
||||
<LocalCliUpdate key={agent.program} agent={agent} backend={backend} />
|
||||
)}
|
||||
{agent.loginHint && (
|
||||
<Section title="Sign In">
|
||||
<p className={styles.text}>
|
||||
|
||||
@@ -9,6 +9,7 @@ import { promptInput } from "@/workbench/inputDialogs";
|
||||
import { ContextMenuHost, dragSession, hideContextMenu } from "@/ui";
|
||||
import { AgentsHeaderActions, AgentsView } from "./AgentsView";
|
||||
import { SESSION_KIND, TASK_DRAG } from "./model";
|
||||
import { usePlatform } from "@/platform/platformInfo";
|
||||
import { archiveTask, unarchiveTask, deleteTask, dockTask, openTask, useAgents } from "./store";
|
||||
import { taskActions, taskMenu, useAgentsHeaderMenu } from "./taskActions";
|
||||
import styles from "./Agents.module.css";
|
||||
@@ -140,6 +141,42 @@ function setup() {
|
||||
}
|
||||
|
||||
describe("Agents selection", () => {
|
||||
it.each([SESSION_KIND, "file"])("right-clicking a task keeps the current %s view open", (kind) => {
|
||||
editor.active = { kind, key: "current", data: { task: "one" } };
|
||||
setup();
|
||||
context("two");
|
||||
expect(screen.getByRole("menuitem", { name: "Rename…" })).toBeTruthy();
|
||||
expect(selectedTasks()).toEqual(["two"]);
|
||||
expect(openTask).not.toHaveBeenCalled();
|
||||
fireEvent.keyDown(document, { key: "Escape" });
|
||||
expect(openTask).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("preserves a multi-selection when opening its context menu without activating a task", () => {
|
||||
setup();
|
||||
select("one");
|
||||
select("three", { shiftKey: true });
|
||||
vi.mocked(openTask).mockClear();
|
||||
context("two");
|
||||
expect(selectedTasks()).toEqual(["one", "two", "three"]);
|
||||
expect(screen.getByRole("menuitem", { name: "Delete (3)…" })).toBeTruthy();
|
||||
expect(openTask).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("treats macOS Control-click as a context menu without opening the task", () => {
|
||||
const os = usePlatform.getState().os;
|
||||
usePlatform.setState({ os: "macos" });
|
||||
try {
|
||||
setup();
|
||||
fireEvent.mouseDown(row("two"), { button: 0, ctrlKey: true });
|
||||
fireEvent.contextMenu(row("two"), { button: 0, ctrlKey: true });
|
||||
expect(screen.getByRole("menuitem", { name: "Rename…" })).toBeTruthy();
|
||||
expect(openTask).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
usePlatform.setState({ os });
|
||||
}
|
||||
});
|
||||
|
||||
it("extends and shrinks a range without opening its lead or losing selection to an editor echo", () => {
|
||||
setup();
|
||||
select("one");
|
||||
@@ -164,14 +201,24 @@ describe("Agents selection", () => {
|
||||
expect(openTask).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each(["metaKey", "ctrlKey"])("toggles individual tasks with %s", (modifier) => {
|
||||
setup();
|
||||
select("one");
|
||||
select("three", { [modifier]: true });
|
||||
expect(selectedTasks()).toEqual(["one", "three"]);
|
||||
select("three", { [modifier]: true });
|
||||
expect(selectedTasks()).toEqual(["one"]);
|
||||
expect(openTask).toHaveBeenCalledTimes(1);
|
||||
it.each([
|
||||
{ os: "macos", modifier: "metaKey" },
|
||||
{ os: "windows", modifier: "ctrlKey" },
|
||||
{ os: "linux", modifier: "ctrlKey" },
|
||||
])("toggles individual tasks with $modifier on $os", ({ os, modifier }) => {
|
||||
const previousOs = usePlatform.getState().os;
|
||||
usePlatform.setState({ os });
|
||||
try {
|
||||
setup();
|
||||
select("one");
|
||||
select("three", { [modifier]: true });
|
||||
expect(selectedTasks()).toEqual(["one", "three"]);
|
||||
select("three", { [modifier]: true });
|
||||
expect(selectedTasks()).toEqual(["one"]);
|
||||
expect(openTask).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
usePlatform.setState({ os: previousOs });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -322,9 +322,10 @@ export function AgentsView() {
|
||||
})
|
||||
}
|
||||
selected={selected}
|
||||
onSelectionChange={(sel, lead) => {
|
||||
onSelectionChange={(sel, lead, reason) => {
|
||||
setSelected(sel);
|
||||
if (!inline && sel.size === 1 && lead?.kind === "task" && sel.has(lead.task.id)) showTask(lead.task.id);
|
||||
if (reason !== "contextMenu" && !inline && sel.size === 1 && lead?.kind === "task" && sel.has(lead.task.id))
|
||||
showTask(lead.task.id);
|
||||
}}
|
||||
onActivate={(n) => n.kind === "task" && showTask(n.task.id)}
|
||||
onContextMenu={(n, sel, e) => {
|
||||
|
||||
@@ -14,6 +14,7 @@ import { EditorView, keymap, placeholder as placeholderText, type ViewUpdate } f
|
||||
import type { AgentCommand, AgentConfigOption, AgentImage, SendKey, SymbolMatch, WhileRunning } from "@/bindings";
|
||||
import { useEditorRegistry, openEditorPaths } from "@/editor/api";
|
||||
import { call, commands, isTauri } from "@/platform/ipc";
|
||||
import { isDraggingOut } from "@/platform/dragOut";
|
||||
import { nativeDropPoint } from "@/platform/nativeDrop";
|
||||
import { invokeLocal } from "@/platform/tauriCore";
|
||||
import { useTx } from "@/platform/i18n";
|
||||
@@ -875,6 +876,8 @@ export function Composer(props: ComposerProps) {
|
||||
void import("@tauri-apps/api/webview").then(({ getCurrentWebview }) =>
|
||||
getCurrentWebview()
|
||||
.onDragDropEvent((event) => {
|
||||
// Project files dragged out of the window come back as an OS drop: not attachments.
|
||||
if (isDraggingOut()) return;
|
||||
const p = event.payload;
|
||||
if (p.type === "enter" || p.type === "over") {
|
||||
setFileOver(inBox(p.position));
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import type { AgentCliOffer, AgentCliUpdateResult, AgentProvider, RequestId } from "@/bindings";
|
||||
import { IpcError, isCancelled, nextRequestId } from "@/platform/ipc";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { isRemoteWindow } from "@/platform/remote";
|
||||
import { openExternalUrl } from "@/platform/openUrl";
|
||||
import { Button, T } from "@/ui";
|
||||
import type { CommandsBackend } from "./registry";
|
||||
import styles from "./AgentList.module.css";
|
||||
|
||||
export function LocalCliUpdate({ agent, backend }: { agent: AgentProvider; backend: CommandsBackend }) {
|
||||
const active = useRef<RequestId | null>(null);
|
||||
const [busy, setBusy] = useState<"check" | "update" | null>(null);
|
||||
const [result, setResult] = useState<AgentCliUpdateResult | null>(null);
|
||||
const [error, setError] = useState("");
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (active.current !== null) backend.cancel(active.current);
|
||||
active.current = null;
|
||||
},
|
||||
[backend],
|
||||
);
|
||||
if (isRemoteWindow()) return null;
|
||||
const check = async (offer?: AgentCliOffer) => {
|
||||
const request = nextRequestId();
|
||||
active.current = request;
|
||||
setBusy(offer ? "update" : "check");
|
||||
setError("");
|
||||
setResult(null);
|
||||
try {
|
||||
const reply = offer
|
||||
? await backend.updateCli(agent.id, offer, request)
|
||||
: await backend.checkCli(agent.id, request);
|
||||
if (active.current === request) setResult(reply);
|
||||
} catch (e) {
|
||||
if (active.current === request && !isCancelled(e)) {
|
||||
setError(
|
||||
e instanceof IpcError && e.kind === "alreadyExists"
|
||||
? tx("An update for this agent is already running.")
|
||||
: e instanceof Error
|
||||
? e.message
|
||||
: String(e),
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
if (active.current === request) {
|
||||
active.current = null;
|
||||
setBusy(null);
|
||||
}
|
||||
}
|
||||
};
|
||||
return (
|
||||
<div className={styles.section}>
|
||||
<div className={styles.sectionTitle}>
|
||||
<T>CLI version</T>
|
||||
<span aria-hidden className={styles.sectionRule} />
|
||||
</div>
|
||||
<div className={styles.actions}>
|
||||
<Button size="small" disabled={!!busy} onClick={() => void check()}>
|
||||
{busy === "check" ? tx("Checking…") : tx("Check for updates")}
|
||||
</Button>
|
||||
{busy && (
|
||||
<Button size="small" onClick={() => backend.cancel(active.current!)}>
|
||||
<T>Cancel</T>
|
||||
</Button>
|
||||
)}
|
||||
{result?.status === "available" && (
|
||||
<Button size="small" variant="primary" onClick={() => void check(result)}>
|
||||
{tx`Update to ${result.latest}`}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<div aria-live="polite">
|
||||
{busy === "update" && (
|
||||
<p className={styles.text}>
|
||||
<T>Updating the npm installation…</T>
|
||||
</p>
|
||||
)}
|
||||
{result?.status === "available" && (
|
||||
<p
|
||||
className={styles.text}
|
||||
>{tx`Installed: ${result.current} · npm latest: ${result.latest} · ${result.prefix}`}</p>
|
||||
)}
|
||||
{result?.status === "permission" && (
|
||||
<p className={styles.text}>
|
||||
{tx`Installed: ${result.current} · npm latest: ${result.latest}. No write permission for the npm installation at ${result.prefix}.`}{" "}
|
||||
<Button
|
||||
size="small"
|
||||
onClick={() =>
|
||||
void openExternalUrl(
|
||||
"https://docs.npmjs.com/resolving-eacces-permissions-errors-when-installing-packages-globally",
|
||||
)
|
||||
}
|
||||
>
|
||||
<T>View permission fixes</T>
|
||||
</Button>
|
||||
</p>
|
||||
)}
|
||||
{result?.status === "updated" && (
|
||||
<p className={styles.text}>{tx`Updated to ${result.current}. New sessions will use this version.`}</p>
|
||||
)}
|
||||
{result?.status === "current" && (
|
||||
<p className={styles.text}>{tx`Installed: ${result.current} · No newer npm release.`}</p>
|
||||
)}
|
||||
{result?.status === "channel" && (
|
||||
<p
|
||||
className={styles.text}
|
||||
>{tx`Installed: ${result.current}. Use your installer to manage this release channel.`}</p>
|
||||
)}
|
||||
{result?.status === "unmanaged" && (
|
||||
<p className={styles.text}>
|
||||
<T>This is not a global npm install OpenIDEA can update. Use its original installer.</T>
|
||||
</p>
|
||||
)}
|
||||
{(error || result?.status === "error") && (
|
||||
<p role="alert" className={styles.error}>
|
||||
{error || (result?.status === "error" && tx`npm could not complete the operation (${result.code}).`)}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -413,6 +413,9 @@ describe("the ACP Registry in the agent list", () => {
|
||||
});
|
||||
|
||||
class FakeCommands implements CommandsBackend {
|
||||
checkCli = vi.fn<CommandsBackend["checkCli"]>();
|
||||
updateCli = vi.fn<CommandsBackend["updateCli"]>();
|
||||
cancel = vi.fn<CommandsBackend["cancel"]>();
|
||||
list: AgentProvider[] = [];
|
||||
saved: [string, string | null][] = [];
|
||||
providers = vi.fn(async () => this.list);
|
||||
@@ -455,6 +458,7 @@ const claudeProvider = (command: string): AgentProvider => ({
|
||||
commandEditable: true,
|
||||
commandReadOnlyReason: null,
|
||||
installed: true,
|
||||
canCheckCliUpdate: true,
|
||||
env: {},
|
||||
config: [],
|
||||
commands: [],
|
||||
@@ -483,6 +487,45 @@ describe("Built-in executable overrides", () => {
|
||||
const apply = () => screen.getByRole("button", { name: "Apply" });
|
||||
const field = () => screen.getByRole("textbox", { name: "Executable" });
|
||||
|
||||
it("checks only on click and updates only after the user chooses the offered version", async () => {
|
||||
const commands = new FakeCommands();
|
||||
const provider = claudeProvider("claude");
|
||||
const offer = { status: "available" as const, current: "1.0.0", latest: "1.1.0", prefix: "/usr/local" };
|
||||
commands.list = [provider];
|
||||
commands.checkCli.mockResolvedValueOnce(offer);
|
||||
commands.updateCli.mockResolvedValueOnce({ status: "updated", current: "1.1.0" });
|
||||
const panel = within(await openCommands(commands));
|
||||
expect(commands.checkCli).not.toHaveBeenCalled();
|
||||
fireEvent.click(panel.getByRole("button", { name: "Check for updates" }));
|
||||
const update = await panel.findByRole("button", { name: "Update to 1.1.0" });
|
||||
expect(commands.checkCli).toHaveBeenCalledOnce();
|
||||
fireEvent.click(update);
|
||||
await panel.findByText("Updated to 1.1.0. New sessions will use this version.");
|
||||
expect(commands.updateCli).toHaveBeenCalledWith(provider.id, offer, expect.any(Number));
|
||||
expect(commands.saved).toEqual([]);
|
||||
});
|
||||
|
||||
it("cancels the in-progress update by its request id", async () => {
|
||||
const commands = new FakeCommands();
|
||||
commands.list = [claudeProvider("claude")];
|
||||
commands.checkCli.mockResolvedValue({ status: "available", current: "1.0.0", latest: "1.1.0", prefix: "/test" });
|
||||
let cancel!: () => void;
|
||||
commands.updateCli.mockImplementation(
|
||||
() =>
|
||||
new Promise((_, reject) => {
|
||||
cancel = () => reject(new IpcError({ kind: "cancelled", message: "cancelled" }));
|
||||
}),
|
||||
);
|
||||
const panel = within(await openCommands(commands));
|
||||
fireEvent.click(panel.getByRole("button", { name: "Check for updates" }));
|
||||
fireEvent.click(await panel.findByRole("button", { name: "Update to 1.1.0" }));
|
||||
fireEvent.click(panel.getByRole("button", { name: "Cancel" }));
|
||||
expect(commands.cancel).toHaveBeenCalledWith(commands.updateCli.mock.calls[0]![2]);
|
||||
await act(async () => cancel());
|
||||
await waitFor(() => expect(panel.getByRole("button", { name: "Check for updates" })).toBeEnabled());
|
||||
expect(panel.queryByRole("alert")).toBeNull();
|
||||
});
|
||||
|
||||
it("follows locale changes and renders login commands as inline code", async () => {
|
||||
const commands = new FakeCommands();
|
||||
commands.list = [
|
||||
|
||||
@@ -3,6 +3,8 @@ import { open } from "@/platform/dialog";
|
||||
import { Channel } from "@tauri-apps/api/core";
|
||||
import type {
|
||||
AcpImportOutcome,
|
||||
AgentCliOffer,
|
||||
AgentCliUpdateResult,
|
||||
AgentProvider,
|
||||
AgentRegistry,
|
||||
CustomAgentInput,
|
||||
@@ -23,6 +25,9 @@ export interface RegistryBackend {
|
||||
|
||||
/** The built-in agents' launch commands: read, and override through an agent file. */
|
||||
export interface CommandsBackend {
|
||||
checkCli(id: string, request: RequestId): Promise<AgentCliUpdateResult>;
|
||||
updateCli(id: string, offer: AgentCliOffer, request: RequestId): Promise<AgentCliUpdateResult>;
|
||||
cancel(request: RequestId): void;
|
||||
providers(): Promise<AgentProvider[]>;
|
||||
set(id: string, command: string | null): Promise<void>;
|
||||
setEnv(id: string, env: Record<string, string>): Promise<void>;
|
||||
@@ -47,6 +52,9 @@ export const tauriRegistry: RegistryBackend = {
|
||||
};
|
||||
|
||||
export const tauriCommands: CommandsBackend = {
|
||||
checkCli: (id, request) => call(commands.agentCliUpdateCheck(id, request)),
|
||||
updateCli: (id, offer, request) => call(commands.agentCliUpdate(id, offer, request)),
|
||||
cancel: tauriRegistry.cancel,
|
||||
providers: () => call(commands.agentProviders()),
|
||||
chooseExecutable: async (title, current) => {
|
||||
const picked = await open({ title, defaultPath: current || undefined, directory: false, multiple: false });
|
||||
|
||||
@@ -7,6 +7,20 @@ vi.mock("@/workbench/contributions", async (orig) => ({
|
||||
}));
|
||||
import { adoptSession, closeSessionTab, useDebug } from "../state";
|
||||
|
||||
it("closes a session's child and grandchild sessions with it (#4280)", async () => {
|
||||
// js-debug: `pnpm run dev` → pnpm.cjs → rspack.js.
|
||||
adoptSession(10, { adapter: "js-debug", name: "pnpm run dev" });
|
||||
adoptSession(11, { adapter: "js-debug", name: "pnpm.cjs", parent: 10 });
|
||||
adoptSession(12, { adapter: "js-debug", name: "rspack.js", parent: 11 });
|
||||
adoptSession(13, { adapter: "js-debug", name: "other" });
|
||||
for (const id of [10, 11, 12, 13])
|
||||
useDebug.setState((s) => ({ sessions: { ...s.sessions, [id]: { ...s.sessions[id]!, status: "terminated" } } }));
|
||||
expect(await closeSessionTab(10)).toBe(true);
|
||||
expect(Object.keys(useDebug.getState().sessions)).toEqual(["13"]);
|
||||
expect(await closeSessionTab(13)).toBe(true);
|
||||
hide.mockClear();
|
||||
});
|
||||
|
||||
it("hides the Debug tool window once its last session tab is closed", async () => {
|
||||
adoptSession(1, { adapter: "delve" });
|
||||
adoptSession(2, { adapter: "delve" });
|
||||
|
||||
@@ -34,6 +34,24 @@ describe("debug console", () => {
|
||||
expect(lines(5).some((l) => l.text.includes("\x1b"))).toBe(false);
|
||||
});
|
||||
|
||||
it("overwrites the line after a carriage return, as a progress bar expects (#4280)", () => {
|
||||
appendConsole(7, "stdout", "Network: http://localhost:8090/\n");
|
||||
appendConsole(7, "stdout", "\x1b[32m━━\x1b[0m (10%) build modules");
|
||||
appendConsole(7, "stdout", "\r");
|
||||
appendConsole(7, "stdout", "\x1b[32m━━━━━━\x1b[0m (63%) build modules\r");
|
||||
// An erase-line escape counts as a carriage return too.
|
||||
appendConsole(7, "stdout", "\x1b[2K\x1b[1Gdone in 1.2 s\r");
|
||||
appendConsole(7, "stdout", "\n");
|
||||
appendConsole(7, "stdout", "next\r\nline\n");
|
||||
expect(lines(7).map((l) => l.text)).toEqual([
|
||||
"Network: http://localhost:8090/\n",
|
||||
"done in 1.2 s\n",
|
||||
"next\n",
|
||||
"line\n",
|
||||
]);
|
||||
expect(lines(7)[1]!.spans).toEqual([{ text: "done in 1.2 s\n" }]);
|
||||
});
|
||||
|
||||
it("keeps a colour across output events and an escape split between them", () => {
|
||||
appendConsole(6, "stderr", "\x1b[3");
|
||||
appendConsole(6, "stderr", "1mred ");
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { expressionAt } from "../editor/valueTooltip";
|
||||
|
||||
/** The expression around the `|` in `line`. */
|
||||
function at(line: string, calls: boolean) {
|
||||
const pos = line.indexOf("|");
|
||||
const view = new EditorView({ state: EditorState.create({ doc: line.replace("|", "") }) });
|
||||
const text = expressionAt(view, pos, { calls })?.text ?? null;
|
||||
view.destroy();
|
||||
return text;
|
||||
}
|
||||
|
||||
describe("expression at the mouse for Quick Evaluate (#4772)", () => {
|
||||
it("takes the call of the clicked method, arguments included", () => {
|
||||
expect(at("String n = vo.getChd|rnum();", true)).toBe("vo.getChdrnum()");
|
||||
expect(at('x = f|(a, g(b), "c)");', true)).toBe('f(a, g(b), "c)")');
|
||||
expect(at("x = list.g|et (i);", true)).toBe("list.get (i)");
|
||||
});
|
||||
|
||||
it("follows member chains through calls and indexing to the clicked member", () => {
|
||||
expect(at("a.getB().c|()", true)).toBe("a.getB().c()");
|
||||
expect(at("a.get|B().c()", true)).toBe("a.getB()");
|
||||
expect(at("items[i + 1].na|me", true)).toBe("items[i + 1].name");
|
||||
expect(at("a.b()[0].c|", true)).toBe("a.b()[0].c");
|
||||
});
|
||||
|
||||
it("leaves an unbalanced call as the bare member", () => {
|
||||
expect(at("vo.getChd|rnum(a,", true)).toBe("vo.getChdrnum");
|
||||
});
|
||||
|
||||
it("keeps plain hovers free of calls", () => {
|
||||
expect(at("String n = vo.getChd|rnum();", false)).toBe("vo.getChdrnum");
|
||||
expect(at("a.getB().c|()", false)).toBe("c");
|
||||
});
|
||||
});
|
||||
@@ -91,7 +91,7 @@ describe("paused editor evaluation", () => {
|
||||
view.dispatch({ selection: { anchor: 0, head: 5 } });
|
||||
expect(click().defaultPrevented).toBe(true);
|
||||
await vi.waitFor(() => expect(document.querySelector(".cm-lsp-hint")?.textContent).toContain("order.items = 42"));
|
||||
expect(ipc.debugEvaluateIn).toHaveBeenCalledExactlyOnceWith(7, 10, "order.items", "hover");
|
||||
expect(ipc.debugEvaluateIn).toHaveBeenCalledExactlyOnceWith(7, 10, "order.items", "watch");
|
||||
expect(view.state.selection.main.head).toBe(16);
|
||||
});
|
||||
|
||||
@@ -101,7 +101,7 @@ describe("paused editor evaluation", () => {
|
||||
session();
|
||||
view.dispatch({ selection: { anchor: 0, head: doc.length } });
|
||||
click();
|
||||
await vi.waitFor(() => expect(ipc.debugEvaluateIn).toHaveBeenCalledWith(7, 10, doc, "hover"));
|
||||
await vi.waitFor(() => expect(ipc.debugEvaluateIn).toHaveBeenCalledWith(7, 10, doc, "watch"));
|
||||
expect(view.state.selection.main.from).toBe(0);
|
||||
expect(view.state.selection.main.to).toBe(doc.length);
|
||||
await vi.waitFor(() =>
|
||||
@@ -114,7 +114,7 @@ describe("paused editor evaluation", () => {
|
||||
const text = "(total +\n order.items)";
|
||||
view.dispatch({ changes: { from: 0, to: doc.length, insert: text }, selection: { anchor: 0, head: text.length } });
|
||||
click();
|
||||
await vi.waitFor(() => expect(ipc.debugEvaluateIn).toHaveBeenCalledWith(7, 10, text, "hover"));
|
||||
await vi.waitFor(() => expect(ipc.debugEvaluateIn).toHaveBeenCalledWith(7, 10, text, "watch"));
|
||||
});
|
||||
|
||||
it("ignores an object response that arrives after the debugger resumes", async () => {
|
||||
|
||||
@@ -70,19 +70,35 @@ it.each([undefined, true, false])(
|
||||
);
|
||||
|
||||
it.each(["breakpoint", "function breakpoint", "exception", "pause"])(
|
||||
"reveals an in-place session on suspend (%s)",
|
||||
"reveals an in-place session in Services on suspend (%s)",
|
||||
async (reason) => {
|
||||
const show = vi.fn();
|
||||
provideToolWindowService({ show } as unknown as ToolWindowService);
|
||||
await startSession(config("launch"), { show: false });
|
||||
expect(show).not.toHaveBeenCalled();
|
||||
handleDebugEvent(42, { kind: "stopped", threadId: 1, reason, description: null, allThreadsStopped: true });
|
||||
expect(show).toHaveBeenCalledWith("debug");
|
||||
// Services shows the session's debugger in place (#4773).
|
||||
expect(show).toHaveBeenCalledExactlyOnceWith("services");
|
||||
expect(useDebug.getState().active).toBe(42);
|
||||
expect(useDebug.getState().sessions[42]).toMatchObject({ status: "paused", selectedThread: 1 });
|
||||
},
|
||||
);
|
||||
|
||||
it("reveals a session started elsewhere in the Debug tool window on suspend", async () => {
|
||||
const show = vi.fn();
|
||||
provideToolWindowService({ show } as unknown as ToolWindowService);
|
||||
await startSession(config("launch"));
|
||||
show.mockClear();
|
||||
handleDebugEvent(42, {
|
||||
kind: "stopped",
|
||||
threadId: 1,
|
||||
reason: "breakpoint",
|
||||
description: null,
|
||||
allThreadsStopped: true,
|
||||
});
|
||||
expect(show).toHaveBeenCalledExactlyOnceWith("debug");
|
||||
});
|
||||
|
||||
it.each(["launch", "attach"])("awaits every file before %s can send configurationDone", async (request) => {
|
||||
const completed: string[] = [];
|
||||
const release: Array<() => void> = [];
|
||||
|
||||
@@ -208,7 +208,7 @@ function evaluateSeed(view: EditorView | undefined = activeEditor()?.view, pos?:
|
||||
const { state } = view;
|
||||
const sel = state.selection.main;
|
||||
if (!sel.empty && (pos == null || (sel.from <= pos && pos <= sel.to))) return state.sliceDoc(sel.from, sel.to);
|
||||
return expressionAt(view, pos ?? sel.head)?.text ?? "";
|
||||
return expressionAt(view, pos ?? sel.head, { calls: true })?.text ?? "";
|
||||
}
|
||||
|
||||
async function quickEvaluate(arg?: unknown) {
|
||||
@@ -234,7 +234,8 @@ async function quickEvaluate(arg?: unknown) {
|
||||
);
|
||||
};
|
||||
try {
|
||||
const value = await evaluate(expression, "hover", session);
|
||||
// Unlike a plain hover, an explicit Quick Evaluate may call methods (adapters refuse that for "hover").
|
||||
const value = await evaluate(expression, "watch", session);
|
||||
if (session && stillCurrent()) showQuickValue(view, pos, expression, value, session.id);
|
||||
} catch (e) {
|
||||
if (stillCurrent()) showHint(view, e instanceof Error ? e.message : String(e), { pos, tone: "error" });
|
||||
|
||||
@@ -19,8 +19,45 @@ import styles from "./editor.module.css";
|
||||
const BASE_HOVER = 100;
|
||||
const IDENT = /[\p{L}\p{N}_$]/u;
|
||||
|
||||
/** Identifier (with `a.b.c` member access) around `pos`, or the selection containing it. */
|
||||
export function expressionAt(view: EditorView, pos: number): { from: number; to: number; text: string } | null {
|
||||
const OPEN: Record<string, string> = { ")": "(", "]": "[" };
|
||||
const CLOSE: Record<string, string> = { "(": ")", "[": "]" };
|
||||
|
||||
/** Index just past the bracket group opening at `i` (strings skipped), or -1 when it doesn't close on the line. */
|
||||
function closeOf(t: string, i: number): number {
|
||||
const stack: string[] = [];
|
||||
for (let j = i; j < t.length; j++) {
|
||||
const c = t[j]!;
|
||||
if (c === '"' || c === "'" || c === "`") {
|
||||
j++;
|
||||
while (j < t.length && t[j] !== c) j += t[j] === "\\" ? 2 : 1;
|
||||
if (j >= t.length) return -1;
|
||||
} else if (CLOSE[c]) stack.push(CLOSE[c]);
|
||||
else if (c === ")" || c === "]") {
|
||||
if (stack.pop() !== c) return -1;
|
||||
if (!stack.length) return j + 1;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/** Index of the bracket opening the group that closes at `i - 1`, or -1. */
|
||||
function openOf(t: string, i: number): number {
|
||||
for (let start = i - 1; start >= 0; start--) {
|
||||
if (t[start] === OPEN[t[i - 1]!] && closeOf(t, start) === i) return start;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Identifier (with `a.b.c` member access) around `pos`, or the selection containing it. With
|
||||
* `calls`, as for Quick Evaluate: member chains through calls and indexing (`a.getB().c`,
|
||||
* `items[i].name`) and the call of the identifier itself (`o.getX()`, `f(a, b)`).
|
||||
*/
|
||||
export function expressionAt(
|
||||
view: EditorView,
|
||||
pos: number,
|
||||
{ calls = false } = {},
|
||||
): { from: number; to: number; text: string } | null {
|
||||
const { state } = view;
|
||||
const sel = state.selection.main;
|
||||
if (!sel.empty && pos >= sel.from && pos <= sel.to) {
|
||||
@@ -33,7 +70,25 @@ export function expressionAt(view: EditorView, pos: number): { from: number; to:
|
||||
let end = start;
|
||||
if (!IDENT.test(t[end] ?? "") && !IDENT.test(t[start - 1] ?? "")) return null;
|
||||
while (end < t.length && IDENT.test(t[end]!)) end++;
|
||||
while (start > 0 && (IDENT.test(t[start - 1]!) || (t[start - 1] === "." && IDENT.test(t[start - 2] ?? "")))) start--;
|
||||
for (;;) {
|
||||
while (start > 0 && IDENT.test(t[start - 1]!)) start--;
|
||||
if (t[start - 1] === "." && IDENT.test(t[start - 2] ?? "")) start--;
|
||||
else if (calls && t[start - 1] === "." && OPEN[t[start - 2] ?? ""]) {
|
||||
let open = openOf(t, start - 1);
|
||||
// `a.b()[0].c`: walk back over every group, then the name they follow.
|
||||
while (open > 0 && OPEN[t[open - 1]!]) open = openOf(t, open);
|
||||
if (open <= 0 || !IDENT.test(t[open - 1]!)) break;
|
||||
start = open;
|
||||
} else break;
|
||||
}
|
||||
if (calls) {
|
||||
let next = end;
|
||||
while (t[next] === " ") next++;
|
||||
if (t[next] === "(") {
|
||||
const close = closeOf(t, next);
|
||||
if (close > 0) end = close;
|
||||
}
|
||||
}
|
||||
const text = t.slice(start, end);
|
||||
if (!text || /^\d/.test(text)) return null;
|
||||
return { from: line.from + start, to: line.from + end, text };
|
||||
|
||||
@@ -79,6 +79,7 @@ function useLiveSessionCount(): number | null {
|
||||
export function activate(): () => void {
|
||||
useDebugRunSessions.setState({
|
||||
Console: lazyComponent(() => import("./ui/DebugConsole").then((m) => m.DebugServiceConsole)),
|
||||
View: lazyComponent(() => import("./ui/DebugToolWindow").then((m) => m.DebugServiceView)),
|
||||
});
|
||||
loadWatches(useProject.getState().project?.root ?? null);
|
||||
publishContext();
|
||||
@@ -88,7 +89,7 @@ export function activate(): () => void {
|
||||
loadJsBreakpoints(useProject.getState().project?.root ?? null);
|
||||
loadResponseOverrides(useProject.getState().project?.root ?? null);
|
||||
const disposers = [
|
||||
() => useDebugRunSessions.setState({ sessions: [], serviceSessions: [], Console: null }),
|
||||
() => useDebugRunSessions.setState({ sessions: [], serviceSessions: [], Console: null, View: null }),
|
||||
registerDebugActions(),
|
||||
registerDebugTabActions(),
|
||||
registerDevToolsWindows(),
|
||||
|
||||
@@ -29,6 +29,7 @@ import {
|
||||
maybeEditorService,
|
||||
notifications,
|
||||
runOutput,
|
||||
SERVICES_WINDOW,
|
||||
toolWindowService,
|
||||
useDebugRunSessions,
|
||||
} from "@/workbench/contributions";
|
||||
@@ -77,6 +78,8 @@ export interface DebugSession {
|
||||
process: RunId | null;
|
||||
/** Pinned tab (root sessions): once finished, a later session opens a new tab instead of taking its place. */
|
||||
pinned?: boolean;
|
||||
/** Started in place from the Services tool window (root sessions): its stops show it there, not in the Debug window. */
|
||||
inPlace?: boolean;
|
||||
status: SessionStatus;
|
||||
stoppedThread: number | null;
|
||||
stopReason: string | null;
|
||||
@@ -111,6 +114,8 @@ export interface ConsoleLine {
|
||||
text: string;
|
||||
/** `text` styled by its ANSI colours. */
|
||||
spans: Span[];
|
||||
/** A carriage return ended the output so far: the next text replaces the line. */
|
||||
cr?: boolean;
|
||||
}
|
||||
|
||||
interface DebugState {
|
||||
@@ -186,6 +191,12 @@ function ansiStream(session: DebugSessionId, category: string): AnsiStream {
|
||||
return stream;
|
||||
}
|
||||
|
||||
/** Styled output, keeping a carriage return (and erase-line) for the console to overwrite its line. */
|
||||
function outputSpans(session: DebugSessionId, category: string, raw: string): Span[] {
|
||||
const stream = ansiStream(session, category);
|
||||
return stream.spans(stream.clean(raw).replace(/\r\n/g, "\n"));
|
||||
}
|
||||
|
||||
// --- accessors ---------------------------------------------------------------
|
||||
|
||||
export function activeSession(): DebugSession | null {
|
||||
@@ -479,7 +490,7 @@ function unfollowProcessOutput(session: DebugSessionId) {
|
||||
export function appendConsole(session: DebugSessionId, category: string, raw: string) {
|
||||
if (!raw) return;
|
||||
flushConsoleOutput();
|
||||
const spans = ansiStream(session, category).parse(raw);
|
||||
const spans = outputSpans(session, category, raw);
|
||||
const text = spans.map((sp) => sp.text).join("");
|
||||
if (!text) return;
|
||||
useDebug.setState((s) => {
|
||||
@@ -522,7 +533,7 @@ function flushConsoleOutput() {
|
||||
const consoleBySession = { ...s.console };
|
||||
for (const { session, category, raw } of chunks) {
|
||||
if (!s.sessions[session]) continue;
|
||||
const spans = ansiStream(session, category).parse(raw);
|
||||
const spans = outputSpans(session, category, raw);
|
||||
const text = spans.map((sp) => sp.text).join("");
|
||||
if (!text) continue;
|
||||
printed.push([session, text]);
|
||||
@@ -645,26 +656,36 @@ async function openServerPage(server: DebugSession, known: ServerPage, url: stri
|
||||
else void stopSession(page);
|
||||
}
|
||||
|
||||
/** Split styled output at real line breaks, retaining partial lines across events. */
|
||||
/**
|
||||
* Split styled output at real line breaks, retaining partial lines across events. As in the
|
||||
* Run console, a carriage return makes the next text replace the line (progress bars).
|
||||
*/
|
||||
function appendConsoleLines(lines: ConsoleLine[], category: string, spans: Span[]) {
|
||||
const last = lines.at(-1);
|
||||
let line =
|
||||
last && last.category === category && !last.text.endsWith("\n") ? { ...last, spans: [...last.spans] } : undefined;
|
||||
if (line) lines[lines.length - 1] = line;
|
||||
for (const span of spans) {
|
||||
let start = 0;
|
||||
while (start < span.text.length) {
|
||||
const newline = span.text.indexOf("\n", start);
|
||||
const end = newline < 0 ? span.text.length : newline + 1;
|
||||
const text = span.text.slice(start, end);
|
||||
for (const piece of span.text.split(/(\r|\n)/)) {
|
||||
if (piece === "\r") {
|
||||
if (line) line.cr = true;
|
||||
continue;
|
||||
}
|
||||
if (!piece) continue;
|
||||
if (!line) {
|
||||
line = { id: ++lineSeq, category, text: "", spans: [] };
|
||||
lines.push(line);
|
||||
}
|
||||
line.text += text;
|
||||
line.spans = appendSpans(line.spans, [{ ...span, text }]);
|
||||
if (newline >= 0) line = undefined;
|
||||
start = end;
|
||||
if (line.cr) {
|
||||
line.cr = undefined;
|
||||
if (piece !== "\n") {
|
||||
line.text = "";
|
||||
line.spans = [];
|
||||
}
|
||||
}
|
||||
line.text += piece;
|
||||
line.spans = appendSpans(line.spans, [{ ...span, text: piece }]);
|
||||
if (piece === "\n") line = undefined;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -720,6 +741,7 @@ export async function startPreparedSession(
|
||||
adapter: config.debugAdapter ?? "",
|
||||
runConfig: config,
|
||||
pinned,
|
||||
inPlace: options.show === false,
|
||||
}),
|
||||
},
|
||||
console: { ...s.console, [id]: [] },
|
||||
@@ -821,6 +843,7 @@ export async function startSession(
|
||||
launch: options.rerunnable === false ? null : launch,
|
||||
process: options.process ?? null,
|
||||
pinned: preparation ? preparation.pinned : pinned,
|
||||
inPlace: options.show === false,
|
||||
status: cur.status === "starting" ? "running" : cur.status,
|
||||
},
|
||||
},
|
||||
@@ -942,11 +965,21 @@ export function pinSession(id: DebugSessionId, pinned: boolean) {
|
||||
patch(id, { pinned });
|
||||
}
|
||||
|
||||
/** Forgets a session and its children; a selected one passes the selection to the tab on its left. */
|
||||
/**
|
||||
* Forgets a session and its descendants (Node's `pnpm` → `pnpm.cjs` → `rspack.js`); a selected
|
||||
* one passes the selection to the tab on its left.
|
||||
*/
|
||||
export function removeSession(id: DebugSessionId) {
|
||||
const st = useDebug.getState();
|
||||
const gone = new Set<DebugSessionId>([id]);
|
||||
for (const s of Object.values(st.sessions)) if (s.parent === id) gone.add(s.id);
|
||||
for (let added = true; added;) {
|
||||
added = false;
|
||||
for (const s of Object.values(st.sessions))
|
||||
if (s.parent != null && gone.has(s.parent) && !gone.has(s.id)) {
|
||||
gone.add(s.id);
|
||||
added = true;
|
||||
}
|
||||
}
|
||||
|
||||
const order = Object.values(st.sessions).map((s) => s.id);
|
||||
const sessions: Record<number, DebugSession> = {};
|
||||
@@ -984,13 +1017,12 @@ export async function rerunSession(id: DebugSessionId, options: { show?: boolean
|
||||
if (!root.runConfig && !launch) return;
|
||||
if (isLive(root)) await stopSession(root.id);
|
||||
rerunOf = root.id;
|
||||
// A session debugged in place from Services reruns there too.
|
||||
const show = options.show ?? (root.inPlace ? false : undefined);
|
||||
try {
|
||||
if (root.runConfig)
|
||||
await executeAction(
|
||||
"run.debugConfig",
|
||||
options.show === false ? { config: root.runConfig, show: false } : root.runConfig,
|
||||
);
|
||||
else await startSession(launch!, { show: options.show });
|
||||
await executeAction("run.debugConfig", show === false ? { config: root.runConfig, show: false } : root.runConfig);
|
||||
else await startSession(launch!, { show });
|
||||
} finally {
|
||||
rerunOf = null;
|
||||
}
|
||||
@@ -1364,7 +1396,8 @@ export function handleDebugEvent(id: DebugSessionId, event: DebugEvent) {
|
||||
void loadFrames(id, event.threadId, !markTraceStop(id, event.threadId, s.stops + 1));
|
||||
const dbg = workflowSettings().debugger;
|
||||
try {
|
||||
if (dbg.showOnBreakpoint) toolWindowService().show("debug");
|
||||
// A session debugged in place from Services shows its debugger there (#4773).
|
||||
if (dbg.showOnBreakpoint) toolWindowService().show(rootOf(s).inPlace ? SERVICES_WINDOW : "debug");
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
|
||||
@@ -353,3 +353,15 @@
|
||||
border-bottom: 0;
|
||||
border-top: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.serviceView {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.serviceView > * {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
/** Debug tool window: toolbar, Threads & Variables (frames + variables), Console. */
|
||||
import { writeClipboardText } from "@/platform/clipboard";
|
||||
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";
|
||||
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
|
||||
import clsx from "clsx";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { basename, useProject } from "@/platform/project";
|
||||
@@ -173,7 +173,35 @@ export function DebugTabs() {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Services › a configuration being debugged: the same debugger as the Debug tool window, for
|
||||
* that session (#4773). `console` replaces the Console tab, e.g. with the console of the run the
|
||||
* debugger is attached to.
|
||||
*/
|
||||
export function DebugServiceView({ sessionId, console: consolePane }: { sessionId: number; console?: ReactNode }) {
|
||||
const shown = useDebug((s) => {
|
||||
const active = s.active != null ? s.sessions[s.active] : undefined;
|
||||
return !!active && rootOf(active).id === sessionId;
|
||||
});
|
||||
useEffect(() => {
|
||||
if (useDebug.getState().sessions[sessionId]) selectSession(sessionId);
|
||||
}, [sessionId]);
|
||||
// The toolbar acts on the active session: using this view makes its session the active one again.
|
||||
const reselect = () => {
|
||||
if (!shown && useDebug.getState().sessions[sessionId]) selectSession(sessionId);
|
||||
};
|
||||
return (
|
||||
<div className={styles.serviceView} onPointerDownCapture={reselect} onFocusCapture={reselect}>
|
||||
{shown && <DebugView consolePane={consolePane} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function DebugToolWindow() {
|
||||
return <DebugView />;
|
||||
}
|
||||
|
||||
function DebugView({ consolePane }: { consolePane?: ReactNode }) {
|
||||
const tx = useTx();
|
||||
const active = useDebug((s) => (s.active != null ? s.sessions[s.active] : undefined));
|
||||
const muted = useBreakpoints((s) => s.muted);
|
||||
@@ -314,7 +342,7 @@ export function DebugToolWindow() {
|
||||
) : tab === "network" ? (
|
||||
<NetworkView key={active.id} session={active.id} />
|
||||
) : (
|
||||
<DebugConsole key={active.id} session={active} />
|
||||
(consolePane ?? <DebugConsole key={active.id} session={active} />)
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -19,7 +19,7 @@ import { FileRefactorDialogHost } from "./FileRefactorDialogs";
|
||||
import { setRefactorBackendForTests } from "./fileRefactor";
|
||||
import { ProjectView } from "./ProjectView";
|
||||
import { beginNew, canPaste } from "./operations";
|
||||
import { initProjectTree, setViewOption, useProjectTree } from "./store";
|
||||
import { initProjectTree, selectModel, setSelection, setViewOption, useProjectTree } from "./store";
|
||||
import type { OutlineItem } from "@/bindings";
|
||||
import { _emitEditorEvent, useEditorRegistry } from "@/editor/api";
|
||||
import { ProjectHeaderActions } from "./HeaderActions";
|
||||
@@ -34,6 +34,12 @@ vi.mock("@/bindings", async (orig) => {
|
||||
const real = await orig<typeof import("@/bindings")>();
|
||||
return { ...real, commands: { ...real.commands, ...ipc } };
|
||||
});
|
||||
const dragOut = vi.hoisted(() => ({
|
||||
canDragOut: vi.fn(() => false),
|
||||
dragOut: vi.fn(async (_paths: readonly string[]) => true),
|
||||
isDraggingOut: vi.fn(() => false),
|
||||
}));
|
||||
vi.mock("@/platform/dragOut", () => dragOut);
|
||||
|
||||
const ok = <T,>(data: T) => ({ status: "ok" as const, data });
|
||||
const item = (name: string, kind: OutlineItem["kind"], line: number, children: OutlineItem[] = []): OutlineItem => {
|
||||
@@ -392,6 +398,67 @@ describe("ProjectView", () => {
|
||||
expect(ghost()).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps the tree from scrolling sideways during a drag", async () => {
|
||||
const { tree, row, rows } = setup();
|
||||
await waitFor(() => expect(rows()).toContain("README.md"));
|
||||
document.elementFromPoint = () => null;
|
||||
fireEvent(
|
||||
row("README.md").querySelector("[data-project-path]")!,
|
||||
new MouseEvent("pointerdown", { bubbles: true, button: 0 }),
|
||||
);
|
||||
act(() => void window.dispatchEvent(new MouseEvent("pointermove", { buttons: 1, clientX: 40, clientY: 0 })));
|
||||
// WebKit's autoscroll toward a pointer right of the tree.
|
||||
tree.scrollLeft = 600;
|
||||
fireEvent.scroll(tree);
|
||||
expect(tree.scrollLeft).toBe(0);
|
||||
act(() => void window.dispatchEvent(new MouseEvent("pointerup", { bubbles: true })));
|
||||
});
|
||||
|
||||
it("hands the selected files to an OS drag once the pointer leaves the window", async () => {
|
||||
const { row, rows } = setup();
|
||||
await waitFor(() => expect(rows()).toContain("README.md"));
|
||||
document.elementFromPoint = () => null;
|
||||
const model = selectModel(useProjectTree.getState());
|
||||
const keys = [`${ROOT}/README.md`, `${ROOT}/src`].map((p) => model.keyOfPath.get(p)!);
|
||||
act(() => setSelection(new Set(keys), keys[0]!));
|
||||
const ghost = () => screen.queryByText("2 items");
|
||||
const press = () =>
|
||||
fireEvent(
|
||||
row("README.md").querySelector("[data-project-path]")!,
|
||||
new MouseEvent("pointerdown", { bubbles: true, button: 0 }),
|
||||
);
|
||||
const move = (x: number) =>
|
||||
act(() => {
|
||||
window.dispatchEvent(new MouseEvent("pointermove", { bubbles: true, buttons: 1, clientX: x, clientY: 10 }));
|
||||
});
|
||||
const release = () => act(() => void window.dispatchEvent(new MouseEvent("pointerup", { bubbles: true })));
|
||||
try {
|
||||
// Where files can't leave (a remote project, the browser), the drag stays in the window.
|
||||
press();
|
||||
move(40);
|
||||
move(-5);
|
||||
expect(ghost()).not.toBeNull();
|
||||
release();
|
||||
expect(dragOut.dragOut).not.toHaveBeenCalled();
|
||||
|
||||
dragOut.canDragOut.mockReturnValue(true);
|
||||
press();
|
||||
move(40);
|
||||
expect(ghost()).not.toBeNull();
|
||||
expect(dragOut.dragOut).not.toHaveBeenCalled();
|
||||
move(window.innerWidth + 5);
|
||||
expect(dragOut.dragOut).toHaveBeenCalledExactlyOnceWith([`${ROOT}/README.md`, `${ROOT}/src`]);
|
||||
// The OS drag owns the pointer now: the in-window drag is over.
|
||||
expect(ghost()).toBeNull();
|
||||
move(-5);
|
||||
release();
|
||||
expect(dragOut.dragOut).toHaveBeenCalledOnce();
|
||||
} finally {
|
||||
dragOut.canDragOut.mockReturnValue(false);
|
||||
dragOut.dragOut.mockClear();
|
||||
}
|
||||
});
|
||||
|
||||
it("cancels a new file when its name field loses focus", async () => {
|
||||
const { rows } = setup();
|
||||
await waitFor(() => expect(rows()).toContain("README.md"));
|
||||
|
||||
@@ -23,6 +23,7 @@ import { revealRange, useEditorRegistry } from "@/editor/api";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { tx, useTxTemplate } from "@/platform/i18n";
|
||||
import { isTauri } from "@/platform/ipc";
|
||||
import { canDragOut, dragOut, isDraggingOut } from "@/platform/dragOut";
|
||||
import { nativeDropPoint } from "@/platform/nativeDrop";
|
||||
import type { RootFolder } from "@/platform/languageSettings";
|
||||
import { useDetectedRoots, useEffectiveRoots } from "@/platform/projectRoots";
|
||||
@@ -42,6 +43,7 @@ import {
|
||||
Popup,
|
||||
beginDrag,
|
||||
dragSession,
|
||||
isOutsideWindow,
|
||||
registerDropTarget,
|
||||
Tree,
|
||||
acquirePopup,
|
||||
@@ -660,6 +662,8 @@ export function ProjectView() {
|
||||
startY = e.clientY;
|
||||
let active = false;
|
||||
let paths: string[] = [];
|
||||
// What an OS drag out of the window carries: groups ("External Libraries") have no folder.
|
||||
let outPaths: string[] = [];
|
||||
// Files and folders can be dropped on the agent composer as references; an
|
||||
// editor opens only files, so folders carry the trailing slash `findDirs`
|
||||
// uses and the editor leaves them out.
|
||||
@@ -668,9 +672,11 @@ export function ProjectView() {
|
||||
// While dragging, the tree scrolls only when the pointer is near its top or bottom edge
|
||||
// (IDEA's DnD autoscroll). Leaving the tree toward a drop target elsewhere (the terminal,
|
||||
// an editor) keeps it where it is: WebKit's own autoscroll of the pressed scroll container
|
||||
// would otherwise keep scrolling it toward the pointer.
|
||||
// would otherwise keep scrolling it toward the pointer. It never scrolls sideways: a pointer
|
||||
// right of the tree would scroll its long rows out of view.
|
||||
const scroller = containerRef.current?.querySelector<HTMLElement>('[role="tree"]') ?? null;
|
||||
let held = scroller?.scrollTop ?? 0;
|
||||
const heldLeft = scroller?.scrollLeft ?? 0;
|
||||
let pointer: { x: number; y: number } | null = null;
|
||||
let frame = 0;
|
||||
const inside = (p: { x: number; y: number }) => {
|
||||
@@ -681,6 +687,7 @@ export function ProjectView() {
|
||||
if (!scroller) return;
|
||||
if (pointer && !inside(pointer)) scroller.scrollTop = held;
|
||||
else held = scroller.scrollTop;
|
||||
if (scroller.scrollLeft !== heldLeft) scroller.scrollLeft = heldLeft;
|
||||
};
|
||||
const edgeScroll = () => {
|
||||
frame = 0;
|
||||
@@ -712,12 +719,21 @@ export function ProjectView() {
|
||||
if (before.has(node.key)) setSelection(before, lead);
|
||||
const nodes = keys.map((k) => m.byKey.get(k)).filter((n): n is ProjectNode => !!n && !n.root && !n.placeholder);
|
||||
paths = nodes.map((n) => n.path);
|
||||
outPaths = nodes.filter((n) => !n.group).map((n) => n.path);
|
||||
if (!paths.length) return cleanup();
|
||||
files = dragSession({
|
||||
type: FILES_DRAG,
|
||||
payload: nodes.map((n) => (n.dir ? `${n.path}/` : n.path)).join("\n"),
|
||||
});
|
||||
}
|
||||
// Leaving the window hands the files to an OS drag: the app they land on copies them.
|
||||
const viewport = { left: 0, top: 0, right: window.innerWidth, bottom: window.innerHeight };
|
||||
if (outPaths.length && canDragOut() && isOutsideWindow(viewport, ev.clientX, ev.clientY)) {
|
||||
const out = outPaths;
|
||||
cleanup();
|
||||
void dragOut(out);
|
||||
return;
|
||||
}
|
||||
if (!pointer) scroller?.addEventListener("scroll", keep, { passive: true });
|
||||
pointer = { x: ev.clientX, y: ev.clientY };
|
||||
keep();
|
||||
@@ -779,6 +795,7 @@ export function ProjectView() {
|
||||
void import("@tauri-apps/api/webview").then(({ getCurrentWebview }) =>
|
||||
getCurrentWebview()
|
||||
.onDragDropEvent((event) => {
|
||||
if (isDraggingOut()) return;
|
||||
const p = event.payload;
|
||||
if (p.type === "leave") return setDropTarget(null);
|
||||
const { x, y } = nativeDropPoint(p.position);
|
||||
|
||||
@@ -34,6 +34,7 @@ import {
|
||||
import { useContributions, type RunConfigTypeContribution } from "@/workbench/contributions";
|
||||
import { TASK_LABELS, taskLabel, type BeforeLaunchKind } from "./beforeLaunch";
|
||||
import { ExpandableTextarea } from "./ExpandableTextarea";
|
||||
import { CWD_MACROS } from "./cwdMacros";
|
||||
import {
|
||||
commandLine,
|
||||
compoundCycle,
|
||||
@@ -245,6 +246,65 @@ function BrowseButton({
|
||||
);
|
||||
}
|
||||
|
||||
const CWD_MACRO_LABELS: Record<(typeof CWD_MACROS)[number], string> = {
|
||||
PROJECT_DIR: "Project root",
|
||||
ContentRoot: "Content root",
|
||||
MODULE_DIR: "Module directory",
|
||||
MODULE_WORKING_DIR: "Module working directory",
|
||||
USER_HOME: "User home directory",
|
||||
};
|
||||
|
||||
/** Inserts a path macro at the caret of the working directory field. */
|
||||
function CwdMacroButton({
|
||||
input,
|
||||
onInsert,
|
||||
}: {
|
||||
input: RefObject<HTMLInputElement | null>;
|
||||
onInsert: (v: string) => void;
|
||||
}) {
|
||||
const tx = useTx();
|
||||
const ref = useRef<HTMLButtonElement>(null);
|
||||
const [open, setOpen] = useState(false);
|
||||
const insert = (macro: string) => {
|
||||
const el = input.current;
|
||||
const value = el?.value ?? "";
|
||||
const from = el?.selectionStart ?? value.length;
|
||||
const to = el?.selectionEnd ?? from;
|
||||
onInsert(value.slice(0, from) + macro + value.slice(to));
|
||||
requestAnimationFrame(() => {
|
||||
el?.focus();
|
||||
el?.setSelectionRange(from + macro.length, from + macro.length);
|
||||
});
|
||||
};
|
||||
return (
|
||||
<>
|
||||
<IconButton
|
||||
ref={ref}
|
||||
icon="plus"
|
||||
size="small"
|
||||
iconSize={14}
|
||||
title={tx("Insert Macro…")}
|
||||
aria-haspopup="menu"
|
||||
aria-expanded={open}
|
||||
onClick={() => setOpen((o) => !o)}
|
||||
/>
|
||||
<Menu
|
||||
open={open}
|
||||
onClose={() => setOpen(false)}
|
||||
anchor={ref}
|
||||
placement="bottom-end"
|
||||
aria-label={tx("Macros")}
|
||||
items={CWD_MACROS.filter((m) => m !== "USER_HOME" || !isRemoteWindow()).map((m) => ({
|
||||
id: m,
|
||||
label: `$${m}$`,
|
||||
shortcut: tx(CWD_MACRO_LABELS[m]),
|
||||
run: () => insert(`$${m}$`),
|
||||
}))}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function ConfigForm({ config, all, type, errors, template, onChange, modifyRequest }: ConfigFormProps) {
|
||||
const openByDefault = useWorkflowSettings((s) => s.run.showOnStart);
|
||||
const externalTools = useWorkflowSettings((s) => s.externalTools);
|
||||
@@ -253,6 +313,7 @@ export function ConfigForm({ config, all, type, errors, template, onChange, modi
|
||||
const tx = useTx();
|
||||
const txTemplate = useTxTemplate();
|
||||
const root = useProject((s) => s.project?.root ?? null);
|
||||
const cwdInput = useRef<HTMLInputElement>(null);
|
||||
const gradle = useBuildModel((s) => s.model?.gradle);
|
||||
const runUsing = useProject((s) => s.settings?.languages?.java?.gradle?.runUsing);
|
||||
const delegated =
|
||||
@@ -566,12 +627,14 @@ export function ConfigForm({ config, all, type, errors, template, onChange, modi
|
||||
<Field label="Working directory" error={errors.cwd}>
|
||||
<div className={styles.inputWithButton}>
|
||||
<Input
|
||||
ref={cwdInput}
|
||||
mono
|
||||
aria-label="Working directory"
|
||||
value={config.cwd ?? ""}
|
||||
placeholder="Project root"
|
||||
onChange={(e) => update({ cwd: e.target.value.trim() ? e.target.value : null })}
|
||||
/>
|
||||
<CwdMacroButton input={cwdInput} onInsert={(cwd) => update({ cwd })} />
|
||||
<BrowseButton
|
||||
directory
|
||||
title="Browse…"
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { expandCwd } from "./cwdMacros";
|
||||
|
||||
const ctx = { root: "/work/app/", module: "services/api", home: "/Users/me" };
|
||||
|
||||
describe("working directory macros (#4755)", () => {
|
||||
it("expands the project, module and home folders", () => {
|
||||
expect(expandCwd("$PROJECT_DIR$/web", ctx)).toEqual({ cwd: "/work/app/web" });
|
||||
expect(expandCwd("$ContentRoot$", ctx)).toEqual({ cwd: "/work/app" });
|
||||
expect(expandCwd("$MODULE_DIR$/bin", ctx)).toEqual({ cwd: "/work/app/services/api/bin" });
|
||||
expect(expandCwd("$MODULE_WORKING_DIR$", ctx)).toEqual({ cwd: "/work/app/services/api" });
|
||||
expect(expandCwd("$USER_HOME$/scratch", ctx)).toEqual({ cwd: "/Users/me/scratch" });
|
||||
});
|
||||
|
||||
it("uses the project folder as the module folder when there is no module", () => {
|
||||
expect(expandCwd("$MODULE_DIR$", { ...ctx, module: null })).toEqual({ cwd: "/work/app" });
|
||||
expect(expandCwd("$MODULE_DIR$", { ...ctx, module: "/elsewhere/mod" })).toEqual({ cwd: "/elsewhere/mod" });
|
||||
});
|
||||
|
||||
it("leaves a path without macros as it is", () => {
|
||||
expect(expandCwd("server", ctx)).toEqual({ cwd: "server" });
|
||||
expect(expandCwd("/abs/$dollar", ctx)).toEqual({ cwd: "/abs/$dollar" });
|
||||
});
|
||||
|
||||
it("names an unknown macro and one without a value", () => {
|
||||
const unknown = expandCwd("$PROJECT_ROOT$/web", ctx);
|
||||
expect("error" in unknown && unknown.error).toContain("$PROJECT_ROOT$");
|
||||
expect("error" in unknown && unknown.error).toContain("$PROJECT_DIR$");
|
||||
const remote = expandCwd("$USER_HOME$", { ...ctx, home: null });
|
||||
expect(remote).toEqual({ error: "$USER_HOME$ is not available in a remote project." });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,80 @@
|
||||
/**
|
||||
* Path macros in a run configuration's working directory (`$PROJECT_DIR$/web`), expanded when
|
||||
* it runs or is debugged; the stored value keeps them, so the configuration moves with the project.
|
||||
*/
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { isTauri, type RunConfig } from "@/platform/ipc";
|
||||
import { isRemoteWindow } from "@/platform/remote";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
|
||||
const MACRO = /\$([A-Za-z_][A-Za-z0-9_]*)\$/g;
|
||||
|
||||
/** The macros a working directory may use. */
|
||||
export const CWD_MACROS = ["PROJECT_DIR", "ContentRoot", "MODULE_DIR", "MODULE_WORKING_DIR", "USER_HOME"] as const;
|
||||
|
||||
export interface CwdContext {
|
||||
root: string;
|
||||
/** The configuration's module directory, absolute or relative to `root`. */
|
||||
module?: string | null;
|
||||
/** The user's home folder; null where it isn't known (a remote project). */
|
||||
home: string | null;
|
||||
}
|
||||
|
||||
const absolute = (p: string) => p.startsWith("/") || /^[A-Za-z]:[\\/]/.test(p) || p.startsWith("\\\\");
|
||||
const trimEnd = (p: string) => p.replace(/[\\/]+$/, "");
|
||||
const join = (root: string, p: string) => (absolute(p) ? p : `${trimEnd(root)}/${p.replace(/^\.[\\/]/, "")}`);
|
||||
|
||||
/** `cwd` with its macros replaced; an error names a macro that is unknown or has no value here. */
|
||||
export function expandCwd(cwd: string, ctx: CwdContext): { cwd: string } | { error: string } {
|
||||
let error: string | null = null;
|
||||
const module = ctx.module ? join(ctx.root, ctx.module) : ctx.root;
|
||||
const values: Record<string, string | null> = {
|
||||
PROJECT_DIR: ctx.root,
|
||||
ContentRoot: ctx.root,
|
||||
MODULE_DIR: module,
|
||||
MODULE_WORKING_DIR: module,
|
||||
USER_HOME: ctx.home,
|
||||
};
|
||||
const out = cwd.replace(MACRO, (all, name: string) => {
|
||||
const value = Object.hasOwn(values, name) ? values[name] : undefined;
|
||||
if (value) return trimEnd(value);
|
||||
const supported = CWD_MACROS.map((m) => `$${m}$`).join(", ");
|
||||
error ??=
|
||||
value === undefined
|
||||
? tx`Unknown macro ${all} in the working directory. Supported: ${supported}.`
|
||||
: tx`${all} is not available in a remote project.`;
|
||||
return all;
|
||||
});
|
||||
return error ? { error } : { cwd: out };
|
||||
}
|
||||
|
||||
let home: Promise<string | null> | null = null;
|
||||
const homeDir = () =>
|
||||
(home ??= isTauri()
|
||||
? import("@tauri-apps/api/path").then((m) => m.homeDir()).catch(() => null)
|
||||
: Promise.resolve(null));
|
||||
|
||||
/** `config` with the macros of its working directory expanded; throws when one can't be. */
|
||||
export async function withExpandedCwd(config: RunConfig): Promise<RunConfig> {
|
||||
const cwd = config.cwd;
|
||||
if (!cwd?.includes("$")) return config;
|
||||
const root = useProject.getState().project?.root;
|
||||
if (!root) return config;
|
||||
const result = expandCwd(cwd, {
|
||||
root,
|
||||
module: config.module,
|
||||
home: isRemoteWindow() ? null : await homeDir(),
|
||||
});
|
||||
if ("error" in result) throw new Error(result.error);
|
||||
return { ...config, cwd: result.cwd };
|
||||
}
|
||||
|
||||
export function notifyCwdError(config: RunConfig, error: unknown) {
|
||||
notifications().notify({
|
||||
group: "run",
|
||||
level: "error",
|
||||
title: tx`Cannot start '${config.name}'`,
|
||||
body: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
}
|
||||
@@ -37,6 +37,7 @@ import {
|
||||
runContextAction,
|
||||
} from "./contextRun";
|
||||
import { runWithExecutor } from "./executors";
|
||||
import { notifyCwdError, withExpandedCwd } from "./cwdMacros";
|
||||
import { debugWithAgent, jdwpLaunch } from "./javaDebug";
|
||||
import { attachesToChild, debugAttachingToChild } from "./pluginAttach";
|
||||
import { RunDialogsOverlay } from "./dialogs";
|
||||
@@ -184,6 +185,11 @@ async function debugConfig(config: RunConfig, chain: readonly string[] = [], sho
|
||||
}
|
||||
|
||||
async function debugLaunch(config: RunConfig, chain: readonly string[], show?: boolean): Promise<void> {
|
||||
try {
|
||||
config = await withExpandedCwd(config);
|
||||
} catch (e) {
|
||||
return notifyCwdError(config, e);
|
||||
}
|
||||
if (!(await prepareLaunch(config, chain, show))) return;
|
||||
if (config.kind === UNITY_CONFIG_KIND) return showUnityAttach(config);
|
||||
// Python on a Docker / Compose target: debugpy in the container, the debugger attaches.
|
||||
|
||||
@@ -116,6 +116,27 @@ describe("configuration types", () => {
|
||||
expect(change.mock.calls.at(-1)?.[0]).toMatchObject({ args: ["-Xmx1g", "-jar", "new.jar", "hello"] });
|
||||
});
|
||||
|
||||
it("inserts a path macro at the caret of the working directory (#4755)", () => {
|
||||
const type = typeFor("jar-application")!;
|
||||
const config = withParams(newConfigOfType(type, []), { jarPath: "app.jar" });
|
||||
const change = vi.fn();
|
||||
render(
|
||||
<ConfigForm
|
||||
config={{ ...config, cwd: "/web" }}
|
||||
all={[]}
|
||||
type={type}
|
||||
errors={{}}
|
||||
onChange={change}
|
||||
modifyRequest={0}
|
||||
/>,
|
||||
);
|
||||
const field = screen.getByLabelText<HTMLInputElement>("Working directory");
|
||||
field.setSelectionRange(0, 0);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Insert Macro…" }));
|
||||
fireEvent.click(screen.getByRole("menuitem", { name: /\$PROJECT_DIR\$/ }));
|
||||
expect(change.mock.calls.at(-1)?.[0]).toMatchObject({ cwd: "$PROJECT_DIR$/web" });
|
||||
});
|
||||
|
||||
it("runs an Application with the chosen JRE and the classpath of the chosen module", () => {
|
||||
const type = typeFor("application")!;
|
||||
const base = withParams(newConfigOfType(type, []), { ...newConfigOfType(type, []).params, mainClass: "a.Main" });
|
||||
|
||||
@@ -757,7 +757,7 @@ function RunDetail({ item }: { item: ServiceTreeItem }) {
|
||||
// Re-render on session changes.
|
||||
useRun((s) => s.sessions);
|
||||
const debugViews = useDebugRunSessions();
|
||||
const Console = debugViews.Console;
|
||||
const { Console, View } = debugViews;
|
||||
const t = useT();
|
||||
const txTemplate = useTxTemplate();
|
||||
const r = resolve(item);
|
||||
@@ -773,11 +773,14 @@ function RunDetail({ item }: { item: ServiceTreeItem }) {
|
||||
);
|
||||
// The configuration ran: its console, as in the Run tool window. Run / Debug / Stop
|
||||
// come from this window's toolbar (the selection), so the console strip leaves them out.
|
||||
if (r.session?.run) {
|
||||
const execution = r.session;
|
||||
return <SessionPanel key={execution.run!.id} session={execution.run!} showLifecycle={false} />;
|
||||
}
|
||||
const execution = r.session?.run;
|
||||
const runConsole = execution && <SessionPanel key={execution.id} session={execution} showLifecycle={false} />;
|
||||
const d = r.session?.debug[0];
|
||||
// Being debugged: the whole debugger in place, as in IDEA's Services (#4773); the console of a
|
||||
// run the debugger is attached to stays its Console tab.
|
||||
if (d && View && (d.status !== "terminated" || !execution))
|
||||
return <View key={d.id} sessionId={d.id} console={runConsole} />;
|
||||
if (runConsole) return runConsole;
|
||||
if (d && Console)
|
||||
return (
|
||||
<div className={styles.debugConsole}>
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
* per-session `ConsoleModel`, batched per animation frame.
|
||||
*/
|
||||
import { withRunTarget } from "@/platform/runTargetSelection";
|
||||
import { notifyCwdError, withExpandedCwd } from "./cwdMacros";
|
||||
import { create } from "zustand";
|
||||
import { Channel } from "@tauri-apps/api/core";
|
||||
import {
|
||||
@@ -847,6 +848,12 @@ async function startRunIn(
|
||||
options: StartRunOptions,
|
||||
): Promise<RunSession | null> {
|
||||
config = withRunTarget(config);
|
||||
try {
|
||||
config = await withExpandedCwd(config);
|
||||
} catch (e) {
|
||||
notifyCwdError(config, e);
|
||||
return null;
|
||||
}
|
||||
if (!options.launch && isCMakeBuild(config)) {
|
||||
await buildCMake(config.id, options.show !== false);
|
||||
return null;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { fireEvent, render, screen, within } from "@testing-library/react";
|
||||
import { usePlatform } from "@/platform/platformInfo";
|
||||
import { ToolWindowShownProvider, useServiceProviders, type ServiceTreeItem } from "@/workbench/contributions";
|
||||
import { ServicesTreeView } from "./ServicesTree";
|
||||
import { useServicesTree } from "./tree";
|
||||
@@ -54,19 +55,29 @@ function setup() {
|
||||
}
|
||||
|
||||
describe("Services selection → actions", () => {
|
||||
it.each(["ctrlKey", "metaKey"])("%s toggles rows and Run applies to the selection", (modifier) => {
|
||||
const { row, selected, toolbar } = setup();
|
||||
fireEvent.mouseDown(row("one"));
|
||||
fireEvent.mouseDown(row("two"), { [modifier]: true });
|
||||
expect(selected()).toEqual(["one", "two"]);
|
||||
expect(screen.getByTestId("detail")).toHaveTextContent("two");
|
||||
fireEvent.click(within(toolbar).getByRole("button", { name: "Run" }));
|
||||
expect(run.mock.calls).toEqual([["one"], ["two"]]);
|
||||
fireEvent.mouseDown(row("one"), { [modifier]: true });
|
||||
expect(selected()).toEqual(["two"]);
|
||||
fireEvent.mouseDown(row("two"), { [modifier]: true });
|
||||
expect(selected()).toEqual([]);
|
||||
expect(screen.queryByTestId("detail")).not.toBeInTheDocument();
|
||||
it.each([
|
||||
{ os: "macos", modifier: "metaKey" },
|
||||
{ os: "windows", modifier: "ctrlKey" },
|
||||
{ os: "linux", modifier: "ctrlKey" },
|
||||
])("$modifier on $os toggles rows and Run applies to the selection", ({ os, modifier }) => {
|
||||
const previousOs = usePlatform.getState().os;
|
||||
usePlatform.setState({ os });
|
||||
try {
|
||||
const { row, selected, toolbar } = setup();
|
||||
fireEvent.mouseDown(row("one"));
|
||||
fireEvent.mouseDown(row("two"), { [modifier]: true });
|
||||
expect(selected()).toEqual(["one", "two"]);
|
||||
expect(screen.getByTestId("detail")).toHaveTextContent("two");
|
||||
fireEvent.click(within(toolbar).getByRole("button", { name: "Run" }));
|
||||
expect(run.mock.calls).toEqual([["one"], ["two"]]);
|
||||
fireEvent.mouseDown(row("one"), { [modifier]: true });
|
||||
expect(selected()).toEqual(["two"]);
|
||||
fireEvent.mouseDown(row("two"), { [modifier]: true });
|
||||
expect(selected()).toEqual([]);
|
||||
expect(screen.queryByTestId("detail")).not.toBeInTheDocument();
|
||||
} finally {
|
||||
usePlatform.setState({ os: previousOs });
|
||||
}
|
||||
});
|
||||
|
||||
it("tells the provider which node became the lead selection", () => {
|
||||
|
||||
@@ -65,7 +65,7 @@ function SpellingPage() {
|
||||
<Row
|
||||
label="Dictionary files"
|
||||
stacked
|
||||
hint="Plain-text word lists (one word per line) or Hunspell .dic files. Relative paths resolve against the project root, ~/ against the home folder."
|
||||
hint="Plain-text word lists (one word per line) or Hunspell .dic files; a .dic with its .aff beside it also accepts the inflected forms and compounds its rules allow. Relative paths resolve against the project root, ~/ against the home folder."
|
||||
>
|
||||
<GlobListEditor
|
||||
aria-label="Custom dictionaries"
|
||||
|
||||
@@ -93,6 +93,10 @@
|
||||
text-overflow: ellipsis;
|
||||
color: var(--fg-subtle);
|
||||
}
|
||||
.nodeCount {
|
||||
flex: none;
|
||||
color: var(--fg-subtle);
|
||||
}
|
||||
.detailIcon {
|
||||
flex: none;
|
||||
--icon-color: var(--fg-subtle);
|
||||
|
||||
@@ -1002,7 +1002,7 @@ export function ChangesTree({ mode }: { mode: "commit" | "local" | "dialog" }) {
|
||||
/>
|
||||
)}
|
||||
{label}
|
||||
{n.type === "group" && <span className={styles.detail}>{fileCount(n.files.length)}</span>}
|
||||
{n.type !== "file" && <span className={styles.nodeCount}>{fileCount(n.files.length)}</span>}
|
||||
{!staging && n.type === "file" && n.files[0] && isPartiallyStaged(n.files[0]) && (
|
||||
<span className={styles.partial} title={tx("Partially staged: only staged hunks are committed")}>
|
||||
<T>partial</T>
|
||||
|
||||
@@ -24,6 +24,7 @@ import { CommitDetails } from "./log/CommitDetails";
|
||||
import { CommitList } from "./log/CommitList";
|
||||
import { FilterBar } from "./log/FilterBar";
|
||||
import { useLogRepositories, useReadOnlyLog } from "./log/logHooks";
|
||||
import { PANE_STYLE } from "./log/shared";
|
||||
import { LogIdContext } from "./logContext";
|
||||
import { invalidateLogDetails } from "./logDetails";
|
||||
import { useLogOptions } from "./logOptions";
|
||||
@@ -223,13 +224,13 @@ export function LogView() {
|
||||
>
|
||||
{showBranches && (
|
||||
<>
|
||||
<SplitPanel id="branches" defaultSize="18%" minSize="120px">
|
||||
<SplitPanel id="branches" style={PANE_STYLE} defaultSize="18%" minSize="120px">
|
||||
<BranchesPanel />
|
||||
</SplitPanel>
|
||||
<SplitHandle />
|
||||
</>
|
||||
)}
|
||||
<SplitPanel id="commits" defaultSize="54%" minSize="25%">
|
||||
<SplitPanel id="commits" style={PANE_STYLE} defaultSize="54%" minSize="25%">
|
||||
<div className={styles.log}>
|
||||
<FilterBar />
|
||||
<CommitList />
|
||||
@@ -238,7 +239,7 @@ export function LogView() {
|
||||
{showDetails && (
|
||||
<>
|
||||
<SplitHandle />
|
||||
<SplitPanel id="details" defaultSize="28%" minSize="15%">
|
||||
<SplitPanel id="details" style={PANE_STYLE} defaultSize="28%" minSize="15%">
|
||||
<CommitDetails key={selection.join(" ") || "none"} commits={commits} />
|
||||
</SplitPanel>
|
||||
</>
|
||||
|
||||
@@ -10,6 +10,7 @@ vi.mock("../DiffEditor", () => ({ DiffEditor: () => <div /> }));
|
||||
|
||||
import { ChangesTree } from "../CommitView";
|
||||
import { useVcs } from "../store";
|
||||
import { useCommit } from "../commitStore";
|
||||
import { useProject } from "@/platform/project";
|
||||
|
||||
const change = (path: string) => ({
|
||||
@@ -26,6 +27,7 @@ const row = (name: string) => screen.getByText(name).closest('[role="treeitem"]'
|
||||
describe("repository nodes in the changes tree", () => {
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
useCommit.setState({ groupByDir: false, groupByRepo: true });
|
||||
useProject.setState({
|
||||
project: { name: "p", root: "/p", trusted: true, isGit: true, settings: {} } as never,
|
||||
settings: {} as never,
|
||||
@@ -41,7 +43,7 @@ describe("repository nodes in the changes tree", () => {
|
||||
|
||||
it("shows the branch each repository is on and follows branch switches", () => {
|
||||
render(<ChangesTree mode="commit" />);
|
||||
expect(row("orders").textContent).toBe("orders");
|
||||
expect(row("orders").textContent).toBe("orders1 file");
|
||||
act(() =>
|
||||
useVcs.setState({
|
||||
heads: {
|
||||
@@ -50,14 +52,35 @@ describe("repository nodes in the changes tree", () => {
|
||||
},
|
||||
}),
|
||||
);
|
||||
expect(row("orders").textContent).toBe("ordersfeature/ABC-123");
|
||||
expect(row("p").textContent).toBe("pmain");
|
||||
expect(row("orders").textContent).toBe("orders1 filefeature/ABC-123");
|
||||
expect(row("p").textContent).toBe("p1 filemain");
|
||||
act(() =>
|
||||
useVcs.setState({
|
||||
heads: { ...useVcs.getState().heads, "/p/orders": { head: null, headCommit: "abcdef0123456789" } },
|
||||
}),
|
||||
);
|
||||
expect(row("orders").textContent).toBe("ordersabcdef01");
|
||||
expect(row("orders").textContent).toBe("orders1 fileabcdef01");
|
||||
});
|
||||
|
||||
it("counts the files under each repository and each nested folder", () => {
|
||||
useCommit.setState({ groupByDir: true });
|
||||
const app = change("/p/App.kt");
|
||||
const order = change("/p/orders/src/Order.kt");
|
||||
const test = change("/p/orders/src/tests/OrderTest.kt");
|
||||
const data = change("/p/orders/src/tests/orders.json");
|
||||
useVcs.setState({ status: [app, order, test, data] });
|
||||
render(<ChangesTree mode="commit" />);
|
||||
|
||||
expect(row("p").textContent).toBe("p1 file");
|
||||
expect(row("orders").textContent).toBe("orders3 files");
|
||||
expect(row("src").textContent).toBe("src3 files");
|
||||
expect(row("tests").textContent).toBe("tests2 files");
|
||||
expect(row("Order.kt").textContent).toBe("Order.kt");
|
||||
|
||||
act(() => useVcs.setState({ status: [app, order, test] }));
|
||||
expect(row("orders").textContent).toBe("orders2 files");
|
||||
expect(row("src").textContent).toBe("src2 files");
|
||||
expect(row("tests").textContent).toBe("tests1 file");
|
||||
});
|
||||
|
||||
it("puts a decorative icon before the branch, on repository rows only", () => {
|
||||
|
||||
@@ -52,7 +52,7 @@ import { commitKey, commitRepo } from "../multiRoot";
|
||||
import { currentRepo, repoName } from "../store";
|
||||
import { CommitMessage } from "./CommitMessage";
|
||||
import { useDropdownMenu, useReadOnlyLog } from "./logHooks";
|
||||
import { toggle } from "./shared";
|
||||
import { PANE_STYLE, toggle } from "./shared";
|
||||
|
||||
const LogMergePreview = lazyComponent(() => import("../GitMergeDiff").then((m) => m.GitMergeDiff));
|
||||
|
||||
@@ -312,7 +312,7 @@ export function CommitDetails({ commits }: { commits: Commit[] }) {
|
||||
|
||||
const details = (
|
||||
<SplitGroup orientation="vertical" id="git-log-details" storageKey="openidea.vcs.logDetailsSplit">
|
||||
<SplitPanel id="files" defaultSize="60%" minSize="60px">
|
||||
<SplitPanel id="files" style={PANE_STYLE} defaultSize="60%" minSize="60px">
|
||||
<div
|
||||
className={styles.filesPane}
|
||||
onFocusCapture={() => setContext("vcsLogChangesFocus", true)}
|
||||
@@ -412,7 +412,7 @@ export function CommitDetails({ commits }: { commits: Commit[] }) {
|
||||
</div>
|
||||
</SplitPanel>
|
||||
<SplitHandle />
|
||||
<SplitPanel id="message" minSize="60px">
|
||||
<SplitPanel id="message" style={PANE_STYLE} minSize="60px">
|
||||
<div className={styles.messageBox}>
|
||||
{many ? (
|
||||
chosen.map((c) => <CommitMessage key={commitKey(c)} commit={c} compact />)
|
||||
@@ -434,11 +434,11 @@ export function CommitDetails({ commits }: { commits: Commit[] }) {
|
||||
id={`git-log-preview-${diffLocation}`}
|
||||
storageKey={`openidea.vcs.logPreviewSplit.${diffLocation}`}
|
||||
>
|
||||
<SplitPanel id="changes" defaultSize="55%" minSize="20%">
|
||||
<SplitPanel id="changes" style={PANE_STYLE} defaultSize="55%" minSize="20%">
|
||||
{details}
|
||||
</SplitPanel>
|
||||
<SplitHandle />
|
||||
<SplitPanel id="preview" minSize="20%">
|
||||
<SplitPanel id="preview" style={PANE_STYLE} minSize="20%">
|
||||
{selectedChange ? (
|
||||
selectedChange.mergeParents?.length === 2 && selectedChange.after ? (
|
||||
<LogMergePreview
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { Commit } from "@/bindings";
|
||||
import { type MenuItem } from "@/ui";
|
||||
import { type ReactNode } from "react";
|
||||
import { type CSSProperties, type ReactNode } from "react";
|
||||
import { type LogOptions } from "../logOptions";
|
||||
import { updateLogOptions } from "../logStore";
|
||||
|
||||
@@ -8,6 +8,12 @@ export const ROW = 26;
|
||||
|
||||
export const LANE = 14;
|
||||
|
||||
/**
|
||||
* Style for the log's split panels. Their panes scroll themselves; the panel's own
|
||||
* `overflow: auto` showed a scrollbar for sub-pixel overflow while a split was dragged.
|
||||
*/
|
||||
export const PANE_STYLE: CSSProperties = { overflow: "hidden" };
|
||||
|
||||
export interface LogColumn {
|
||||
id: string;
|
||||
title: string;
|
||||
|
||||
@@ -8,6 +8,9 @@
|
||||
.group {
|
||||
flex: 1;
|
||||
}
|
||||
.group:has(> :global([data-separator="active"])) * {
|
||||
cursor: col-resize !important;
|
||||
}
|
||||
.editor {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
|
||||
@@ -119,6 +119,7 @@ export function MarkdownEditor({
|
||||
<div ref={ref} className={clsx(styles.split, styles[`mode-${mode}`])}>
|
||||
<SplitGroup
|
||||
orientation="horizontal"
|
||||
disableCursor
|
||||
className={styles.group}
|
||||
storageKey={mode === "split" ? SPLIT_STORAGE_KEY : undefined}
|
||||
>
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { commands, type RemoteSession } from "./ipc";
|
||||
import { useRemote } from "./remote";
|
||||
import { canDragOut, dragOut, isDraggingOut } from "./dragOut";
|
||||
|
||||
beforeEach(() => vi.stubGlobal("__TAURI_INTERNALS__", {}));
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
useRemote.setState({ session: null });
|
||||
});
|
||||
|
||||
describe("dragging files out of the window", () => {
|
||||
it("is offered for a local project in the desktop app only", () => {
|
||||
expect(canDragOut()).toBe(true);
|
||||
useRemote.setState({ session: { id: "remote" } as unknown as RemoteSession });
|
||||
expect(canDragOut()).toBe(false);
|
||||
useRemote.setState({ session: null });
|
||||
vi.unstubAllGlobals();
|
||||
expect(canDragOut()).toBe(false);
|
||||
});
|
||||
|
||||
it("hands every path to one OS drag and reports whether another app took them", async () => {
|
||||
let end!: (dropped: boolean) => void;
|
||||
const drag = vi
|
||||
.spyOn(commands, "windowDragFiles")
|
||||
.mockReturnValue(new Promise((resolve) => (end = (data) => resolve({ status: "ok", data }))));
|
||||
const paths = ["/w/a b/中文.txt", "/w/src"];
|
||||
const result = dragOut(paths);
|
||||
expect(drag).toHaveBeenCalledExactlyOnceWith(paths);
|
||||
// Until it ends, OS drops on this window are the same files coming back.
|
||||
expect(isDraggingOut()).toBe(true);
|
||||
end(true);
|
||||
expect(await result).toBe(true);
|
||||
expect(isDraggingOut()).toBe(false);
|
||||
});
|
||||
|
||||
it("stops ignoring drops at the next press when the drag never reports its end", () => {
|
||||
vi.spyOn(commands, "windowDragFiles").mockReturnValue(new Promise(() => {}));
|
||||
void dragOut(["/w/a.txt"]);
|
||||
expect(isDraggingOut()).toBe(true);
|
||||
window.dispatchEvent(new MouseEvent("pointerdown"));
|
||||
expect(isDraggingOut()).toBe(false);
|
||||
});
|
||||
|
||||
it("ends quietly when the drag can't start", async () => {
|
||||
vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
vi.spyOn(commands, "windowDragFiles").mockResolvedValue({
|
||||
status: "error",
|
||||
error: { kind: "not_found", message: "not a local file: /srv/x" } as never,
|
||||
});
|
||||
expect(await dragOut(["/srv/x"])).toBe(false);
|
||||
expect(isDraggingOut()).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* Files dragged out of the window become an OS file drag, so the app they are dropped
|
||||
* on (Explorer, Finder, an SFTP client) copies them, as from IDEA's Project view (#2867).
|
||||
* Only a local project's files: a remote project's live on its server.
|
||||
*/
|
||||
import { call, commands, isTauri } from "./ipc";
|
||||
import { isRemoteWindow } from "./remote";
|
||||
|
||||
/** The running drag, until it ends or the next press shows none is live. */
|
||||
let running: object | null = null;
|
||||
const pressed = () => {
|
||||
running = null;
|
||||
};
|
||||
|
||||
/** Whether files can be dragged out of this window. */
|
||||
export function canDragOut(): boolean {
|
||||
return isTauri() && !isRemoteWindow();
|
||||
}
|
||||
|
||||
/**
|
||||
* Hands `paths` to an OS drag; call while the primary button is held, once the pointer
|
||||
* left the window. Resolves when the drag ends: true when another app took the files.
|
||||
*/
|
||||
export async function dragOut(paths: readonly string[]): Promise<boolean> {
|
||||
const drag = {};
|
||||
running = drag;
|
||||
// A backend that loses the drag never resolves; a fresh press means it is over anyway.
|
||||
window.addEventListener("pointerdown", pressed, true);
|
||||
try {
|
||||
return await call(commands.windowDragFiles([...paths]));
|
||||
} catch (e) {
|
||||
console.warn("could not drag files out", e);
|
||||
return false;
|
||||
} finally {
|
||||
if (running === drag) running = null;
|
||||
window.removeEventListener("pointerdown", pressed, true);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a drag out of this window is running. An OS file drop meanwhile is the
|
||||
* dragged files coming back, which the window ignores instead of importing or
|
||||
* opening its own files.
|
||||
*/
|
||||
export function isDraggingOut(): boolean {
|
||||
return running !== null;
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
{
|
||||
"Plain-text word lists (one word per line) or Hunspell .dic files; a .dic with its .aff beside it also accepts the inflected forms and compounds its rules allow. Relative paths resolve against the project root, ~/ against the home folder.": "Plain-text word lists (one word per line) or Hunspell .dic files; a .dic with its .aff beside it also accepts the inflected forms and compounds its rules allow. Relative paths resolve against the project root, ~/ against the home folder.",
|
||||
"Trust Folder": "Trust Folder",
|
||||
"No files selected": "No files selected",
|
||||
"{added} added": "{added} added",
|
||||
@@ -909,7 +910,6 @@
|
||||
"devcontainer up exited with {status}": "devcontainer up exited with {status}",
|
||||
"Select an item to view details": "Select an item to view details",
|
||||
"Select files in the Project view, Commit tool window, or open a file in the editor": "Select files in the Project view, Commit tool window, or open a file in the editor",
|
||||
|
||||
"Nothing to show": "Nothing to show",
|
||||
"IDE-managed Tomcat runtime directory must not overlap Tomcat home or base directory": "IDE-managed Tomcat runtime directory must not overlap Tomcat home or base directory",
|
||||
"Invalid log stream configuration": "Invalid log stream configuration",
|
||||
@@ -1368,6 +1368,19 @@
|
||||
"No checksum provided: the download can't be verified.": "No checksum provided: the download can't be verified.",
|
||||
"Sign In": "Sign In",
|
||||
"New Tasks": "New Tasks",
|
||||
"CLI version": "CLI version",
|
||||
"Checking…": "Checking…",
|
||||
"Check for updates": "Check for updates",
|
||||
"Updating the npm installation…": "Updating the npm installation…",
|
||||
"Installed: {0} · npm latest: {1} · {2}": "Installed: {0} · npm latest: {1} · {2}",
|
||||
"Installed: {0} · npm latest: {1}. No write permission for the npm installation at {2}.": "Installed: {0} · npm latest: {1}. No write permission for the npm installation at {2}.",
|
||||
"View permission fixes": "View permission fixes",
|
||||
"Updated to {0}. New sessions will use this version.": "Updated to {0}. New sessions will use this version.",
|
||||
"Installed: {0} · No newer npm release.": "Installed: {0} · No newer npm release.",
|
||||
"Installed: {0}. Use your installer to manage this release channel.": "Installed: {0}. Use your installer to manage this release channel.",
|
||||
"npm could not complete the operation ({0}).": "npm could not complete the operation ({0}).",
|
||||
"An update for this agent is already running.": "An update for this agent is already running.",
|
||||
"This is not a global npm install OpenIDEA can update. Use its original installer.": "This is not a global npm install OpenIDEA can update. Use its original installer.",
|
||||
"Coding Agents": "Coding Agents",
|
||||
"Install coding agents and configure how they launch, chat and connect to the IDE.": "Install coding agents and configure how they launch, chat and connect to the IDE.",
|
||||
"Fork Agent Task": "Fork Agent Task",
|
||||
@@ -2800,5 +2813,10 @@
|
||||
"Cannot download to {folder}": "Cannot download to {folder}",
|
||||
"Copy the selected files and folders of a remote project to a folder on this computer": "Copy the selected files and folders of a remote project to a folder on this computer",
|
||||
"{modifier}+Click to only see \"{name}\"": "{modifier}+Click to only see \"{name}\"",
|
||||
"Not a thread count Maven accepts, so builds run serially. Use a number (4) or a core multiplier (2C, 2.5C).": "Not a thread count Maven accepts, so builds run serially. Use a number (4) or a core multiplier (2C, 2.5C)."
|
||||
"Not a thread count Maven accepts, so builds run serially. Use a number (4) or a core multiplier (2C, 2.5C).": "Not a thread count Maven accepts, so builds run serially. Use a number (4) or a core multiplier (2C, 2.5C).",
|
||||
"Unknown macro {all} in the working directory. Supported: {supported}.": "Unknown macro {all} in the working directory. Supported: {supported}.",
|
||||
"{all} is not available in a remote project.": "{all} is not available in a remote project.",
|
||||
"Cannot start '{name}'": "Cannot start '{name}'",
|
||||
"Module working directory": "Module working directory",
|
||||
"User home directory": "User home directory"
|
||||
}
|
||||
@@ -3244,7 +3244,6 @@
|
||||
"Accepted in every project.": "Aceptadas en todos los proyectos.",
|
||||
"Custom dictionaries": "Diccionarios personalizados",
|
||||
"Dictionary files": "Archivos de diccionario",
|
||||
"Plain-text word lists (one word per line) or Hunspell .dic files. Relative paths resolve against the project root, ~/ against the home folder.": "Listas de palabras en texto plano (una palabra por línea) o archivos .dic de Hunspell. Las rutas relativas se resuelven respecto a la raíz del proyecto y ~/ respecto a la carpeta personal.",
|
||||
"No custom dictionaries": "No hay diccionarios personalizados",
|
||||
"Dictionary path": "Ruta del diccionario",
|
||||
"Natural Languages": "Idiomas naturales",
|
||||
|
||||
@@ -3117,7 +3117,6 @@
|
||||
"Accepted in every project.": "Acceptés dans tous les projets.",
|
||||
"Custom dictionaries": "Dictionnaires personnalisés",
|
||||
"Dictionary files": "Fichiers de dictionnaire",
|
||||
"Plain-text word lists (one word per line) or Hunspell .dic files. Relative paths resolve against the project root, ~/ against the home folder.": "Listes de mots en texte brut (un mot par ligne) ou fichiers Hunspell .dic. Les chemins relatifs sont résolus depuis la racine du projet, ~/ depuis le dossier personnel.",
|
||||
"No custom dictionaries": "Aucun dictionnaire personnalisé",
|
||||
"Dictionary path": "Chemin du dictionnaire",
|
||||
"Natural Languages": "Langues naturelles",
|
||||
|
||||
@@ -3293,7 +3293,6 @@
|
||||
"Accepted in every project.": "모든 프로젝트에서 허용됩니다.",
|
||||
"Custom dictionaries": "사용자 지정 사전",
|
||||
"Dictionary files": "사전 파일",
|
||||
"Plain-text word lists (one word per line) or Hunspell .dic files. Relative paths resolve against the project root, ~/ against the home folder.": "일반 텍스트 단어 목록(한 줄에 한 단어) 또는 Hunspell .dic 파일. 상대 경로는 프로젝트 루트를, ~/는 홈 폴더를 기준으로 해결됩니다.",
|
||||
"No custom dictionaries": "사용자 지정 사전 없음",
|
||||
"Dictionary path": "사전 경로",
|
||||
"Natural Languages": "자연어",
|
||||
|
||||
@@ -3216,7 +3216,6 @@
|
||||
"Accepted in every project.": "Akceptowane we wszystkich projektach.",
|
||||
"Custom dictionaries": "Własne słowniki",
|
||||
"Dictionary files": "Pliki słowników",
|
||||
"Plain-text word lists (one word per line) or Hunspell .dic files. Relative paths resolve against the project root, ~/ against the home folder.": "Listy słów w zwykłym tekście (jednosłowne w wierszu) lub pliki .dic Hunspell. Ścieżki względne są rozwiązywane względem katalogu głównego projektu, a ~/ względem folderu domowego.",
|
||||
"No custom dictionaries": "Brak własnych słowników",
|
||||
"Dictionary path": "Ścieżka słownika",
|
||||
"Natural Languages": "Języki naturalne",
|
||||
|
||||
@@ -3217,7 +3217,6 @@
|
||||
"Accepted in every project.": "Aceitas em todos os projetos.",
|
||||
"Custom dictionaries": "Dicionários personalizados",
|
||||
"Dictionary files": "Arquivos de dicionário",
|
||||
"Plain-text word lists (one word per line) or Hunspell .dic files. Relative paths resolve against the project root, ~/ against the home folder.": "Listas de palavras em texto simples (uma palavra por linha) ou arquivos .dic do Hunspell. Caminhos relativos são resolvidos em relação à raiz do projeto, ~/ em relação à pasta pessoal.",
|
||||
"No custom dictionaries": "Nenhum dicionário personalizado",
|
||||
"Dictionary path": "Caminho do dicionário",
|
||||
"Natural Languages": "Idiomas naturais",
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
{
|
||||
"Plain-text word lists (one word per line) or Hunspell .dic files; a .dic with its .aff beside it also accepts the inflected forms and compounds its rules allow. Relative paths resolve against the project root, ~/ against the home folder.": "纯文本单词列表(每行一个词)或 Hunspell .dic 文件;旁边有同名 .aff 的 .dic 还会接受其规则允许的变形和复合词。相对路径基于项目根目录解析,~/ 表示主目录。",
|
||||
"MCP server instructions": "MCP 服务器说明",
|
||||
"MCP tools (deferred)": "MCP 工具(延迟加载)",
|
||||
"System tools (deferred)": "系统工具(延迟加载)",
|
||||
@@ -4104,7 +4105,6 @@
|
||||
"Accepted in every project.": "在所有项目中接受。",
|
||||
"Custom dictionaries": "自定义词典",
|
||||
"Dictionary files": "词典文件",
|
||||
"Plain-text word lists (one word per line) or Hunspell .dic files. Relative paths resolve against the project root, ~/ against the home folder.": "纯文本单词列表(每行一个单词)或 Hunspell .dic 文件。相对路径相对于项目根目录解析,~/ 相对于主文件夹解析。",
|
||||
"No custom dictionaries": "没有自定义词典",
|
||||
"Dictionary path": "词典路径",
|
||||
"Natural Languages": "自然语言",
|
||||
@@ -5285,7 +5285,6 @@
|
||||
"Configuration…": "配置…",
|
||||
"No deployment server configured": "未配置部署服务器",
|
||||
"Select files in the Project view, Commit tool window, or open a file in the editor": "请在项目视图或提交工具窗口中选择文件,或在编辑器中打开文件",
|
||||
|
||||
"Upload to": "上传到",
|
||||
"Download from": "下载自",
|
||||
"Sync with Deployed to": "与已部署的同步",
|
||||
@@ -7769,6 +7768,19 @@
|
||||
"No checksum provided: the download can't be verified.": "未提供校验和:无法校验下载的文件。",
|
||||
"Sign In": "登录",
|
||||
"New Tasks": "新任务",
|
||||
"CLI version": "CLI 版本",
|
||||
"Checking…": "正在检查…",
|
||||
"Check for updates": "检查更新",
|
||||
"Updating the npm installation…": "正在更新 npm 安装…",
|
||||
"Installed: {0} · npm latest: {1} · {2}": "已安装:{0} · npm 最新版:{1} · {2}",
|
||||
"Installed: {0} · npm latest: {1}. No write permission for the npm installation at {2}.": "已安装:{0} · npm 最新版:{1}。没有位于 {2} 的 npm 安装目录的写入权限。",
|
||||
"View permission fixes": "查看权限修复方法",
|
||||
"Updated to {0}. New sessions will use this version.": "已更新到 {0}。新会话将使用此版本。",
|
||||
"Installed: {0} · No newer npm release.": "已安装:{0} · 没有更新的 npm 版本。",
|
||||
"Installed: {0}. Use your installer to manage this release channel.": "已安装:{0}。请使用原安装工具管理此发布渠道。",
|
||||
"npm could not complete the operation ({0}).": "npm 无法完成操作({0})。",
|
||||
"An update for this agent is already running.": "此智能体已有更新正在进行。",
|
||||
"This is not a global npm install OpenIDEA can update. Use its original installer.": "这不是 OpenIDEA 能更新的 npm 全局安装。请使用原安装工具更新。",
|
||||
"Coding Agents": "编程智能体",
|
||||
"Install coding agents and configure how they launch, chat and connect to the IDE.": "安装编程 Agent,并配置其启动方式、聊天行为以及与 IDE 的连接。",
|
||||
"Fork Agent Task": "Fork Agent 任务",
|
||||
@@ -9160,5 +9172,10 @@
|
||||
"Cannot download to {folder}": "无法下载到 {folder}",
|
||||
"Copy the selected files and folders of a remote project to a folder on this computer": "把远程项目中选中的文件和文件夹复制到本机的文件夹",
|
||||
"{modifier}+Click to only see \"{name}\"": "{modifier}+点击仅显示“{name}”",
|
||||
"Not a thread count Maven accepts, so builds run serially. Use a number (4) or a core multiplier (2C, 2.5C).": "Maven 不接受这个线程数,构建将串行执行。请填写数字(4)或核数倍数(2C、2.5C)。"
|
||||
"Not a thread count Maven accepts, so builds run serially. Use a number (4) or a core multiplier (2C, 2.5C).": "Maven 不接受这个线程数,构建将串行执行。请填写数字(4)或核数倍数(2C、2.5C)。",
|
||||
"Unknown macro {all} in the working directory. Supported: {supported}.": "工作目录中有未知的宏 {all}。支持:{supported}。",
|
||||
"{all} is not available in a remote project.": "{all} 在远程项目中不可用。",
|
||||
"Cannot start '{name}'": "无法启动“{name}”",
|
||||
"Module working directory": "模块工作目录",
|
||||
"User home directory": "用户主目录"
|
||||
}
|
||||
@@ -49,6 +49,35 @@ const labels = (tree: HTMLElement) =>
|
||||
.queryAllByRole("treeitem")
|
||||
.map((el) => el.textContent);
|
||||
|
||||
describe("Tree context-menu selection", () => {
|
||||
it.each([
|
||||
{ os: "windows", gesture: { button: 2 } },
|
||||
{ os: "macos", gesture: { button: 0, ctrlKey: true } },
|
||||
])("marks $os context-menu selection without changing ordinary activation", ({ os, gesture }) => {
|
||||
const previousOs = usePlatform.getState().os;
|
||||
usePlatform.setState({ os });
|
||||
try {
|
||||
const selection = vi.fn();
|
||||
const menu = vi.fn();
|
||||
const { tree, key, onActivate } = setup({ onSelectionChange: selection, onContextMenu: menu });
|
||||
const readme = within(tree).getByRole("treeitem", { name: "README.md" });
|
||||
fireEvent.mouseDown(readme, gesture);
|
||||
fireEvent.contextMenu(readme, gesture);
|
||||
expect(selection).toHaveBeenLastCalledWith(new Set(["README.md"]), data[1], "contextMenu");
|
||||
expect(menu).toHaveBeenCalledWith(data[1], new Set(["README.md"]), expect.anything());
|
||||
expect(onActivate).not.toHaveBeenCalled();
|
||||
key("Home");
|
||||
expect(selection).toHaveBeenLastCalledWith(new Set(["src"]), data[0]);
|
||||
fireEvent.mouseDown(readme, { button: 0 });
|
||||
expect(selection).toHaveBeenLastCalledWith(new Set(["README.md"]), data[1]);
|
||||
key("Enter");
|
||||
expect(onActivate).toHaveBeenCalledWith(data[1], expect.anything());
|
||||
} finally {
|
||||
usePlatform.setState({ os: previousOs });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("Tree directory context", () => {
|
||||
it("does not contribute virtual document URIs as filesystem directories", () => {
|
||||
const { key } = setup({ getDirectory: () => "jdt://contents/library.jar/package" });
|
||||
|
||||
@@ -104,7 +104,8 @@ export interface TreeProps<T> {
|
||||
|
||||
selected?: ReadonlySet<string>;
|
||||
defaultSelected?: Iterable<string>;
|
||||
onSelectionChange?: (selected: Set<string>, lead: T | null) => void;
|
||||
/** Context-menu selection can update the action target without navigating to it. */
|
||||
onSelectionChange?: (selected: Set<string>, lead: T | null, reason?: "contextMenu") => void;
|
||||
multiSelect?: boolean;
|
||||
|
||||
/** Enter / double-click on a leaf (or on nodes `activateExpandable` accepts). */
|
||||
@@ -426,22 +427,23 @@ export function Tree<T>(props: TreeProps<T>) {
|
||||
};
|
||||
|
||||
const commitSelection = useCallback(
|
||||
(next: Set<string>, leadKey: string | null) => {
|
||||
(next: Set<string>, leadKey: string | null, reason?: "contextMenu") => {
|
||||
if (!selectedControlled) setSelectedInner(next);
|
||||
setLead(leadKey);
|
||||
const leadRow = leadKey != null ? rows[indexOfKey.get(leadKey) ?? -1] : undefined;
|
||||
props.onSelectionChange?.(next, leadRow?.node ?? null);
|
||||
if (reason) props.onSelectionChange?.(next, leadRow?.node ?? null, reason);
|
||||
else props.onSelectionChange?.(next, leadRow?.node ?? null);
|
||||
},
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[rows, indexOfKey, selectedControlled, props.onSelectionChange],
|
||||
);
|
||||
|
||||
const selectIndex = (i: number, mode: "single" | "toggle" | "range" = "single") => {
|
||||
const selectIndex = (i: number, mode: "single" | "toggle" | "range" = "single", reason?: "contextMenu") => {
|
||||
const row = rows[i];
|
||||
if (!row || row.loading) return;
|
||||
if (mode === "single" || !multiSelect) {
|
||||
setAnchor(row.key);
|
||||
commitSelection(new Set([row.key]), row.key);
|
||||
commitSelection(new Set([row.key]), row.key, reason);
|
||||
} else if (mode === "toggle") {
|
||||
const next = new Set(selected);
|
||||
if (next.has(row.key)) next.delete(row.key);
|
||||
@@ -649,8 +651,8 @@ export function Tree<T>(props: TreeProps<T>) {
|
||||
};
|
||||
|
||||
const onRowMouseDown = (e: MouseEvent, i: number) => {
|
||||
if (e.button === 2) {
|
||||
if (!selected.has(rows[i]!.key)) selectIndex(i);
|
||||
if (e.button === 2 || (e.button === 0 && e.ctrlKey && isMacHost())) {
|
||||
if (!selected.has(rows[i]!.key)) selectIndex(i, "single", "contextMenu");
|
||||
return;
|
||||
}
|
||||
if (e.button !== 0) return;
|
||||
|
||||
@@ -16,6 +16,7 @@ export {
|
||||
beginDrag,
|
||||
dragSession,
|
||||
dropZoneAt,
|
||||
isOutsideWindow,
|
||||
registerDropTarget,
|
||||
setDragRequiresAlt,
|
||||
startPointerDrag,
|
||||
|
||||
@@ -1980,7 +1980,9 @@ export const useDebugRunSessions = create<{
|
||||
sessions: DebugRunSession[];
|
||||
serviceSessions: DebugServiceSession[];
|
||||
Console: ComponentType<{ sessionId: number }> | null;
|
||||
}>(() => ({ sessions: [], serviceSessions: [], Console: null }));
|
||||
/** The whole debugger of a session (Services shows it in place); `console` replaces its Console tab. */
|
||||
View: ComponentType<{ sessionId: number; console?: ReactNode }> | null;
|
||||
}>(() => ({ sessions: [], serviceSessions: [], Console: null, View: null }));
|
||||
|
||||
/**
|
||||
* The Services tool window's badge: how many of its listed services are running.
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { commands } from "@/platform/ipc";
|
||||
import { dragOut } from "@/platform/dragOut";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { useRemote } from "@/platform/remote";
|
||||
import type { RemoteSession } from "@/platform/ipc";
|
||||
@@ -52,6 +54,29 @@ describe("files dropped from the OS", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("ignores its own files dragged out of the window and dropped back on it", async () => {
|
||||
let end!: () => void;
|
||||
vi.spyOn(commands, "windowDragFiles").mockReturnValue(
|
||||
new Promise((resolve) => (end = () => resolve({ status: "ok", data: false }))),
|
||||
);
|
||||
const handler = vi.fn(() => true);
|
||||
const unregister = registerFileDropHandler(handler);
|
||||
const { d, calls } = deps();
|
||||
try {
|
||||
const drag = dragOut(["/p/a.ts"]);
|
||||
await handleFileDrop(["/p/a.ts"], 1, 1, d);
|
||||
end();
|
||||
await drag;
|
||||
expect(handler).not.toHaveBeenCalled();
|
||||
expect(calls).toEqual([]);
|
||||
await handleFileDrop(["/p/a.ts"], 1, 1, d);
|
||||
expect(handler).toHaveBeenCalledOnce();
|
||||
} finally {
|
||||
unregister();
|
||||
vi.restoreAllMocks();
|
||||
}
|
||||
});
|
||||
|
||||
it("opens each dropped file in its own tab, focusing the last; works for files outside the project", async () => {
|
||||
const { d, calls } = deps();
|
||||
await handleFileDrop(["/p/a.ts", "/elsewhere/notes.md"], 1, 1, d);
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
*/
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { call, commands, isTauri } from "@/platform/ipc";
|
||||
import { isDraggingOut } from "@/platform/dragOut";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { isRemoteWindow } from "@/platform/remote";
|
||||
import { nativeDropPoint } from "@/platform/nativeDrop";
|
||||
@@ -57,6 +58,8 @@ export function handleFileDrop(
|
||||
y: number,
|
||||
deps: FileDropDeps = defaultDeps,
|
||||
): Promise<void> | null {
|
||||
// Files dragged out of this window and dropped back on it: nothing to open.
|
||||
if (isDraggingOut()) return Promise.resolve();
|
||||
for (const handler of fileDropHandlers) if (paths.length && handler(paths, x, y)) return Promise.resolve();
|
||||
const { project, lightEdit } = useProject.getState();
|
||||
if (!paths.length || !(project || lightEdit) || isRemoteWindow() || dropOwnedAt(x, y)) return null;
|
||||
|
||||
Reference in new issue
Заблокувати користувача