дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-05 09:41:34 +02:00
feat(run): choose the run device from plugin device providers (#7822)
* feat(run): choose the run device from plugin device providers Plugins can declare device providers (`[[contributes.devices]]`): a program that lists simulators, emulators or phones as JSON, the run configurations it applies to, and how a chosen device reaches the run (extra arguments, environment, an optional prepare step that boots it). The title bar shows a device chooser for the selected configuration; Run and Debug prepare the chosen device first. Before-launch and build-on-update runs skip the device. * feat(plugins): document run devices and require plugin API 1.21 `[[contributes.devices]]` now needs `engines.openidea = "^1.21"` and uses camelCase fields (`appliesTo`, `runArgs`) like the other run contribution points. The plugin README, the manifest reference and the API versions page (en/zh) describe it, and `plugins/official/android-devices` is a small example that lists the devices adb sees for Gradle install tasks. * fix(plugins): harden device runner process handling, guard refresh races, verbatim headers, and add en.json entries * fix(plugins): use portable process:sh capability in android-devices example and README --------- Co-authored-by: l0ng-ai <[email protected]>
Цей коміт міститься в:
1 джерело
71ded3e4c0
коміт
579ce3f731
30 files changed
+1121
-9
No files matched your search
@@ -1,5 +1,6 @@
|
||||
//! Plugin window commands shared by local IPC and remote RPC.
|
||||
|
||||
use super::devices::{Device, DeviceProvider};
|
||||
use super::{
|
||||
ClipboardAnswer, CommandAnswer, CommitAnswer, DecorationSet, EventKind, PluginContextKey, PluginEditor, PluginHost,
|
||||
PluginInfo, PluginStatusItem, WorkbenchEvent,
|
||||
@@ -14,6 +15,46 @@ use std::collections::BTreeMap;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Device providers (simulators, emulators…) of enabled plugins whose programs are granted.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn plugin_device_providers(plugins: &Arc<PluginHost>) -> IdeResult<Vec<DeviceProvider>> {
|
||||
let plugins = plugins.clone();
|
||||
blocking(move || {
|
||||
plugins.wait_initial_load(std::time::Duration::from_secs(5));
|
||||
Ok(plugins.device_providers())
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// The devices a provider lists now, its command running in this window's project.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn plugin_devices(
|
||||
host: &Host,
|
||||
plugins: &Arc<PluginHost>,
|
||||
window: &str,
|
||||
plugin_id: String,
|
||||
provider_id: String,
|
||||
) -> IdeResult<Vec<Device>> {
|
||||
let plugins = plugins.clone();
|
||||
let root = host.project(window).ok().map(|p| p.root.clone());
|
||||
blocking(move || plugins.list_devices(&plugin_id, &provider_id, root.as_deref())).await
|
||||
}
|
||||
|
||||
/// Gets a device ready (boots an emulator…) and returns the id to run with.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn plugin_device_prepare(
|
||||
host: &Host,
|
||||
plugins: &Arc<PluginHost>,
|
||||
window: &str,
|
||||
plugin_id: String,
|
||||
provider_id: String,
|
||||
device_id: String,
|
||||
) -> IdeResult<String> {
|
||||
let plugins = plugins.clone();
|
||||
let root = host.project(window).ok().map(|p| p.root.clone());
|
||||
blocking(move || plugins.prepare_device(&plugin_id, &provider_id, &device_id, root.as_deref())).await
|
||||
}
|
||||
|
||||
/// Runs a plugin command in the context of this window's project and focused editor.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[command(trust = trusted)]
|
||||
@@ -485,6 +526,9 @@ ide_command::domain!(
|
||||
plugin_context_keys,
|
||||
plugin_debug_attach_target,
|
||||
plugin_decoration_sets,
|
||||
plugin_device_prepare,
|
||||
plugin_device_providers,
|
||||
plugin_devices,
|
||||
plugin_event_kinds,
|
||||
plugin_finish_operation,
|
||||
plugin_parse_test_results,
|
||||
|
||||
@@ -0,0 +1,494 @@
|
||||
//! The `devices` extension point: run devices (simulators, emulators, phones)
|
||||
//! a plugin lists with a program, offered in a chooser next to the run
|
||||
//! configurations they apply to.
|
||||
//!
|
||||
//! ```toml
|
||||
//! [[contributes.devices]]
|
||||
//! id = "ios-simulators"
|
||||
//! name = "iOS Simulators"
|
||||
//! command = "/usr/bin/python3" # prints a JSON array of devices
|
||||
//! args = ["-I", "./devices/ios.py"] # `./x` is relative to the package
|
||||
//! appliesTo = "net\\d+\\.\\d+-ios" # regex over a configuration's command line
|
||||
//! runArgs = ["--device", "${device.id}"]
|
||||
//! env = { SIMULATOR_UDID = "${device.id}" }
|
||||
//! prepare = ["/usr/bin/python3", "-I", "./devices/boot.py", "${device.id}"]
|
||||
//! ```
|
||||
//!
|
||||
//! `command` and `prepare`'s program are `process:` capabilities like a
|
||||
//! language server's: a provider is offered only while they are granted, and
|
||||
//! starts the approved file (checked right before it starts).
|
||||
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use ide_extension::{
|
||||
Capability, Disposable, ExtensionPoint, Package, Placement, Prepared, check_relative, decode, validate_item_id,
|
||||
};
|
||||
use ide_language::ProgramPin;
|
||||
use parking_lot::RwLock;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
pub const POINT_ID: &str = "devices";
|
||||
/// How long a provider may take to list its devices (booting one is `prepare`'s job).
|
||||
pub const LIST_TIMEOUT: Duration = Duration::from_secs(20);
|
||||
/// How long getting a device ready may take (booting an emulator).
|
||||
pub const PREPARE_TIMEOUT: Duration = Duration::from_secs(300);
|
||||
/// A device list larger than this is not a device list.
|
||||
const MAX_OUTPUT: u64 = 4 << 20;
|
||||
const MAX_ARGS: usize = 64;
|
||||
|
||||
#[derive(Clone, Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct Decl {
|
||||
/// Unique within the plugin.
|
||||
pub id: String,
|
||||
/// Shown in the chooser (`iOS Simulators`).
|
||||
pub name: String,
|
||||
/// Program printing a JSON array of devices.
|
||||
pub command: String,
|
||||
/// Its arguments; `./x` is relative to the package directory.
|
||||
#[serde(default)]
|
||||
pub args: Vec<String>,
|
||||
/// Regular expression matched against a configuration's command line,
|
||||
/// arguments and parameters: the chooser shows for the configurations it finds.
|
||||
pub applies_to: String,
|
||||
/// Appended to the arguments of a run with a device selected; `${device.id}`,
|
||||
/// `${device.name}` expand to it.
|
||||
#[serde(default)]
|
||||
pub run_args: Vec<String>,
|
||||
/// Added to the environment of a run or debug session with a device selected
|
||||
/// (same expansions).
|
||||
#[serde(default)]
|
||||
pub env: BTreeMap<String, String>,
|
||||
/// Program and arguments that get the chosen device ready before a run or
|
||||
/// debug session (boot an emulator) and print the id to use; `${device.id}` expands.
|
||||
#[serde(default)]
|
||||
pub prepare: Vec<String>,
|
||||
}
|
||||
|
||||
impl Decl {
|
||||
/// The programs it starts, each a `process:` capability.
|
||||
fn programs(&self) -> impl Iterator<Item = &str> {
|
||||
std::iter::once(self.command.trim()).chain(self.prepare.first().map(|p| p.trim()))
|
||||
}
|
||||
}
|
||||
|
||||
/// A device provider of an enabled plugin, as the UI sees it.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DeviceProvider {
|
||||
pub plugin_id: String,
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
/// Regular expression over a configuration's command line, arguments and parameters.
|
||||
pub applies_to: String,
|
||||
/// Appended to run arguments; `${device.id}` / `${device.name}` expand.
|
||||
pub run_args: Vec<String>,
|
||||
/// Added to the environment of runs and debug sessions (same expansions).
|
||||
pub env: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
/// One device a provider listed.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Device {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
/// Secondary text (`iOS 26.0`).
|
||||
#[serde(default)]
|
||||
pub detail: Option<String>,
|
||||
/// Heading the device is listed under (`iOS Simulators`, `Physical Devices`).
|
||||
#[serde(default)]
|
||||
pub group: Option<String>,
|
||||
/// Booted / connected: preferred when nothing is selected yet.
|
||||
#[serde(default)]
|
||||
pub running: bool,
|
||||
}
|
||||
|
||||
/// Providers of enabled plugins: (seq, plugin id, package directory, declaration).
|
||||
#[derive(Default)]
|
||||
pub struct Devices {
|
||||
items: RwLock<Vec<(u64, String, PathBuf, Decl)>>,
|
||||
seq: AtomicU64,
|
||||
}
|
||||
|
||||
impl Devices {
|
||||
fn add(self: &Arc<Self>, plugin: String, dir: PathBuf, decl: Decl) -> Disposable {
|
||||
let seq = self.seq.fetch_add(1, Ordering::Relaxed);
|
||||
self.items.write().push((seq, plugin, dir, decl));
|
||||
let weak = Arc::downgrade(self);
|
||||
Disposable::new(move || {
|
||||
if let Some(this) = weak.upgrade() {
|
||||
this.items.write().retain(|(s, _, _, _)| *s != seq);
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub struct DevicesPoint {
|
||||
store: Arc<Devices>,
|
||||
}
|
||||
|
||||
impl DevicesPoint {
|
||||
pub fn new(store: Arc<Devices>) -> Self {
|
||||
Self { store }
|
||||
}
|
||||
}
|
||||
|
||||
impl ExtensionPoint for DevicesPoint {
|
||||
fn id(&self) -> &'static str {
|
||||
POINT_ID
|
||||
}
|
||||
|
||||
fn placement(&self) -> Placement {
|
||||
Placement::Workspace
|
||||
}
|
||||
|
||||
fn prepare(&self, pkg: &Package, decl: toml::Value) -> Result<Prepared, String> {
|
||||
pkg.manifest.needs_api("contributes.devices", 21)?;
|
||||
let d: Decl = decode(POINT_ID, decl)?;
|
||||
validate_item_id(&d.id, "device provider id")?;
|
||||
if d.name.trim().is_empty() || d.name.len() > 128 {
|
||||
return Err(format!("device provider {:?}: `name` must be 1–128 bytes", d.id));
|
||||
}
|
||||
if d.applies_to.trim().is_empty() {
|
||||
return Err(format!("device provider {:?} needs `appliesTo`", d.id));
|
||||
}
|
||||
if d.args.len() > MAX_ARGS || d.prepare.len() > MAX_ARGS || d.run_args.len() > MAX_ARGS {
|
||||
return Err(format!("device provider {:?}: at most {MAX_ARGS} arguments", d.id));
|
||||
}
|
||||
for program in d.programs() {
|
||||
if program.is_empty() || program.contains(char::is_whitespace) || program.starts_with("./") {
|
||||
return Err(format!(
|
||||
"device provider {:?}: `command` and `prepare[0]` are one installed program (scripts go in the arguments)",
|
||||
d.id
|
||||
));
|
||||
}
|
||||
}
|
||||
let mut prepared = Prepared::new(d.name.clone(), {
|
||||
let (store, plugin, dir, d) = (self.store.clone(), pkg.id().to_owned(), pkg.dir.clone(), d.clone());
|
||||
move || Ok(store.add(plugin, dir, d))
|
||||
})
|
||||
.key(d.id.clone());
|
||||
for program in d.programs() {
|
||||
prepared = prepared.capability(Capability::Process(program.to_owned()));
|
||||
}
|
||||
for file in d.args.iter().chain(d.prepare.iter().skip(1)).filter_map(|a| a.strip_prefix("./")) {
|
||||
let file = Path::new(file);
|
||||
check_relative(file, "device provider file")?;
|
||||
prepared = prepared.file(file);
|
||||
}
|
||||
Ok(prepared)
|
||||
}
|
||||
}
|
||||
|
||||
type Pins = Arc<RwLock<HashMap<(String, String), ProgramPin>>>;
|
||||
|
||||
/// The providers whose programs are granted, and running them.
|
||||
pub(super) struct DeviceRunner<'a> {
|
||||
pub store: &'a Devices,
|
||||
pub pins: &'a Pins,
|
||||
}
|
||||
|
||||
impl DeviceRunner<'_> {
|
||||
fn pin(&self, plugin: &str, program: &str) -> Option<ProgramPin> {
|
||||
self.pins.read().get(&(plugin.to_owned(), Capability::Process(program.to_owned()).to_string())).cloned()
|
||||
}
|
||||
|
||||
fn granted(&self, plugin: &str, d: &Decl) -> bool {
|
||||
d.programs().all(|p| self.pin(plugin, p).is_some())
|
||||
}
|
||||
|
||||
pub fn providers(&self) -> Vec<DeviceProvider> {
|
||||
let mut out: Vec<DeviceProvider> = self
|
||||
.store
|
||||
.items
|
||||
.read()
|
||||
.iter()
|
||||
.filter(|(_, plugin, _, d)| self.granted(plugin, d))
|
||||
.map(|(_, plugin, _, d)| DeviceProvider {
|
||||
plugin_id: plugin.clone(),
|
||||
id: d.id.clone(),
|
||||
name: d.name.clone(),
|
||||
applies_to: d.applies_to.clone(),
|
||||
run_args: d.run_args.clone(),
|
||||
env: d.env.clone(),
|
||||
})
|
||||
.collect();
|
||||
out.sort_by(|a, b| (&a.plugin_id, &a.id).cmp(&(&b.plugin_id, &b.id)));
|
||||
out
|
||||
}
|
||||
|
||||
fn find(&self, plugin: &str, provider: &str) -> IdeResult<(PathBuf, Decl)> {
|
||||
self.store
|
||||
.items
|
||||
.read()
|
||||
.iter()
|
||||
.find(|(_, p, _, d)| p == plugin && d.id == provider)
|
||||
.map(|(_, _, dir, d)| (dir.clone(), d.clone()))
|
||||
.ok_or_else(|| IdeError::not_found(format!("plugin {plugin:?} has no device provider {provider:?}")))
|
||||
}
|
||||
|
||||
/// The approved file of `program`, checked now.
|
||||
fn program(&self, plugin: &str, program: &str) -> IdeResult<PathBuf> {
|
||||
let pin = self.pin(plugin, program).ok_or_else(|| {
|
||||
IdeError::unavailable(format!("allow process:{program} for plugin {plugin} in Settings › Plugins"))
|
||||
})?;
|
||||
pin.verify().map(Path::to_path_buf).map_err(IdeError::unavailable)
|
||||
}
|
||||
|
||||
/// Runs the provider's list command (blocking, up to [`LIST_TIMEOUT`]) in `cwd`.
|
||||
pub fn list(&self, plugin: &str, provider: &str, cwd: Option<&Path>) -> IdeResult<Vec<Device>> {
|
||||
let (dir, d) = self.find(plugin, provider)?;
|
||||
let program = self.program(plugin, d.command.trim())?;
|
||||
let args = resolve_args(&dir, &d.args, None);
|
||||
let out = run(&d.name, &program, &args, cwd, LIST_TIMEOUT)?;
|
||||
serde_json::from_slice(&out)
|
||||
.map_err(|e| IdeError::unavailable(format!("{}: expected a JSON array of devices ({e})", d.name)))
|
||||
}
|
||||
|
||||
/// Gets `device` ready (boots an emulator) with the provider's `prepare` and
|
||||
/// returns the id to run with: the last line it prints, else `device`.
|
||||
pub fn prepare(&self, plugin: &str, provider: &str, device: &str, cwd: Option<&Path>) -> IdeResult<String> {
|
||||
let (dir, d) = self.find(plugin, provider)?;
|
||||
let Some((program, args)) = d.prepare.split_first() else { return Ok(device.to_owned()) };
|
||||
let program = self.program(plugin, program.trim())?;
|
||||
let args = resolve_args(&dir, args, Some(device));
|
||||
let out = run(&d.name, &program, &args, cwd, PREPARE_TIMEOUT)?;
|
||||
let out = String::from_utf8_lossy(&out);
|
||||
Ok(out.lines().map(str::trim).rfind(|l| !l.is_empty()).unwrap_or(device).to_owned())
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves `./x` manifest paths relative to `package` first, and expands `${device.id}`
|
||||
/// only on non-path arguments so a device id starting with `./` is never rewritten into
|
||||
/// a package path.
|
||||
fn resolve_args(package: &Path, args: &[String], device: Option<&str>) -> Vec<std::ffi::OsString> {
|
||||
args.iter()
|
||||
.map(|arg| match arg.strip_prefix("./") {
|
||||
Some(rel) => package.join(rel).into_os_string(),
|
||||
None => match device {
|
||||
Some(id) => arg.replace("${device.id}", id).into(),
|
||||
None => arg.into(),
|
||||
},
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Runs `program` with `args` and returns its standard output; an error with its standard
|
||||
/// error when it fails or outlives `timeout`.
|
||||
fn run(
|
||||
name: &str,
|
||||
program: &Path,
|
||||
args: &[std::ffi::OsString],
|
||||
cwd: Option<&Path>,
|
||||
timeout: Duration,
|
||||
) -> IdeResult<Vec<u8>> {
|
||||
use std::sync::mpsc;
|
||||
let failed = |e: &dyn std::fmt::Display| IdeError::unavailable(format!("{name}: {e}"));
|
||||
let mut cmd = Command::new(program);
|
||||
cmd.args(args).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||
if let Some(cwd) = cwd {
|
||||
cmd.current_dir(cwd);
|
||||
}
|
||||
ide_core::process::prepare(&mut cmd);
|
||||
ide_core::process::own_group(&mut cmd);
|
||||
let mut child = cmd.spawn().map_err(|e| failed(&e))?;
|
||||
let (tx, rx) = mpsc::channel::<(bool, Option<Vec<u8>>)>();
|
||||
let pipes: [(bool, u64, Option<Box<dyn Read + Send>>); 2] = [
|
||||
(true, MAX_OUTPUT, child.stdout.take().map(|p| Box::new(p) as Box<dyn Read + Send>)),
|
||||
(false, 64 << 10, child.stderr.take().map(|p| Box::new(p) as Box<dyn Read + Send>)),
|
||||
];
|
||||
for (is_out, limit, pipe) in pipes {
|
||||
let tx = tx.clone();
|
||||
std::thread::spawn(move || {
|
||||
let mut buf = [0u8; 8192];
|
||||
if let Some(pipe) = pipe {
|
||||
let mut pipe = pipe.take(limit);
|
||||
while let Ok(n @ 1..) = pipe.read(&mut buf) {
|
||||
if tx.send((is_out, Some(buf[..n].to_vec()))).is_err() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
let _ = tx.send((is_out, None));
|
||||
});
|
||||
}
|
||||
drop(tx);
|
||||
let (mut out, mut err, mut open) = (Vec::new(), Vec::new(), 2);
|
||||
let deadline = Instant::now() + timeout;
|
||||
let mut drain_until = None;
|
||||
let status = loop {
|
||||
if drain_until.is_none()
|
||||
&& let Some(status) = child.try_wait().map_err(|e| failed(&e))?
|
||||
{
|
||||
drain_until = Some((status, Instant::now() + Duration::from_secs(2)));
|
||||
}
|
||||
if let Some((status, until)) = drain_until
|
||||
&& (open == 0 || Instant::now() >= until)
|
||||
{
|
||||
break status;
|
||||
}
|
||||
if drain_until.is_none() && Instant::now() >= deadline {
|
||||
ide_core::process::kill_tree(&mut child);
|
||||
return Err(failed(&format!("no answer within {} s", timeout.as_secs())));
|
||||
}
|
||||
match rx.recv_timeout(Duration::from_millis(25)) {
|
||||
Ok((is_out, Some(chunk))) => if is_out { &mut out } else { &mut err }.extend(chunk),
|
||||
Ok((_, None)) => open -= 1,
|
||||
Err(_) => {}
|
||||
}
|
||||
};
|
||||
if !status.success() {
|
||||
let err = String::from_utf8_lossy(&err);
|
||||
let reason = err.trim();
|
||||
return Err(failed(&if reason.is_empty() { status.to_string() } else { reason.to_owned() }));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[cfg(unix)]
|
||||
fn decl(command: &str, args: &[&str], prepare: &[&str]) -> Decl {
|
||||
Decl {
|
||||
id: "sims".into(),
|
||||
name: "Simulators".into(),
|
||||
command: command.into(),
|
||||
args: args.iter().map(|a| a.to_string()).collect(),
|
||||
applies_to: "-ios".into(),
|
||||
run_args: vec![],
|
||||
env: BTreeMap::new(),
|
||||
prepare: prepare.iter().map(|a| a.to_string()).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A store with `d` from plugin `p` in `dir`, and `granted` programs pinned.
|
||||
#[cfg(unix)]
|
||||
fn fixture(dir: &Path, d: Decl, granted: &[&str]) -> (Arc<Devices>, Pins, Disposable) {
|
||||
let store: Arc<Devices> = Arc::default();
|
||||
let added = store.add("p".into(), dir.to_path_buf(), d);
|
||||
let pins: Pins = Arc::default();
|
||||
for program in granted {
|
||||
let cap = Capability::Process((*program).into()).to_string();
|
||||
pins.write().insert(("p".into(), cap), ProgramPin::approve(*program).unwrap());
|
||||
}
|
||||
(store, pins, added)
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn lists_what_the_program_prints() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::write(
|
||||
dir.path().join("list.sh"),
|
||||
r#"echo '[{"id":"A1","name":"iPhone 17","group":"iOS 26.0","running":true},{"id":"B2","name":"iPad"}]'"#,
|
||||
)
|
||||
.unwrap();
|
||||
let (store, pins, _keep) = fixture(dir.path(), decl("/bin/sh", &["./list.sh"], &[]), &["/bin/sh"]);
|
||||
let runner = DeviceRunner { store: &store, pins: &pins };
|
||||
assert_eq!(runner.providers().len(), 1);
|
||||
let devices = runner.list("p", "sims", None).unwrap();
|
||||
assert_eq!(devices.len(), 2);
|
||||
assert_eq!(devices[0].group.as_deref(), Some("iOS 26.0"));
|
||||
assert!(devices[0].running && !devices[1].running);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn ungranted_providers_are_hidden_and_refused() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (store, pins, _keep) = fixture(dir.path(), decl("/bin/sh", &["-c", "echo []"], &[]), &[]);
|
||||
let runner = DeviceRunner { store: &store, pins: &pins };
|
||||
assert!(runner.providers().is_empty());
|
||||
let err = runner.list("p", "sims", None).unwrap_err();
|
||||
assert!(err.message.contains("allow process:/bin/sh"), "{}", err.message);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn failures_carry_the_reason() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (store, pins, _keep) =
|
||||
fixture(dir.path(), decl("/bin/sh", &["-c", "echo xcrun missing >&2; exit 3"], &[]), &["/bin/sh"]);
|
||||
let err = DeviceRunner { store: &store, pins: &pins }.list("p", "sims", None).unwrap_err();
|
||||
assert!(err.message.contains("xcrun missing"), "{}", err.message);
|
||||
let (store, pins, _keep) = fixture(dir.path(), decl("/bin/echo", &["not json"], &[]), &["/bin/echo"]);
|
||||
let err = DeviceRunner { store: &store, pins: &pins }.list("p", "sims", None).unwrap_err();
|
||||
assert!(err.message.contains("JSON array"), "{}", err.message);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn prepare_answers_the_id_to_run_with() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (store, pins, _keep) = fixture(dir.path(), decl("/bin/sh", &[], &[]), &["/bin/sh"]);
|
||||
let runner = DeviceRunner { store: &store, pins: &pins };
|
||||
assert_eq!(runner.prepare("p", "sims", "avd:Pixel", None).unwrap(), "avd:Pixel");
|
||||
let boots = decl("/bin/sh", &[], &["/bin/sh", "-c", "echo booting ${device.id}; echo emulator-5554"]);
|
||||
let (store, pins, _keep) = fixture(dir.path(), boots, &["/bin/sh"]);
|
||||
let runner = DeviceRunner { store: &store, pins: &pins };
|
||||
assert_eq!(runner.prepare("p", "sims", "avd:Pixel", None).unwrap(), "emulator-5554");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn declarations_need_api_1_21_capabilities_and_their_files() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::create_dir(dir.path().join("devices")).unwrap();
|
||||
std::fs::write(dir.path().join("devices/list.py"), "").unwrap();
|
||||
let package = |engine: &str| {
|
||||
let src = format!("id = \"sims\"\nname = \"Sims\"\nversion = \"0.1.0\"\nengines.openidea = \"{engine}\"\n");
|
||||
Package::new(ide_extension::Manifest::parse(&src).unwrap(), dir.path().to_path_buf())
|
||||
};
|
||||
let pkg = package("^1.21");
|
||||
let point = DevicesPoint::new(Arc::default());
|
||||
let toml = |s: &str| -> toml::Value { toml::from_str(s).unwrap() };
|
||||
let minimal = "id = \"x\"\nname = \"X\"\ncommand = \"/bin/sh\"\nappliesTo = \"x\"\n";
|
||||
let old = point.prepare(&package("^1.20"), toml(minimal)).unwrap_err();
|
||||
assert!(old.contains("contributes.devices is new in plugin API 1.21"), "{old}");
|
||||
let kebab = point.prepare(&pkg, toml("id = \"x\"\nname = \"X\"\ncommand = \"/bin/sh\"\napplies-to = \"x\"\n"));
|
||||
assert!(kebab.is_err(), "unknown fields are refused");
|
||||
let ok = point
|
||||
.prepare(
|
||||
&pkg,
|
||||
toml("id = \"ios\"\nname = \"iOS\"\ncommand = \"/usr/bin/python3\"\nargs = [\"-I\", \"./devices/list.py\"]\nappliesTo = \"-ios$\"\nprepare = [\"/bin/sh\", \"./devices/list.py\"]\n"),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
ok.capabilities,
|
||||
[Capability::Process("/usr/bin/python3".into()), Capability::Process("/bin/sh".into())]
|
||||
);
|
||||
assert_eq!(ok.files, [PathBuf::from("devices/list.py"), PathBuf::from("devices/list.py")]);
|
||||
let script =
|
||||
point.prepare(&pkg, toml("id = \"x\"\nname = \"X\"\ncommand = \"./list.sh\"\nappliesTo = \"x\"\n"));
|
||||
assert!(script.unwrap_err().contains("one installed program"));
|
||||
let escape = point.prepare(
|
||||
&pkg,
|
||||
toml("id = \"x\"\nname = \"X\"\ncommand = \"/bin/sh\"\nargs = [\"./../x\"]\nappliesTo = \"x\"\n"),
|
||||
);
|
||||
assert!(escape.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_args_does_not_rewrite_device_id_as_package_path() {
|
||||
let pkg = Path::new("/plugins/mobile");
|
||||
let args = vec!["./boot.sh".into(), "${device.id}".into(), "--id=${device.id}".into()];
|
||||
let resolved = resolve_args(pkg, &args, Some("./../escape"));
|
||||
assert_eq!(
|
||||
resolved,
|
||||
vec![
|
||||
pkg.join("boot.sh").into_os_string(),
|
||||
std::ffi::OsString::from("./../escape"),
|
||||
std::ffi::OsString::from("--id=./../escape"),
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,7 @@ pub mod commit;
|
||||
mod console_rules;
|
||||
mod database;
|
||||
mod dependencies;
|
||||
pub mod devices;
|
||||
pub(crate) mod diagnostics;
|
||||
pub mod docs;
|
||||
mod endpoints;
|
||||
@@ -404,6 +405,8 @@ pub struct PluginHost {
|
||||
java_agents: Arc<java_agents::JavaAgents>,
|
||||
/// `[[contributes.skills]]` of enabled plugins.
|
||||
skills: Arc<skills::PluginSkills>,
|
||||
/// `[[contributes.devices]]` of enabled plugins.
|
||||
devices: Arc<devices::Devices>,
|
||||
/// `[[contributes.providers]]` of enabled plugins.
|
||||
providers: Arc<providers::Providers>,
|
||||
navigation: Mutex<navigation::NavigationIndex>,
|
||||
@@ -505,8 +508,18 @@ impl PluginHost {
|
||||
let providers: Arc<providers::Providers> = Arc::default();
|
||||
let java_agents: Arc<java_agents::JavaAgents> = Arc::default();
|
||||
let skills: Arc<skills::PluginSkills> = Arc::default();
|
||||
register_builtin_points(®istry, &ui, &languages, &run_detectors, &java_agents, &providers, &skills)
|
||||
.map_err(IdeError::internal)?;
|
||||
let devices: Arc<devices::Devices> = Arc::default();
|
||||
register_builtin_points(
|
||||
®istry,
|
||||
&ui,
|
||||
&languages,
|
||||
&run_detectors,
|
||||
&java_agents,
|
||||
&providers,
|
||||
&skills,
|
||||
&devices,
|
||||
)
|
||||
.map_err(IdeError::internal)?;
|
||||
let pins: Arc<RwLock<HashMap<(String, String), ProgramPin>>> = Arc::default();
|
||||
let policy_pins = pins.clone();
|
||||
languages.set_process_policy(Arc::new(move |plugin, cap| {
|
||||
@@ -543,6 +556,7 @@ impl PluginHost {
|
||||
run_detectors,
|
||||
java_agents,
|
||||
skills,
|
||||
devices,
|
||||
providers,
|
||||
navigation: Mutex::default(),
|
||||
endpoints: Mutex::default(),
|
||||
@@ -2018,6 +2032,22 @@ impl PluginHost {
|
||||
Arc::new(java_agents::PluginJavaAgents { store: self.java_agents.clone(), pins: self.pins.clone() })
|
||||
}
|
||||
|
||||
/// Device providers (`[[contributes.devices]]`) whose programs are granted.
|
||||
pub fn device_providers(&self) -> Vec<devices::DeviceProvider> {
|
||||
devices::DeviceRunner { store: &self.devices, pins: &self.pins }.providers()
|
||||
}
|
||||
|
||||
/// Runs a device provider's list command in `cwd` (blocking, up to [`devices::LIST_TIMEOUT`]).
|
||||
pub fn list_devices(&self, plugin: &str, provider: &str, cwd: Option<&Path>) -> IdeResult<Vec<devices::Device>> {
|
||||
devices::DeviceRunner { store: &self.devices, pins: &self.pins }.list(plugin, provider, cwd)
|
||||
}
|
||||
|
||||
/// Gets a device ready (boots an emulator) and returns the id to run with
|
||||
/// (blocking, up to [`devices::PREPARE_TIMEOUT`]).
|
||||
pub fn prepare_device(&self, plugin: &str, provider: &str, device: &str, cwd: Option<&Path>) -> IdeResult<String> {
|
||||
devices::DeviceRunner { store: &self.devices, pins: &self.pins }.prepare(plugin, provider, device, cwd)
|
||||
}
|
||||
|
||||
/// The syntax of plugin languages, for [`ide_language::set_external_syntax`].
|
||||
pub fn syntax_provider(self: &Arc<Self>) -> Arc<dyn ide_language::ExternalSyntax> {
|
||||
Arc::new(PluginSyntax(Arc::downgrade(self)))
|
||||
|
||||
@@ -59,6 +59,7 @@ fn command(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
|
||||
}
|
||||
|
||||
/// Registers every first-party extension point.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn register_builtin_points(
|
||||
registry: &ExtensionRegistry,
|
||||
ui: &Arc<UiStore>,
|
||||
@@ -67,6 +68,7 @@ pub fn register_builtin_points(
|
||||
java_agents: &Arc<super::java_agents::JavaAgents>,
|
||||
providers: &Arc<super::providers::Providers>,
|
||||
skills: &Arc<super::skills::PluginSkills>,
|
||||
devices: &Arc<super::devices::Devices>,
|
||||
) -> Result<(), String> {
|
||||
registry.register(Arc::new(UiPoint::new(COMMANDS, ui.clone(), command)))?;
|
||||
registry.register(Arc::new(super::theme::ThemesPoint::new(ui.clone())))?;
|
||||
@@ -75,6 +77,7 @@ pub fn register_builtin_points(
|
||||
registry.register(Arc::new(super::run_detectors::RunDetectorsPoint::new(run_detectors.clone())))?;
|
||||
registry.register(Arc::new(super::java_agents::JavaAgentsPoint::new(java_agents.clone())))?;
|
||||
registry.register(Arc::new(super::skills::SkillsPoint::new(skills.clone())))?;
|
||||
registry.register(Arc::new(super::devices::DevicesPoint::new(devices.clone())))?;
|
||||
registry.register(Arc::new(super::navigation::IndexersPoint))?;
|
||||
registry.register(Arc::new(super::providers::ProvidersPoint::new(providers.clone())))?;
|
||||
registry.register(Arc::new(UiPoint::new(super::providers::SECRETS_POINT, ui.clone(), super::providers::secret)))?;
|
||||
|
||||
@@ -2841,6 +2841,25 @@ fn official_string_tools() {
|
||||
assert_eq!(f.workspace.document(&editor.path).unwrap().0, before + 1, "both selections in one change");
|
||||
}
|
||||
|
||||
/// Android Devices: a device provider without code, offered once
|
||||
/// `process:sh` is granted, for Gradle install and connected test tasks.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn official_android_devices() {
|
||||
let f = fixture(Limits::default());
|
||||
let info = f.install(&official("android-devices"));
|
||||
assert!(info.error.is_none(), "{:?}", info.error);
|
||||
let providers = f.host.device_providers();
|
||||
assert_eq!(providers.len(), 1, "{providers:?}");
|
||||
let android = &providers[0];
|
||||
assert_eq!((android.plugin_id.as_str(), android.id.as_str()), ("openidea.android-devices", "android"));
|
||||
assert_eq!(android.env.get("ANDROID_SERIAL").map(String::as_str), Some("${device.id}"));
|
||||
let applies = regex_lite::Regex::new(&android.applies_to).unwrap();
|
||||
assert!(applies.is_match("./gradlew :app:installDebug"));
|
||||
assert!(applies.is_match("./gradlew connectedDebugAndroidTest"));
|
||||
assert!(!applies.is_match("./gradlew build"));
|
||||
}
|
||||
|
||||
/// Key Promoter: action events are batched; an idle plugin is
|
||||
/// woken once per batch, and its counts persist in storage.
|
||||
#[test]
|
||||
|
||||
@@ -131,6 +131,7 @@ Each contribution point is a table (`[contributes.settings]`) or an array of tab
|
||||
| `runDetectors` | `id`, `name`, `files`, `command`, `args?`, `test?`, `framework?`, `outputMode?` | no | [Run targets](/en/plugins/guides/run-targets) |
|
||||
| `runConfigurations` | `files` (API 1.4) | yes | [Run targets](/en/plugins/guides/run-targets) |
|
||||
| `javaAgents` | `path`, `args?` (API 1.10); `vmOptions?`, `jdk?` (API 1.14); `executor?` (API 1.18) | no | [README: Java agents](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#java-agents-api-110) |
|
||||
| `devices` | `id`, `name`, `command`, `args?`, `appliesTo`, `runArgs?`, `env?`, `prepare?` (API 1.21) | no | [README: Run devices](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#run-devices-api-121) |
|
||||
| `skills` | `path` (`skills/<name>/SKILL.md`, API 1.15) | no | [README: API 1.15](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#api-115) |
|
||||
| `mcpTools` | `name`, `description`, `inputSchema`, `readOnly`, `destructive` (API 1.4) | yes | [MCP tools](/en/plugins/guides/mcp) |
|
||||
| `themes` | `path`, `editor-scheme?` | no | [Themes](/en/plugins/guides/themes) |
|
||||
|
||||
@@ -35,7 +35,7 @@ The plugin API has one version number: the version of the WIT package in [`wit/`
|
||||
| 1.18.0 | OpenIDEA 0.1.54 | `[[contributes.overlays]]`: a package web page floating over the workbench that never takes the keyboard focus, placed and resized through `openidea.overlay`; `[[contributes.dialogs]]`: a package web page in a modal, resizable IDE dialog opened with `views.reveal`, with a `closed` view event and `openidea.dialog.close()`; `events.subscribe-paths-with-options` (`debounce-ms`), `workspace.project.generation` and `FilesChanged` project/generation fields, stale run target/configuration rejection, and the `project-closed` lifecycle event; `execution-configurations`, `run.start-with-options` and `runDetectors.outputMode`: `pipes` or `pty` console output for plugin run configurations; `[[contributes.runAnything]]` with the `run-anything-provider` export: Run Anything lines starting with the plugin's prefix; `views.open-terminal-session-in`: a keyed terminal in a project directory; `workspace.invoking-project`: the project of the window a call serves, also in `gutter-actions` and `hover-actions`; `events.watch-paths` and the `watched-files-changed` event: files and directories outside the project, within `fs.read` grants; the `run-configuration-completion` export: completion in the Arguments field of the plugin's own run configurations; `services.context` and `services.toolbar` menus on the IDE's own Services nodes, with the selected services as the command argument; `executor` on `[[contributes.javaAgents]]`: "Run/Debug '\<name\>' with \<title\>" beside Run and Debug, the only launches that get that agent, also startable from the plugin's own commands with a configuration id; grant-scoped `agents.fork-session`: fork a recorded native agent session (`claude`, `codex`, or `copilot`) into a new task in the invoking window's project (`agents` capability), with the host validating the session and building the fork invocation itself |
|
||||
| 1.19.0 | OpenIDEA 0.1.56 | `[capabilities.reasons]`: the plugin's own sentence on why it asks for a capability, shown below the host's description in the permission dialog and Settings › Plugins; `settings.open` / `settings.open-permissions`: open Settings at one of the plugin's own pages or at its permissions; `net.fetch-stream`: a response whose body is read as it arrives (server-sent events, streamed model replies), with the SDK's `host::fetch_stream` and `sse` parser; `editor.open-as-text`: open a file in the built-in text editor even when a custom editor claims it (the SDK's `host::open_editor_as_text`); the `openIn` menu: the **Open In** submenu of the editor, its tab and the Project view |
|
||||
| 1.20.0 | OpenIDEA 0.1.57 | Database table context menus and read-only table schema inspection (`database.schema`). Optional `syntax-decorations-provider` export: foreground marks on an open text editor, in the theme tokens `rainbow-1` … `rainbow-5` or its own `#rrggbb` colours for dark and light themes, and a bounded slice of the editor's syntax tree. |
|
||||
| 1.21.0 | In development | Run lifecycle & Run Config extensions: `run-started` event, `run-exited` for user-launched plugin runs, `run.stop`, `"java"` in `attach-child`, `prepareCommand` `mode` (`"run"` / `"debug"`) and loopback `javaDebug` JDWP attach, `run.upsert-configuration`, `run.open-edit-configurations`, `ownsBeforeLaunch`, transient `logFiles` log-tail tabs (`project.read` / `fs.read`), and the `runConsole.toolbar` menu. Settings controls: `presentation` (`radio`, `segmented`, `slider`, `color`, `checkbox-list`), `enumOptions` labels, hints and icons for `enum` values, `minimum` / `maximum` / `step`, and `when` conditions that hide a setting. `build.sdks` and `build.artifacts` under `build.read`: read installed JDKs/Maven/toolchains (`active` marking the project selection), build-model Maven/Gradle WAR artifacts, and Project Structure › Artifacts definitions (with `id`, `origin`, and `tool`) in trusted projects. `TextEditor::visible_lines` under `editor.read`: the first and last document line on screen when the command or event was invoked. `cloneSources`: plugin pages in the Clone Repository dialog's source list. `popup = true` on `[[contributes.dialogs]]`: a lightweight popup that closes on a click outside it or when the window loses focus. Database discovery and SQL execution in trusted projects: `database.connected-sources`, `database.list-schemas`, and `database.list-tables` under `database.schema`, plus bounded `database.execute-query` under the separate high-risk `database.query` capability. |
|
||||
| 1.21.0 | In development | Run lifecycle & Run Config extensions: `run-started` event, `run-exited` for user-launched plugin runs, `run.stop`, `"java"` in `attach-child`, `prepareCommand` `mode` (`"run"` / `"debug"`) and loopback `javaDebug` JDWP attach, `run.upsert-configuration`, `run.open-edit-configurations`, `ownsBeforeLaunch`, transient `logFiles` log-tail tabs (`project.read` / `fs.read`), and the `runConsole.toolbar` menu. Settings controls: `presentation` (`radio`, `segmented`, `slider`, `color`, `checkbox-list`), `enumOptions` labels, hints and icons for `enum` values, `minimum` / `maximum` / `step`, and `when` conditions that hide a setting. `build.sdks` and `build.artifacts` under `build.read`: read installed JDKs/Maven/toolchains (`active` marking the project selection), build-model Maven/Gradle WAR artifacts, and Project Structure › Artifacts definitions (with `id`, `origin`, and `tool`) in trusted projects. `TextEditor::visible_lines` under `editor.read`: the first and last document line on screen when the command or event was invoked. `cloneSources`: plugin pages in the Clone Repository dialog's source list. `popup = true` on `[[contributes.dialogs]]`: a lightweight popup that closes on a click outside it or when the window loses focus. Database discovery and SQL execution in trusted projects: `database.connected-sources`, `database.list-schemas`, and `database.list-tables` under `database.schema`, plus bounded `database.execute-query` under the separate high-risk `database.query` capability. Run devices: `[[contributes.devices]]` lists emulators, simulators and phones in a title bar chooser for the configurations it applies to. |
|
||||
|
||||
The full list of what each version added is in [`plugins/README.md`](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md).
|
||||
|
||||
@@ -58,7 +58,7 @@ engines.openidea = "^1.4"
|
||||
| `net.http:`, `ipc:`, `ide.commands`, `database.sources`; the `file-closed`, `settings-changed`, `input-mode-changed`, `run-exited`, `terminal-exited` and `content-tab-action` events; `runConfigurations`, `snippets`, `mcpTools`, command `icon`, run detector `framework`; the API 1.4 provider kinds and injections; the API 1.4 menu locations | `^1.4` |
|
||||
| `net:ask` | `^1.5` |
|
||||
| `on-event:websocket-ready` and background WebSockets | `^1.6` |
|
||||
| settings `presentation`, `enumOptions` and `when`; `cloneSources`; `database.query` | `^1.21` |
|
||||
| settings `presentation`, `enumOptions` and `when`; `cloneSources`; `database.query`; `[[contributes.devices]]` | `^1.21` |
|
||||
|
||||
## The component's own version
|
||||
|
||||
|
||||
@@ -131,6 +131,7 @@ optional = ["net:api.openai.com", "secrets"]
|
||||
| `runDetectors` | `id`、`name`、`files`、`command`、`args?`、`test?`、`framework?`、`outputMode?`(API 1.18) | 否 | [运行目标](/zh/plugins/guides/run-targets) |
|
||||
| `runConfigurations` | `files`(API 1.4) | 是 | [运行目标](/zh/plugins/guides/run-targets) |
|
||||
| `javaAgents` | `path`、`args?`(API 1.10);`vmOptions?`、`jdk?`(API 1.14);`executor?`(API 1.18) | 否 | [README:Java agents](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#java-agents-api-110) |
|
||||
| `devices` | `id`、`name`、`command`、`args?`、`appliesTo`、`runArgs?`、`env?`、`prepare?`(API 1.21) | 否 | [README:运行设备](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#run-devices-api-121) |
|
||||
| `skills` | `path`(`skills/<name>/SKILL.md`,API 1.15) | 否 | [README:API 1.15](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#api-115) |
|
||||
| `mcpTools` | `name`、`description`、`inputSchema`、`readOnly`、`destructive`(API 1.4) | 是 | [MCP 工具](/zh/plugins/guides/mcp) |
|
||||
| `themes` | `path`、`editor-scheme?` | 否 | [主题](/zh/plugins/guides/themes) |
|
||||
|
||||
@@ -32,7 +32,7 @@ description: "engines.openidea、插件 API 从 1.0 到 1.21 的各个版本,
|
||||
| 1.18.0 | OpenIDEA 0.1.54 | `[[contributes.overlays]]`:悬浮在工作台上方、从不抢占键盘焦点的插件网页,可通过 `openidea.overlay` 移动和调整大小;`[[contributes.dialogs]]`:插件网页显示在可调整大小的模态对话框中,用 `views.reveal` 打开,关闭时发 `closed` 视图事件,页面可调用 `openidea.dialog.close()`;`events.subscribe-paths-with-options`(`debounce-ms`)、`workspace.project.generation` 与 `FilesChanged` 的 `project`/`generation` 字段、过期运行目标/配置拒绝以及 `project-closed` 生命周期事件;`execution-configurations`、`run.start-with-options` 与 `runDetectors.outputMode`:插件运行配置的控制台输出方式(`pipes` 或 `pty`);`[[contributes.runAnything]]` 与 `run-anything-provider` 导出:以插件前缀开头的 Run Anything 行;`views.open-terminal-session-in`:在项目子目录中打开带 key 的终端;`workspace.invoking-project`:本次调用所服务窗口的项目,`gutter-actions` 和 `hover-actions` 中也可用;`events.watch-paths` 与 `watched-files-changed` 事件:监听项目之外、`fs.read` 授权范围内的文件和目录;`run-configuration-completion` 导出:补全插件自己运行配置的“实参”字段;`services.context` 和 `services.toolbar` 菜单:作用于 IDE 自带的 Services 节点,命令参数是选中的服务;`[[contributes.javaAgents]]` 的 `executor`:运行和调试旁边的“使用 \<title\> 运行/调试 '\<name\>'”,只有经它启动时才加载该代理,插件自己的命令也可用配置 id 经它启动;需授权的 `agents.fork-session`:把录制的原生 agent 会话(`claude`、`codex` 或 `copilot`)派生为调用窗口项目中的新任务(`agents` 能力),宿主自行校验会话并构造 fork 调用 |
|
||||
| 1.19.0 | OpenIDEA 0.1.56 | `[capabilities.reasons]`:插件用一句话说明为什么需要某个能力,显示在授权对话框和 设置 › 插件 中宿主说明的下方;`settings.open` / `settings.open-permissions`:打开设置并定位到插件自己的页面或它的权限;`net.fetch-stream`:边到达边读取响应体(服务器推送事件 SSE、模型的流式回复),SDK 提供 `host::fetch_stream` 和 `sse` 解析器;`editor.open-as-text`:即使文件被自定义编辑器认领,也用内置文本编辑器打开(SDK 的 `host::open_editor_as_text`);菜单点 `openIn`:编辑器、标签页和项目视图的 **打开方式** 子菜单 |
|
||||
| 1.20.0 | OpenIDEA 0.1.57 | 数据库表的上下文菜单和只读表结构查看(`database.schema`)。可选的 `syntax-decorations-provider` 导出:用主题 token `rainbow-1` … `rainbow-5` 或自带的深色/浅色主题 `#rrggbb` 颜色,给打开的文本编辑器中的范围涂前景色,依据编辑器语法树的有界片段。 |
|
||||
| 1.21.0 | `main` 上开发中 | 运行配置与运行生命周期扩展:`run-started` 事件与用户启动配置时的 `run-exited`、`run.stop`、`attach-child` 支持 `"java"`、`prepareCommand` 传入 `mode`(`"run"` / `"debug"`)并支持回环 `javaDebug` 附加 JDWP 调试器、`run.upsert-configuration`、`run.open-edit-configurations`、`ownsBeforeLaunch`、控制台日志文件实时标签页 `logFiles`(按 `project.read` / `fs.read` 授权)以及 `runConsole.toolbar` 菜单位置。设置控件:`presentation`(`radio`、`segmented`、`slider`、`color`、`checkbox-list`),为 `enum` 值提供标签、说明和图标的 `enumOptions`,`minimum` / `maximum` / `step`,以及隐藏设置的 `when` 条件。`build.read` 新增 `build.sdks` 与 `build.artifacts`:在受信任项目中读取已安装的 JDK / Maven / 工具链(带项目当前选中的 `active` 标记)以及构建模型 Maven/Gradle WAR 产物和 Project Structure › Artifacts 定义(含 `id`、`origin` 与 `tool`)。`editor.read` 下的 `TextEditor::visible_lines`:命令或事件触发时屏幕上显示的首行和末行。`[[contributes.dialogs]]` 的 `popup = true`:轻量弹出层,点击外部或窗口失去焦点时关闭。`cloneSources`:Clone Repository 对话框来源列表中的插件页面。受信任项目中的数据库发现与 SQL 执行:`database.schema` 新增 `database.connected-sources`、`database.list-schemas`、`database.list-tables`;新增独立高风险能力 `database.query` 与有界的 `database.execute-query`。 |
|
||||
| 1.21.0 | `main` 上开发中 | 运行配置与运行生命周期扩展:`run-started` 事件与用户启动配置时的 `run-exited`、`run.stop`、`attach-child` 支持 `"java"`、`prepareCommand` 传入 `mode`(`"run"` / `"debug"`)并支持回环 `javaDebug` 附加 JDWP 调试器、`run.upsert-configuration`、`run.open-edit-configurations`、`ownsBeforeLaunch`、控制台日志文件实时标签页 `logFiles`(按 `project.read` / `fs.read` 授权)以及 `runConsole.toolbar` 菜单位置。设置控件:`presentation`(`radio`、`segmented`、`slider`、`color`、`checkbox-list`),为 `enum` 值提供标签、说明和图标的 `enumOptions`,`minimum` / `maximum` / `step`,以及隐藏设置的 `when` 条件。`build.read` 新增 `build.sdks` 与 `build.artifacts`:在受信任项目中读取已安装的 JDK / Maven / 工具链(带项目当前选中的 `active` 标记)以及构建模型 Maven/Gradle WAR 产物和 Project Structure › Artifacts 定义(含 `id`、`origin` 与 `tool`)。`editor.read` 下的 `TextEditor::visible_lines`:命令或事件触发时屏幕上显示的首行和末行。`[[contributes.dialogs]]` 的 `popup = true`:轻量弹出层,点击外部或窗口失去焦点时关闭。`cloneSources`:Clone Repository 对话框来源列表中的插件页面。受信任项目中的数据库发现与 SQL 执行:`database.schema` 新增 `database.connected-sources`、`database.list-schemas`、`database.list-tables`;新增独立高风险能力 `database.query` 与有界的 `database.execute-query`。 运行设备:`[[contributes.devices]]` 在标题栏的设备选择器中列出模拟器和手机,用于其适用的运行配置。 |
|
||||
|
||||
每个版本新增内容的完整列表见 [`plugins/README.md`](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md)。
|
||||
|
||||
@@ -55,7 +55,7 @@ engines.openidea = "^1.4"
|
||||
| `net.http:`、`ipc:`、`ide.commands`、`database.sources`;`file-closed`、`settings-changed`、`input-mode-changed`、`run-exited`、`terminal-exited` 和 `content-tab-action` 事件;`runConfigurations`、`snippets`、`mcpTools`、命令 `icon`、运行检测器的 `framework`;API 1.4 的 provider kind 和嵌入语言;API 1.4 新增的菜单位置 | `^1.4` |
|
||||
| `net:ask` | `^1.5` |
|
||||
| `on-event:websocket-ready` 和后台 WebSocket | `^1.6` |
|
||||
| 设置的 `presentation`、`enumOptions` 和 `when`;`cloneSources`;`database.query` | `^1.21` |
|
||||
| 设置的 `presentation`、`enumOptions` 和 `when`;`cloneSources`;`database.query`;`[[contributes.devices]]` | `^1.21` |
|
||||
|
||||
## 组件本身的版本
|
||||
|
||||
|
||||
@@ -145,6 +145,7 @@ work), but 0.1 code no longer runs: rebuild it against the 1.0 SDK.
|
||||
| `runDetectors` | `id`, `name`, `files`, `command`, `args?`, `test?`, `framework?` (API 1.4; §6.2) | no |
|
||||
| `runConfigurations` | `files`: marker files for the optional `run-configurations` export (API 1.4) | yes |
|
||||
| `javaAgents` | `path` (a jar in the package), `args?`, `vmOptions?`, `jdk?`, `executor?` — a Java agent for Java run configurations, behind `java.agent` (API 1.10; `vmOptions`/`jdk` in 1.14; `executor` in 1.18; _Java agents_) | no |
|
||||
| `devices` | `id`, `name`, `command`, `args?`, `appliesTo`, `runArgs?`, `env?`, `prepare?` — run devices (emulators, simulators, phones) offered in a title bar chooser for the run configurations `appliesTo` matches (API 1.21; _Run devices_) | no |
|
||||
| `skills` | `path` (`skills/<name>/SKILL.md` in the package) — agent skill folder staged into coding-agent sessions (API 1.15) | no |
|
||||
| `mcpTools` | `name`, `description`, `inputSchema` (package JSON Schema path), `readOnly`, `destructive` (API 1.4; see _Plugin MCP tools_) | yes |
|
||||
| `snippets` | `language`, `path` (named JSON snippets; API 1.4) | no |
|
||||
@@ -382,8 +383,8 @@ machine. Users can revoke optional capabilities in Settings › Plugins.
|
||||
| `clipboard` | medium | `host::copy_to_clipboard` and the clipboard API in the plugin's web views |
|
||||
| `clipboard.read` | medium | API 1.11: `host::read_clipboard`, the clipboard's text and image, only in commands and view actions the user ran |
|
||||
| `agents` | medium | API 1.18: `host::fork_agent_session`, fork a recorded native agent session into a new task in the project; trusted projects only |
|
||||
| `code.semantics` | low | API 1.21: `Project::lsp_definition`, `lsp_type_definition`, `lsp_implementations`, `lsp_references`, `lsp_hover_info`, `lsp_document_symbols`; trusted projects only |
|
||||
| `run.output` | medium | API 1.21: `run-output` events with the stdout and stderr of runs and debug sessions; trusted projects only |
|
||||
| `code.semantics` | low | API 1.21: `Project::lsp_definition`, `lsp_type_definition`, `lsp_implementations`, `lsp_references`, `lsp_hover_info`, `lsp_document_symbols`; trusted projects only |
|
||||
| `run.output` | medium | API 1.21: `run-output` events with the stdout and stderr of runs and debug sessions; trusted projects only |
|
||||
|
||||
`process:` capabilities are also derived from what the contributions start: a
|
||||
language's `language-servers` and `debugger` commands and a run detector's
|
||||
@@ -3216,6 +3217,51 @@ The host accepts replies only from that plugin and window. Content is limited to
|
||||
1 Mi UTF-16 units and each side of a diff to 8 Mi, with at most 16 actions and one
|
||||
Save action.
|
||||
|
||||
### Run devices (API 1.21)
|
||||
|
||||
A plugin that knows the devices an app can run on (emulators, simulators,
|
||||
phones) can offer them in the title bar, next to the run configurations they
|
||||
apply to. Declare a program that lists them; no code is needed:
|
||||
|
||||
```toml
|
||||
engines.openidea = "^1.21"
|
||||
|
||||
[capabilities]
|
||||
required = ["process:sh"]
|
||||
|
||||
[[contributes.devices]]
|
||||
id = "android" # unique within the plugin
|
||||
name = "Android Devices" # menu heading when devices have no group
|
||||
command = "sh" # one installed program: a process: capability
|
||||
args = ["./devices/list.sh"] # `./x` is a file in the package
|
||||
appliesTo = '\b(install\w+|connected\w*AndroidTest)\b'
|
||||
runArgs = ["--device", "${device.id}"] # optional: appended to the arguments of a run
|
||||
env = { ANDROID_SERIAL = "${device.id}" } # optional: added to runs and debug sessions
|
||||
prepare = ["sh", "./devices/boot.sh", "${device.id}"] # optional
|
||||
```
|
||||
|
||||
- `command` prints a JSON array of devices on stdout:
|
||||
`[{"id": "emulator-5554", "name": "Pixel 8", "detail": "API 35", "group": "Emulators", "running": true}]`.
|
||||
`id` and `name` are required; `detail` is shown after the name, `group`
|
||||
headings the menu, and a `running` device is chosen when nothing is chosen yet.
|
||||
A non-zero exit shows the program's stderr in the menu. Listing may take up
|
||||
to 20 seconds.
|
||||
- `appliesTo` is a regular expression matched against a configuration's
|
||||
command line, arguments and parameters. The chooser shows when the selected
|
||||
configuration matches; the first matching provider wins.
|
||||
- `runArgs` and `env` expand `${device.id}` and `${device.name}`. `runArgs`
|
||||
apply to runs only; `env` to runs and debug sessions.
|
||||
- `prepare` runs before a run or debug session on the chosen device, with
|
||||
`${device.id}` expanded, for example to boot an emulator. The last line it
|
||||
prints is the id the session uses; nothing printed keeps the chosen id. It
|
||||
may take up to 5 minutes.
|
||||
- `command` and `prepare[0]` are `process:` capabilities: a provider is offered
|
||||
only while they are granted. They run in the project root. Before-launch
|
||||
tasks and build-on-update runs don't use the device.
|
||||
- The choice is kept per project and provider.
|
||||
|
||||
`plugins/official/android-devices` is a complete example.
|
||||
|
||||
### Java agents (API 1.10)
|
||||
|
||||
A plugin that observes or instruments the user's application (request
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
# android-devices — API 1.21 example
|
||||
|
||||
A device provider (`[[contributes.devices]]`): the title bar shows a device
|
||||
chooser next to Gradle run configurations that install the app or run connected
|
||||
tests (`./gradlew :app:installDebug`), and the chosen device reaches the run as
|
||||
`ANDROID_SERIAL`, which adb and the Android Gradle plugin's install tasks honour.
|
||||
|
||||
```
|
||||
android-devices/
|
||||
├─ plugin.toml # manifest: the provider and the process:sh capability
|
||||
└─ devices/
|
||||
└─ list.sh # prints `adb devices -l` as the JSON array the IDE reads
|
||||
```
|
||||
|
||||
It is data only: no code, no WebAssembly, no build step. `adb` must be on PATH
|
||||
(Android SDK platform tools). Connected emulators and phones are listed;
|
||||
offline and unauthorized ones are not.
|
||||
|
||||
Install the folder through Settings › Plugins › Install from Disk and allow
|
||||
`process:sh`. Check it from the repository root:
|
||||
|
||||
```sh
|
||||
cargo run -p ide-host --bin openidea-plugin -- check plugins/official/android-devices
|
||||
```
|
||||
|
||||
To boot an emulator before the run, add a `prepare` command that starts it and
|
||||
prints the serial to use. The fields are described in the
|
||||
[plugin guide](../../README.md#run-devices-api-121).
|
||||
@@ -0,0 +1,17 @@
|
||||
# Prints the devices `adb devices -l` reports as the JSON array OpenIDEA reads:
|
||||
# [{"id": "emulator-5554", "name": "Pixel 8", "group": "Emulators", "running": true}, ...]
|
||||
if ! command -v adb >/dev/null 2>&1; then
|
||||
echo "adb not found on PATH: install the Android SDK platform tools" >&2
|
||||
exit 1
|
||||
fi
|
||||
adb devices -l | awk '
|
||||
BEGIN { printf "["; n = 0 }
|
||||
NR > 1 && $2 == "device" {
|
||||
id = $1; name = id
|
||||
for (i = 3; i <= NF; i++) if ($i ~ /^model:/) { name = substr($i, 7); gsub("_", " ", name) }
|
||||
gsub(/["\\]/, "", id); gsub(/["\\]/, "", name)
|
||||
group = id ~ /^emulator-/ ? "Emulators" : "Physical Devices"
|
||||
printf "%s{\"id\":\"%s\",\"name\":\"%s\",\"group\":\"%s\",\"running\":true}", (n++ ? "," : ""), id, name, group
|
||||
}
|
||||
END { print "]" }
|
||||
'
|
||||
@@ -0,0 +1,22 @@
|
||||
# A device provider is data only: a program that lists devices, no `wasm`.
|
||||
id = "openidea.android-devices"
|
||||
name = "Android Devices (API Example)"
|
||||
version = "0.1.0"
|
||||
description = "Lists the emulators and phones adb sees and runs Gradle install tasks on the chosen one; see the package README."
|
||||
authors = ["OpenIDEA contributors"]
|
||||
license = "Apache-2.0"
|
||||
engines.openidea = "^1.21"
|
||||
|
||||
[capabilities]
|
||||
# `process:sh` runs `devices/list.sh`, which calls `adb` from PATH.
|
||||
required = ["process:sh"]
|
||||
|
||||
[[contributes.devices]]
|
||||
id = "android"
|
||||
name = "Android Devices"
|
||||
command = "sh"
|
||||
args = ["./devices/list.sh"]
|
||||
# Gradle install and connected test tasks: `./gradlew :app:installDebug`.
|
||||
appliesTo = '\b(install\w+|connected\w*AndroidTest)\b'
|
||||
# adb, and the Android Gradle plugin's install tasks, use the device ANDROID_SERIAL names.
|
||||
env = { ANDROID_SERIAL = "${device.id}" }
|
||||
@@ -575,6 +575,9 @@ plugin_content_tab_action trusted project_host bin
|
||||
plugin_context_keys trusted project_host bindings sync
|
||||
plugin_debug_attach_target trusted project_host bindings async
|
||||
plugin_decoration_sets trusted project_host bindings sync
|
||||
plugin_device_prepare trusted project_host bindings async
|
||||
plugin_device_providers trusted project_host bindings async
|
||||
plugin_devices trusted project_host bindings async
|
||||
plugin_endpoints trusted project_host bindings async
|
||||
plugin_event_kinds trusted project_host bindings async
|
||||
plugin_finish_operation trusted project_host bindings sync
|
||||
|
||||
@@ -1623,6 +1623,12 @@ export const commands = {
|
||||
pluginDebugAttachTarget: (config: string, run: RunId) => typedError<AttachableProcess, IdeError>(__TAURI_INVOKE("plugin_debug_attach_target", { config, run })),
|
||||
/** Project-scoped decoration snapshots; the window filters to its current root. */
|
||||
pluginDecorationSets: () => __TAURI_INVOKE<{ [key in string]: DecorationSet[] }>("plugin_decoration_sets"),
|
||||
/** Gets a device ready (boots an emulator…) and returns the id to run with. */
|
||||
pluginDevicePrepare: (pluginId: string, providerId: string, deviceId: string) => typedError<string, IdeError>(__TAURI_INVOKE("plugin_device_prepare", { pluginId, providerId, deviceId })),
|
||||
/** Device providers (simulators, emulators…) of enabled plugins whose programs are granted. */
|
||||
pluginDeviceProviders: () => typedError<DeviceProvider[], IdeError>(__TAURI_INVOKE("plugin_device_providers")),
|
||||
/** The devices a provider lists now, its command running in this window's project. */
|
||||
pluginDevices: (pluginId: string, providerId: string) => typedError<Device[], IdeError>(__TAURI_INVOKE("plugin_devices", { pluginId, providerId })),
|
||||
pluginEndpoints: (pluginId: string) => typedError<PluginEndpoint[], IdeError>(__TAURI_INVOKE("plugin_endpoints", { pluginId })),
|
||||
/** Kinds of workbench events plugins want (re-fetch on `subscriptionsChanged`). */
|
||||
pluginEventKinds: () => __TAURI_INVOKE<EventKind[]>("plugin_event_kinds"),
|
||||
@@ -8621,6 +8627,31 @@ export type DevContainerResourceStatus = {
|
||||
hostRequirements: HostRequirementsCheck,
|
||||
};
|
||||
|
||||
/** One device a provider listed. */
|
||||
export type Device = {
|
||||
id: string,
|
||||
name: string,
|
||||
/** Secondary text (`iOS 26.0`). */
|
||||
detail?: string | null,
|
||||
/** Heading the device is listed under (`iOS Simulators`, `Physical Devices`). */
|
||||
group?: string | null,
|
||||
/** Booted / connected: preferred when nothing is selected yet. */
|
||||
running?: boolean,
|
||||
};
|
||||
|
||||
/** A device provider of an enabled plugin, as the UI sees it. */
|
||||
export type DeviceProvider = {
|
||||
pluginId: string,
|
||||
id: string,
|
||||
name: string,
|
||||
/** Regular expression over a configuration's command line, arguments and parameters. */
|
||||
appliesTo: string,
|
||||
/** Appended to run arguments; `${device.id}` / `${device.name}` expand. */
|
||||
runArgs: string[],
|
||||
/** Added to the environment of runs and debug sessions (same expansions). */
|
||||
env: { [key in string]: string },
|
||||
};
|
||||
|
||||
export type Diagnostic = {
|
||||
range: Range,
|
||||
severity: Severity,
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { BarButton, Icon, Menu, type MenuItem } from "@/ui";
|
||||
import { useTx } from "@/platform/i18n";
|
||||
import type { RunConfig } from "@/platform/ipc";
|
||||
import { loadDeviceProviders, providerFor, providerKey, refreshDevices, selectDevice, useDevices } from "./devices";
|
||||
import styles from "./Run.module.css";
|
||||
|
||||
/**
|
||||
* Title bar device chooser (Rider's): shown next to the configuration chooser when a
|
||||
* plugin's device provider applies to the selected configuration.
|
||||
*/
|
||||
export function DeviceChooser({ config }: { config: RunConfig | undefined }) {
|
||||
const tx = useTx();
|
||||
const providers = useDevices((s) => s.providers);
|
||||
const provider = providerFor(config, providers);
|
||||
const key = provider ? providerKey(provider) : "";
|
||||
const devices = useDevices((s) => s.devices[key]);
|
||||
const selected = useDevices((s) => s.selected[key]);
|
||||
const loading = useDevices((s) => !!s.loading[key]);
|
||||
const error = useDevices((s) => s.errors[key]);
|
||||
const anchor = useRef<HTMLButtonElement>(null);
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
void Promise.resolve().then(loadDeviceProviders);
|
||||
}, [config?.id]);
|
||||
|
||||
// The list on first show, so a booted device is picked before the first run.
|
||||
useEffect(() => {
|
||||
if (provider && !devices && !loading) void refreshDevices(provider);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [key]);
|
||||
|
||||
if (!provider) return null;
|
||||
|
||||
const groups = new Map<string, MenuItem[]>();
|
||||
for (const d of devices ?? []) {
|
||||
const group = d.group ?? provider.name;
|
||||
const items = groups.get(group) ?? [];
|
||||
items.push({
|
||||
label: d.detail ? `${d.name} · ${d.detail}` : d.name,
|
||||
verbatim: true,
|
||||
checked: d.id === selected?.id,
|
||||
run: () => selectDevice(provider, d),
|
||||
});
|
||||
groups.set(group, items);
|
||||
}
|
||||
const items: MenuItem[] = [...groups].flatMap(([group, list]) => [
|
||||
{ kind: "header" as const, label: group, verbatim: true },
|
||||
...list,
|
||||
]);
|
||||
if (error) items.push({ label: error, verbatim: true, disabled: true });
|
||||
else if (devices && !devices.length) items.push({ label: "No devices found", disabled: true });
|
||||
if (items.length > 0) items.push({ kind: "separator" });
|
||||
items.push({
|
||||
label: loading ? "Refreshing…" : "Refresh Devices",
|
||||
icon: "refresh",
|
||||
disabled: loading,
|
||||
run: () => void refreshDevices(provider),
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
<BarButton
|
||||
ref={anchor}
|
||||
variant="title"
|
||||
className={styles.widgetChooser}
|
||||
tooltip={tx("Run Device")}
|
||||
aria-haspopup="menu"
|
||||
aria-expanded={open}
|
||||
onClick={() => {
|
||||
if (!open) void refreshDevices(provider);
|
||||
setOpen((v) => !v);
|
||||
}}
|
||||
>
|
||||
<span className={styles.widgetName}>{selected?.name ?? tx("Select Device")}</span>
|
||||
<Icon name="chevron-down" size={14} className={styles.widgetChevron} />
|
||||
</BarButton>
|
||||
<Menu open={open} anchor={anchor} items={items} placement="bottom-start" onClose={() => setOpen(false)} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import { configIcon } from "./configs";
|
||||
import { CMakeProfileChooser } from "./CMakeProfileChooser";
|
||||
import { FlutterDeviceChooser } from "./FlutterDeviceChooser";
|
||||
import { IosSimulatorChooser } from "./IosSimulatorChooser";
|
||||
import { DeviceChooser } from "./DeviceChooser";
|
||||
import { useRemoteLabel } from "./remote";
|
||||
import { CURRENT_FILE, useRun, isLive } from "./store";
|
||||
import { compoundTargets, selectedTarget } from "./sessionTargets";
|
||||
@@ -96,6 +97,7 @@ export function RunWidget() {
|
||||
</span>
|
||||
<Icon name="chevron-down" size={16} className={styles.widgetChevron} />
|
||||
</BarButton>
|
||||
<DeviceChooser config={selected} />
|
||||
<span className={styles.widgetButtons}>
|
||||
{showLoading ? (
|
||||
<>
|
||||
|
||||
@@ -96,6 +96,7 @@ async function runToEnd(
|
||||
const session = await startRun(config, undefined, undefined, {
|
||||
chain,
|
||||
show,
|
||||
noDevice: true,
|
||||
onExit: (code, stopped) => done(code === 0 && !stopped),
|
||||
});
|
||||
if (!session || session.status === "failed") return false;
|
||||
|
||||
@@ -68,6 +68,7 @@ export async function runUpdateBuild(build: RunConfig): Promise<void> {
|
||||
upsertTask({ id: taskId, title: build.name, message: null, fraction: null, done: false, cancel });
|
||||
try {
|
||||
const session = await startRun(build, undefined, undefined, {
|
||||
noDevice: true,
|
||||
onLine: (text) => {
|
||||
errors.add(text);
|
||||
const progress = buildProgressLine(text);
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import type { DeviceProvider, RunConfig } from "@/platform/ipc";
|
||||
import { providerFor, selectDevice, useDevices, withDevice } from "./devices";
|
||||
|
||||
const sims: DeviceProvider = {
|
||||
pluginId: "dotnet-mobile",
|
||||
id: "ios-simulators",
|
||||
name: "iOS Simulators",
|
||||
appliesTo: "net\\d+\\.\\d+-ios",
|
||||
runArgs: ["--device", "${device.id}"],
|
||||
env: { SIMULATOR_UDID: "${device.id}", SIMULATOR_NAME: "${device.name}" },
|
||||
};
|
||||
|
||||
const cfg = (args: string[], params: Record<string, string> = {}): RunConfig => ({
|
||||
id: "app",
|
||||
name: "App.iOS",
|
||||
kind: "dotnet",
|
||||
command: "dotnet",
|
||||
args,
|
||||
cwd: null,
|
||||
env: { KEEP: "1" },
|
||||
detected: true,
|
||||
isTest: false,
|
||||
debugAdapter: "dotnet-mobile",
|
||||
params,
|
||||
});
|
||||
|
||||
const ios = cfg(["run", "--project", "App.iOS/App.iOS.csproj"], { framework: "net10.0-ios" });
|
||||
|
||||
describe("run devices", () => {
|
||||
beforeEach(() => useDevices.setState({ providers: [sims], selected: {} }));
|
||||
|
||||
it("applies to configurations whose command line or parameters match", () => {
|
||||
expect(providerFor(ios)).toBe(sims);
|
||||
expect(providerFor(cfg(["run", "-f", "net9.0-ios"]))).toBe(sims);
|
||||
expect(providerFor(cfg(["run"], { framework: "net10.0-android" }))).toBeUndefined();
|
||||
useDevices.setState({ providers: [{ ...sims, appliesTo: "(" }] });
|
||||
expect(providerFor(ios), "an invalid pattern matches nothing").toBeUndefined();
|
||||
});
|
||||
|
||||
it("runs on the chosen device: arguments for runs, environment for both", () => {
|
||||
expect(withDevice(ios, "run"), "nothing chosen yet").toBe(ios);
|
||||
selectDevice(sims, { id: "A1", name: "iPhone 17 Pro", detail: null, group: "iOS 26.0", running: true });
|
||||
const run = withDevice(ios, "run");
|
||||
expect(run.args.slice(-2)).toEqual(["--device", "A1"]);
|
||||
expect(run.env).toEqual({ KEEP: "1", SIMULATOR_UDID: "A1", SIMULATOR_NAME: "iPhone 17 Pro" });
|
||||
const debug = withDevice(ios, "debug");
|
||||
expect(debug.args).toEqual(ios.args);
|
||||
expect(debug.env.SIMULATOR_UDID).toBe("A1");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,166 @@
|
||||
/**
|
||||
* Run devices contributed by plugins (simulators, emulators, phones): the
|
||||
* providers that apply to a configuration, the device chosen for it (per project
|
||||
* and provider) and what running on it adds to the configuration.
|
||||
*/
|
||||
import { create } from "zustand";
|
||||
import { call, commands, type Device, type DeviceProvider, type RunConfig } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
|
||||
const SELECTED_KEY = "openidea.run.device:";
|
||||
|
||||
export const providerKey = (p: Pick<DeviceProvider, "pluginId" | "id">) => `${p.pluginId}/${p.id}`;
|
||||
|
||||
interface DevicesState {
|
||||
providers: DeviceProvider[];
|
||||
/** Last listing per provider key. */
|
||||
devices: Record<string, Device[]>;
|
||||
loading: Record<string, boolean>;
|
||||
errors: Record<string, string>;
|
||||
/** Chosen device per provider key (this project). */
|
||||
selected: Record<string, Device>;
|
||||
}
|
||||
|
||||
export const useDevices = create<DevicesState>(() => ({
|
||||
providers: [],
|
||||
devices: {},
|
||||
loading: {},
|
||||
errors: {},
|
||||
selected: {},
|
||||
}));
|
||||
|
||||
function projectRoot(): string | null {
|
||||
return useProject.getState().project?.root ?? null;
|
||||
}
|
||||
|
||||
function storedSelection(root: string): Record<string, Device> {
|
||||
try {
|
||||
const raw = JSON.parse(localStorage.getItem(SELECTED_KEY + root) ?? "{}") as unknown;
|
||||
return raw && typeof raw === "object" ? (raw as Record<string, Device>) : {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
function storeSelection(root: string, selected: Record<string, Device>) {
|
||||
try {
|
||||
localStorage.setItem(SELECTED_KEY + root, JSON.stringify(selected));
|
||||
} catch {
|
||||
/* storage unavailable: the choice lasts for this session */
|
||||
}
|
||||
}
|
||||
|
||||
/** Re-reads the providers of the live plugins (and this project's stored choices). */
|
||||
export async function loadDeviceProviders(): Promise<void> {
|
||||
const startRoot = projectRoot();
|
||||
let providers: DeviceProvider[] = [];
|
||||
try {
|
||||
providers = await call(commands.pluginDeviceProviders());
|
||||
} catch {
|
||||
/* no plugin host (browser, tests) */
|
||||
}
|
||||
if (projectRoot() !== startRoot) return;
|
||||
useDevices.setState({ providers, selected: startRoot ? storedSelection(startRoot) : {} });
|
||||
}
|
||||
|
||||
const refreshSeq = new Map<string, number>();
|
||||
|
||||
/** Lists the devices of `provider` now; keeps the previous list on failure. */
|
||||
export async function refreshDevices(provider: DeviceProvider): Promise<void> {
|
||||
const key = providerKey(provider);
|
||||
const startRoot = projectRoot();
|
||||
const seq = (refreshSeq.get(key) ?? 0) + 1;
|
||||
refreshSeq.set(key, seq);
|
||||
useDevices.setState((s) => ({ loading: { ...s.loading, [key]: true } }));
|
||||
try {
|
||||
const devices = await call(commands.pluginDevices(provider.pluginId, provider.id));
|
||||
if (refreshSeq.get(key) !== seq || projectRoot() !== startRoot) return;
|
||||
useDevices.setState((s) => {
|
||||
const { [key]: _gone, ...errors } = s.errors;
|
||||
return { devices: { ...s.devices, [key]: devices }, errors };
|
||||
});
|
||||
// Nothing chosen yet: the device that is already running, as Rider does.
|
||||
const chosen = useDevices.getState().selected[key];
|
||||
const still = chosen && devices.find((d) => d.id === chosen.id);
|
||||
if (still) selectDevice(provider, still);
|
||||
else if (!chosen) {
|
||||
const running = devices.find((d) => d.running);
|
||||
if (running) selectDevice(provider, running);
|
||||
}
|
||||
} catch (e) {
|
||||
if (refreshSeq.get(key) !== seq || projectRoot() !== startRoot) return;
|
||||
const message = e instanceof Error ? e.message : String(e);
|
||||
useDevices.setState((s) => ({ errors: { ...s.errors, [key]: message } }));
|
||||
} finally {
|
||||
if (refreshSeq.get(key) === seq) {
|
||||
useDevices.setState((s) => ({ loading: { ...s.loading, [key]: false } }));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function selectDevice(provider: DeviceProvider, device: Device): void {
|
||||
const key = providerKey(provider);
|
||||
const selected = { ...useDevices.getState().selected, [key]: device };
|
||||
useDevices.setState({ selected });
|
||||
const root = projectRoot();
|
||||
if (root) storeSelection(root, selected);
|
||||
}
|
||||
|
||||
/** What a provider's `appliesTo` is matched against. */
|
||||
function commandLine(config: RunConfig): string {
|
||||
return [config.command, ...config.args, ...Object.values(config.params ?? {})].join(" ");
|
||||
}
|
||||
|
||||
/** The provider whose devices `config` runs on, if any. */
|
||||
export function providerFor(
|
||||
config: RunConfig | undefined,
|
||||
providers: readonly DeviceProvider[] = useDevices.getState().providers,
|
||||
): DeviceProvider | undefined {
|
||||
if (!config) return undefined;
|
||||
const line = commandLine(config);
|
||||
return providers.find((p) => {
|
||||
try {
|
||||
return new RegExp(p.appliesTo).test(line);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const expand = (template: string, device: Device) =>
|
||||
template.replaceAll("${device.id}", device.id).replaceAll("${device.name}", device.name);
|
||||
|
||||
/** The provider and chosen device `config` runs on, if both exist. */
|
||||
export function chosenDevice(config: RunConfig): { provider: DeviceProvider; device: Device } | undefined {
|
||||
const provider = providerFor(config);
|
||||
const device = provider && useDevices.getState().selected[providerKey(provider)];
|
||||
return provider && device ? { provider, device } : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* `config` on its chosen device: the provider's run arguments appended (for runs)
|
||||
* and its environment added. Unchanged without a provider or a chosen device.
|
||||
* `id` replaces the device id (what the provider's `prepare` answered).
|
||||
*/
|
||||
export function withDevice(config: RunConfig, mode: "run" | "debug", id?: string): RunConfig {
|
||||
const chosen = chosenDevice(config);
|
||||
if (!chosen) return config;
|
||||
const { provider } = chosen;
|
||||
const device = id ? { ...chosen.device, id } : chosen.device;
|
||||
const env = { ...config.env };
|
||||
for (const [k, v] of Object.entries(provider.env)) env[k] = expand(v, device);
|
||||
const args = mode === "run" ? [...config.args, ...provider.runArgs.map((a) => expand(a, device))] : config.args;
|
||||
return { ...config, args, env };
|
||||
}
|
||||
|
||||
/**
|
||||
* `withDevice` after the provider got the device ready (booted an emulator); throws
|
||||
* what the provider reported when it could not.
|
||||
*/
|
||||
export async function onDevice(config: RunConfig, mode: "run" | "debug"): Promise<RunConfig> {
|
||||
const chosen = chosenDevice(config);
|
||||
if (!chosen) return config;
|
||||
const { provider, device } = chosen;
|
||||
const id = await call(commands.pluginDevicePrepare(provider.pluginId, provider.id, device.id));
|
||||
return withDevice(config, mode, id);
|
||||
}
|
||||
@@ -138,6 +138,7 @@ import { rerunFailedConfigs } from "./testing/rerun";
|
||||
import { TEST_TREE_FOCUS, testTree } from "./testTree";
|
||||
import { startAgentRun, trimAgentArchive, type AgentRunRequest } from "./agentRuns";
|
||||
import { compoundTargets, selectedTarget } from "./sessionTargets";
|
||||
import { onDevice } from "./devices";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { UNITY_CONFIG_KIND, showUnityAttach } from "./unity";
|
||||
|
||||
@@ -219,6 +220,17 @@ async function debugLaunch(config: RunConfig, chain: readonly string[], show?: b
|
||||
} catch (e) {
|
||||
return notifyCwdError(config, e);
|
||||
}
|
||||
try {
|
||||
config = await onDevice(config, "debug");
|
||||
} catch (e) {
|
||||
notifications().notify({
|
||||
group: "run",
|
||||
level: "error",
|
||||
title: tx`Cannot prepare the device for '${config.name}'`,
|
||||
body: e instanceof Error ? e.message : String(e),
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (!(await prepareLaunch(config, chain, show))) return;
|
||||
const originalConfig = config;
|
||||
const typePrepare = typeForConfig(config)?.prepareLaunch;
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
*/
|
||||
import { withRunTarget } from "@/platform/runTargetSelection";
|
||||
import { notifyCwdError, withExpandedCwd } from "./cwdMacros";
|
||||
import { chosenDevice, onDevice } from "./devices";
|
||||
import { create } from "zustand";
|
||||
import { Channel } from "@tauri-apps/api/core";
|
||||
import {
|
||||
@@ -988,6 +989,8 @@ interface StartRunOptions {
|
||||
check?: { signal: AbortSignal; own: (sessionId: string) => void };
|
||||
/** The debugger of this run has started already and waits for the program: not another instance of it. */
|
||||
debuggerWaiting?: boolean;
|
||||
/** A helper run (before launch build): not on the device chosen in the title bar. */
|
||||
noDevice?: boolean;
|
||||
}
|
||||
|
||||
/** Starts `config`, reusing the tab of a finished (or the given) session (see `reusableTab`). */
|
||||
@@ -1252,6 +1255,14 @@ async function startRunIn(
|
||||
if (!check && launch.kind === "tomcat") useRun.setState({ activeSession: sessionId });
|
||||
if (runtimes.get(sessionId)?.generation !== generation) return getSession(sessionId) ?? null;
|
||||
}
|
||||
// On the device chosen in the title bar: after `prepareLaunch`, which rebuilds the arguments.
|
||||
const device = options.launch || options.noDevice ? undefined : chosenDevice(launch);
|
||||
if (device) {
|
||||
enqueue(sessionId, { kind: "system", text: tx`Preparing ${device.device.name}…\n` });
|
||||
flush(sessionId);
|
||||
launch = await onDevice(launch, "run");
|
||||
if (runtimes.get(sessionId)?.generation !== generation) return getSession(sessionId) ?? null;
|
||||
}
|
||||
const machine = isFlutterMachineRun(launch);
|
||||
if (machine) rt.stdout = flutterMachineOutput(sessionId, config);
|
||||
// Debug launches read the agent's output lines, `flutter run --machine` speaks JSON: never through a terminal.
|
||||
|
||||
@@ -5752,5 +5752,11 @@
|
||||
"Installation": "Installation",
|
||||
"Host architecture": "Host architecture",
|
||||
"Detect toolchains": "Detect toolchains",
|
||||
"For MinGW, empty fields are detected from the toolset, otherwise from PATH. Visual Studio uses vcvarsall for its compiler, headers and libraries. Explicit compilers and build tools are passed to CMake as CMAKE_C_COMPILER, CMAKE_CXX_COMPILER and CMAKE_MAKE_PROGRAM.": "For MinGW, empty fields are detected from the toolset, otherwise from PATH. Visual Studio uses vcvarsall for its compiler, headers and libraries. Explicit compilers and build tools are passed to CMake as CMAKE_C_COMPILER, CMAKE_CXX_COMPILER and CMAKE_MAKE_PROGRAM."
|
||||
"For MinGW, empty fields are detected from the toolset, otherwise from PATH. Visual Studio uses vcvarsall for its compiler, headers and libraries. Explicit compilers and build tools are passed to CMake as CMAKE_C_COMPILER, CMAKE_CXX_COMPILER and CMAKE_MAKE_PROGRAM.": "For MinGW, empty fields are detected from the toolset, otherwise from PATH. Visual Studio uses vcvarsall for its compiler, headers and libraries. Explicit compilers and build tools are passed to CMake as CMAKE_C_COMPILER, CMAKE_CXX_COMPILER and CMAKE_MAKE_PROGRAM.",
|
||||
"No devices found": "No devices found",
|
||||
"Refresh Devices": "Refresh Devices",
|
||||
"Run Device": "Run Device",
|
||||
"Select Device": "Select Device",
|
||||
"Cannot prepare the device for '{name}'": "Cannot prepare the device for '{name}'",
|
||||
"Preparing {name}…\n": "Preparing {name}…\n"
|
||||
}
|
||||
@@ -762,6 +762,13 @@
|
||||
"Edit Changelist…": "Editar lista de cambios…",
|
||||
"Edit Commit Message…": "Editar mensaje de confirmación…",
|
||||
"Edit Configurations…": "Editar configuraciones…",
|
||||
"No devices found": "No se encontraron dispositivos",
|
||||
"Refreshing…": "Actualizando…",
|
||||
"Refresh Devices": "Actualizar dispositivos",
|
||||
"Run Device": "Dispositivo de ejecución",
|
||||
"Select Device": "Seleccionar dispositivo",
|
||||
"Cannot prepare the device for '{name}'": "No se puede preparar el dispositivo para '{name}'",
|
||||
"Preparing {name}…\n": "Preparando {name}…\n",
|
||||
"Edit Configuration…": "Editar configuración…",
|
||||
"Edit Data": "Editar datos",
|
||||
"Edit the configuration that would run the context before saving it": "Editar la configuración que ejecutaría el contexto antes de guardarla",
|
||||
|
||||
@@ -702,6 +702,13 @@
|
||||
"Edit Changelist…": "Modifier la liste de modifications…",
|
||||
"Edit Commit Message…": "Modifier le message de commit…",
|
||||
"Edit Configurations…": "Modifier les configurations…",
|
||||
"No devices found": "Aucun appareil trouvé",
|
||||
"Refreshing…": "Actualisation…",
|
||||
"Refresh Devices": "Actualiser les appareils",
|
||||
"Run Device": "Appareil d'exécution",
|
||||
"Select Device": "Sélectionner un appareil",
|
||||
"Cannot prepare the device for '{name}'": "Impossible de préparer l'appareil pour « {name} »",
|
||||
"Preparing {name}…\n": "Préparation de {name}…\n",
|
||||
"Edit Configuration…": "Modifier la configuration…",
|
||||
"Edit Data": "Modifier les données",
|
||||
"Edit the configuration that would run the context before saving it": "Modifier la configuration qui exécuterait le contexte avant de l'enregistrer",
|
||||
|
||||
@@ -799,6 +799,13 @@
|
||||
"Edit Changelist…": "변경 목록 편집…",
|
||||
"Edit Commit Message…": "커밋 메시지 편집…",
|
||||
"Edit Configurations…": "구성 편집…",
|
||||
"No devices found": "기기를 찾을 수 없음",
|
||||
"Refreshing…": "새로 고치는 중…",
|
||||
"Refresh Devices": "기기 새로 고침",
|
||||
"Run Device": "실행 기기",
|
||||
"Select Device": "기기 선택",
|
||||
"Cannot prepare the device for '{name}'": "'{name}'의 기기를 준비할 수 없음",
|
||||
"Preparing {name}…\n": "{name} 준비 중…\n",
|
||||
"Edit Configuration…": "구성 편집…",
|
||||
"Edit Data": "데이터 편집",
|
||||
"Edit the configuration that would run the context before saving it": "저장하기 전에 컨텍스트를 실행할 구성 편집",
|
||||
|
||||
@@ -754,6 +754,13 @@
|
||||
"Edit Changelist…": "Edytuj listę zmian…",
|
||||
"Edit Commit Message…": "Edytuj wiadomość zatwierdzenia…",
|
||||
"Edit Configurations…": "Edytuj konfiguracje…",
|
||||
"No devices found": "Nie znaleziono urządzeń",
|
||||
"Refreshing…": "Odświeżanie…",
|
||||
"Refresh Devices": "Odśwież urządzenia",
|
||||
"Run Device": "Urządzenie uruchomieniowe",
|
||||
"Select Device": "Wybierz urządzenie",
|
||||
"Cannot prepare the device for '{name}'": "Nie można przygotować urządzenia dla „{name}”",
|
||||
"Preparing {name}…\n": "Przygotowywanie {name}…\n",
|
||||
"Edit Configuration…": "Edytuj konfigurację…",
|
||||
"Edit Data": "Edytuj dane",
|
||||
"Edit the configuration that would run the context before saving it": "Edytuj konfigurację, która uruchomiłaby kontekst, przed jej zapisaniem",
|
||||
|
||||
@@ -754,6 +754,13 @@
|
||||
"Edit Changelist…": "Editar lista de alterações…",
|
||||
"Edit Commit Message…": "Editar mensagem de commit…",
|
||||
"Edit Configurations…": "Editar configurações…",
|
||||
"No devices found": "Nenhum dispositivo encontrado",
|
||||
"Refreshing…": "Atualizando…",
|
||||
"Refresh Devices": "Atualizar dispositivos",
|
||||
"Run Device": "Dispositivo de execução",
|
||||
"Select Device": "Selecionar dispositivo",
|
||||
"Cannot prepare the device for '{name}'": "Não foi possível preparar o dispositivo para '{name}'",
|
||||
"Preparing {name}…\n": "Preparando {name}…\n",
|
||||
"Edit Configuration…": "Editar configuração…",
|
||||
"Edit Data": "Editar dados",
|
||||
"Edit the configuration that would run the context before saving it": "Editar a configuração que executaria o contexto antes de salvá-la",
|
||||
|
||||
@@ -2052,6 +2052,12 @@
|
||||
"Edit Changelist…": "编辑更改列表…",
|
||||
"Edit Commit Message…": "编辑提交消息…",
|
||||
"Edit Configurations…": "编辑配置…",
|
||||
"No devices found": "未找到设备",
|
||||
"Refresh Devices": "刷新设备",
|
||||
"Run Device": "运行设备",
|
||||
"Select Device": "选择设备",
|
||||
"Cannot prepare the device for '{name}'": "无法为“{name}”准备设备",
|
||||
"Preparing {name}…\n": "正在准备 {name}…\n",
|
||||
"Edit Configuration…": "编辑配置…",
|
||||
"Edit Data": "编辑数据",
|
||||
"Edit the configuration that would run the context before saving it": "在保存前编辑将运行上下文的配置",
|
||||
|
||||
Reference in new issue
Заблокувати користувача