Skip to content

XP event5x XPListening, games, ratings, comments and chat earn five times the XP

leftLeaderboard

juicewrld-desktopsrc-taurisrcpluginshost.rs

1.4.2Released Nov 21, 2026

host.rs

580 lines29.8 KBRust
//! The app's side of the plugin host process: starting juicewrld-plugins.exe, its requests and their answers, and the//! watchdog. The host sends a heartbeat from its main thread four times a second (its message loop runs it, inside a//! plugin's own dialog too). The app kills the host when an audio call is stuck for 3 s, when the heartbeat stops for//! 5 s with nothing asked of it (3 s while an editor window is open, since an editor owned by the app's window shares//! its input; 15 s then even with a request under way), or when a request runs out of time with no heartbeat (a plugin//! call that never returns). A request that runs out of time while the heartbeat goes on (a plugin's dialog waiting for//! an answer, usually) fails on its own and the host is left alone. Either way (a kill, or the host crashing on its own)//! every request waiting is failed and `on_gone` hears which generation went and why, so the instances it ran can be//! reported lost; the next request starts a new host.use super::proto::{self, Event, Frame, Reply, Request, KIND_EVENT, KIND_REQUEST, KIND_RESPONSE};use serde_json::Value;use std::collections::HashMap;use std::io::{BufRead, BufReader};use std::os::windows::io::AsRawHandle;use std::os::windows::process::CommandExt;use std::path::PathBuf;use std::process::{Child, ChildStdin, Command, Stdio};use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};use std::sync::{mpsc, Arc, Mutex, MutexGuard};use std::time::{Duration, Instant};const CREATE_NO_WINDOW: u32 = 0x0800_0000;/// Silence from the host's main thread this long, with nothing asked of it, is a hang.const SILENCE: Duration = Duration::from_secs(5);/// The same while a plugin's editor is open: its window is owned by the app's, which ties their input together (measured/// in tests/host.rs), so a plugin whose window stopped answering is ended sooner.const SILENCE_EDITOR: Duration = Duration::from_secs(3);/// While an editor is open, silence this long is a hang even with a request under way (an open may take a minute to/// load a big module): the app's input mustn't be held up for longer. A module that really takes this long to load while/// an editor is open ends the host too, the lesser harm.const SILENCE_EDITOR_BUSY: Duration = Duration::from_secs(15);/// A heartbeat this recent says the host's main thread is alive (in a plugin's own dialog, say), not hung.const FRESH: Duration = Duration::from_millis(1500);/// An audio call reported stuck for this long is a hang.const STUCK: Duration = Duration::from_secs(3);/// How long a plugin's editor may take to open. Opening one takes a moment, not more: one that hasn't opened by then has/// hung (with no heartbeat, the host is ended), and its window, owned by the app's and so sharing its input, mustn't/// hold the app's input up for longer than that.pub const EDITOR_LIMIT: Duration = Duration::from_secs(10);fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {    m.lock().unwrap_or_else(|e| e.into_inner())}/// Puts a process this app started (the host, a scan child) in a job that ends with the app: however the app goes/// (closed, crashed, killed), Windows ends them too, so no plugin process is ever left behind, stuck in a plugin.pub fn adopt(child: &Child) {    use std::sync::OnceLock;    use windows::Win32::Foundation::HANDLE;    use windows::Win32::System::JobObjects::{        AssignProcessToJobObject, CreateJobObjectW, JobObjectExtendedLimitInformation, SetInformationJobObject,        JOBOBJECT_EXTENDED_LIMIT_INFORMATION, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,    };    static JOB: OnceLock<usize> = OnceLock::new();    let job = *JOB.get_or_init(|| {        // SAFETY: a job of our own, its handle kept open for the life of the process (closing it ends the children).        unsafe {            let Ok(job) = CreateJobObjectW(None, None) else { return 0 };            let mut info = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default();            info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;            let _ = SetInformationJobObject(                job,                JobObjectExtendedLimitInformation,                &info as *const _ as *const std::ffi::c_void,                std::mem::size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as u32,            );            job.0 as usize        }    });    if job != 0 {        // SAFETY: the job handle above and a child we just started.        unsafe {            let _ = AssignProcessToJobObject(HANDLE(job as *mut _), HANDLE(child.as_raw_handle()));        }    }}/// Why a host went.#[derive(Debug, Clone, PartialEq)]pub struct Gone {    pub generation: u32,    /// "crashed", "hung" or "stopped" (the app closed it, or plugins were switched off).    pub reason: String,    /// The crash report (host/main.rs `crashed`): exception code, instance, module.    pub crash: Option<Value>,}type Waiting = mpsc::Sender<Result<(Value, Vec<u8>), String>>;/// A request waiting for its answer.struct Pending {    tx: Waiting,    deadline: Instant,    /// An Open: if it runs out of time and finishes later, its instance is closed (nobody has it).    opens: bool,}pub struct Conn {    pub generation: u32,    pub pid: u32,    child: Mutex<Child>,    stdin: Mutex<ChildStdin>,    pending: Mutex<HashMap<u32, Pending>>,    /// Requests that ran out of time while the host was alive, and whether each was an Open: a late answer to an Open    /// is an instance nobody knows of, closed at once.    expired: Mutex<HashMap<u32, bool>>,    /// The folders and owner window the host was last told (Hello), so a change reaches a host already running.    hello: Mutex<(Vec<String>, u64)>,    /// Editor windows open in the host, as its last heartbeat said.    editors: AtomicU32,    next_id: AtomicU32,    beat: Mutex<Instant>,    stuck_since: Mutex<Option<Instant>>,    /// The instances the last heartbeat said were stuck in their audio call: a hang's culprits.    stuck: Mutex<Vec<u32>>,    dead: AtomicBool,    finished: AtomicBool,    kill_reason: Mutex<Option<String>>,    crash: Mutex<Option<Value>>,}impl Conn {    /// Asks the host something and waits (up to `limit`) for the answer. Blocking: call from a worker thread.    pub fn request(&self, req: &Request, bytes: Vec<u8>, limit: Duration) -> Result<(Value, Vec<u8>), String> {        if self.dead.load(Ordering::SeqCst) {            return Err("the plugin host has stopped".into());        }        let id = self.next_id.fetch_add(1, Ordering::Relaxed);        let (tx, rx) = mpsc::channel();        let opens = matches!(req, Request::Open { .. });        lock(&self.pending).insert(id, Pending { tx, deadline: Instant::now() + limit, opens });        let frame = Frame::new(KIND_REQUEST, id, req, bytes);        if proto::write_frame(&mut *lock(&self.stdin), &frame).is_err() {            lock(&self.pending).remove(&id);            return Err("the plugin host has stopped".into());        }        match rx.recv_timeout(limit + Duration::from_secs(2)) {            Ok(r) => r,            Err(_) => Err("the plugin host didn't answer".into()),        }    }    /// The host's process handle, for duplicating handles into it.    pub fn process_handle(&self) -> isize {        lock(&self.child).as_raw_handle() as isize    }    pub fn alive(&self) -> bool {        !self.dead.load(Ordering::SeqCst)    }    /// Ends the host now; `reason` is what the instances' pages are told.    pub fn kill(&self, reason: &str) {        lock(&self.kill_reason).get_or_insert_with(|| reason.to_string());        let _ = lock(&self.child).kill();    }}type OnEvent = Arc<dyn Fn(u32, Event) + Send + Sync>;type OnGone = Arc<dyn Fn(Gone) + Send + Sync>;/// The host is gone (its pipe closed, or its process ended): once, whichever is noticed first. Every waiting request/// fails, and `on_gone` hears why.fn finish(c: &Arc<Conn>, on_gone: &OnGone) {    if c.finished.swap(true, Ordering::SeqCst) {        return;    }    c.dead.store(true, Ordering::SeqCst);    // Its exit code says how it went; one that closed the pipe and lingers is ended.    let t0 = Instant::now();    let status = loop {        if let Ok(Some(s)) = lock(&c.child).try_wait() {            break Some(s);        }        if t0.elapsed() > Duration::from_secs(2) {            let _ = lock(&c.child).kill();            break None;        }        std::thread::sleep(Duration::from_millis(20));    };    // Give the log thread a moment to read the crash report.    std::thread::sleep(Duration::from_millis(100));    let killed = lock(&c.kill_reason).clone();    // A crash names its instance in its report; a hang, the instance the heartbeat said was stuck.    let stuck = lock(&c.stuck).clone();    let crash = lock(&c.crash).clone().or_else(|| match (killed.as_deref(), stuck.first()) {        (Some("hung"), Some(inst)) => Some(serde_json::json!({ "inst": inst, "stuck": stuck })),        _ => None,    });    let reason = killed.unwrap_or_else(|| if crash.is_some() || !status.is_some_and(|s| s.success()) { "crashed".into() } else { "stopped".into() });    let message = match reason.as_str() {        "hung" => "the plugin host stopped responding",        "crashed" => "a plugin crashed",        _ => "the plugin host has stopped",    };    for (_, w) in lock(&c.pending).drain() {        let _ = w.tx.send(Err(message.into()));    }    eprintln!("[plugins] the plugin host (generation {}) is gone: {reason}{}", c.generation, crash.as_ref().map(|c| format!(" {c}")).unwrap_or_default());    on_gone(Gone { generation: c.generation, reason, crash });}pub struct Host {    exe: PathBuf,    conn: Mutex<Option<Arc<Conn>>>,    generation: AtomicU32,    on_event: OnEvent,    on_gone: OnGone,    /// When the last few hosts died: a host that keeps crashing isn't restarted on its own.    deaths: Mutex<Vec<Instant>>,}impl Host {    pub fn new(exe: PathBuf, on_event: OnEvent, on_gone: OnGone) -> Host {        Host { exe, conn: Mutex::new(None), generation: AtomicU32::new(0), on_event, on_gone, deaths: Mutex::new(Vec::new()) }    }    pub fn exe_present(&self) -> bool {        self.exe.is_file()    }    /// The running host, if there is one.    pub fn current(&self) -> Option<Arc<Conn>> {        lock(&self.conn).clone().filter(|c| c.alive())    }    /// The running host, or a new one, told which folders it may load from and which window owns its editors. A host    /// already running is told again when those changed since (a folder added or ticked, one unticked).    pub fn connect(&self, roots: &[String], owner: u64) -> Result<Arc<Conn>, String> {        let running = lock(&self.conn).clone().filter(|c| c.alive());        if let Some(c) = running {            if *lock(&c.hello) != (roots.to_vec(), owner) {                c.request(&Request::Hello { version: proto::VERSION, roots: roots.to_vec(), owner }, Vec::new(), Duration::from_secs(10))?;                *lock(&c.hello) = (roots.to_vec(), owner);                eprintln!("[plugins] told the plugin host its folders again: {roots:?}");            }            return Ok(c);        }        let mut slot = lock(&self.conn);        if let Some(c) = slot.as_ref().filter(|c| c.alive()) {            return Ok(c.clone());        }        let generation = self.generation.fetch_add(1, Ordering::SeqCst) + 1;        let mut cmd = Command::new(&self.exe);        cmd.arg("--host").stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).creation_flags(CREATE_NO_WINDOW);        // A debug test run's folders are the only ones the host may load from.        super::child_env(&mut cmd);        let mut child = cmd.spawn().map_err(|e| format!("couldn't start the plugin host: {e}"))?;        adopt(&child);        let stdin = child.stdin.take().ok_or("no pipe to the plugin host")?;        let stdout = child.stdout.take().ok_or("no pipe from the plugin host")?;        let stderr = child.stderr.take().ok_or("no pipe from the plugin host")?;        let conn = Arc::new(Conn {            generation,            pid: child.id(),            child: Mutex::new(child),            stdin: Mutex::new(stdin),            pending: Mutex::new(HashMap::new()),            expired: Mutex::new(HashMap::new()),            hello: Mutex::new((roots.to_vec(), owner)),            editors: AtomicU32::new(0),            next_id: AtomicU32::new(1),            beat: Mutex::new(Instant::now()),            stuck_since: Mutex::new(None),            stuck: Mutex::new(Vec::new()),            dead: AtomicBool::new(false),            finished: AtomicBool::new(false),            kill_reason: Mutex::new(None),            crash: Mutex::new(None),        });        eprintln!("[plugins] started the plugin host (process {}, generation {generation})", conn.pid);        // Its stderr: logged, and a crash report kept for the pages.        let c = conn.clone();        let _ = std::thread::Builder::new().name("plugins-log".into()).spawn(move || {            for line in BufReader::new(stderr).lines().map_while(Result::ok) {                if let Some(report) = line.strip_prefix("[crash] ") {                    *lock(&c.crash) = serde_json::from_str(report).ok();                }                eprintln!("[plugins] {line}");            }        });        // Its stdout: answers to the waiting requests, and events.        let c = conn.clone();        let on_event = self.on_event.clone();        let on_gone = self.on_gone.clone();        let _ = std::thread::Builder::new().name("plugins-pipe".into()).spawn(move || {            let mut out = stdout;            while let Ok(Some(f)) = proto::read_frame(&mut out) {                match f.kind {                    KIND_RESPONSE => {                        let r = match serde_json::from_slice::<Reply>(&f.json) {                            Ok(Reply::Ok(v)) => Ok((v, f.bytes)),                            Ok(Reply::Err(e)) => Err(e),                            Err(e) => Err(format!("the plugin host answered nonsense: {e}")),                        };                        let waiting = lock(&c.pending).remove(&f.id);                        if let Some(w) = waiting {                            let _ = w.tx.send(r);                        } else if lock(&c.expired).remove(&f.id) == Some(true) {                            // An Open the page stopped waiting for finished after all: nobody has that instance.                            if let Some(inst) = r.ok().and_then(|(v, _)| v["inst"].as_u64()) {                                eprintln!("[plugins] an open that ran out of time finished late; closing its instance {inst}");                                let id = c.next_id.fetch_add(1, Ordering::Relaxed);                                let frame = Frame::new(KIND_REQUEST, id, &Request::Close { inst: inst as u32 }, Vec::new());                                let _ = proto::write_frame(&mut *lock(&c.stdin), &frame);                            }                        }                    }                    KIND_EVENT => match serde_json::from_slice::<Event>(&f.json) {                        Ok(Event::Heartbeat { stuck, editors }) => {                            *lock(&c.beat) = Instant::now();                            c.editors.store(editors, Ordering::Relaxed);                            let mut since = lock(&c.stuck_since);                            if stuck.is_empty() {                                *since = None;                            } else {                                since.get_or_insert_with(Instant::now);                            }                            *lock(&c.stuck) = stuck;                        }                        Ok(ev) => on_event(c.generation, ev),                        Err(_) => {}                    },                    _ => {}                }            }            // The pipe closed: the host is gone, by its own crash or our kill.            finish(&c, &on_gone);        });        // The watchdog. It also notices the process ending while its pipe stays open (a helper process a plugin        // started can keep a copy of it).        let c = conn.clone();        let on_gone = self.on_gone.clone();        let _ = std::thread::Builder::new().name("plugins-watchdog".into()).spawn(move || loop {            std::thread::sleep(Duration::from_millis(250));            if !c.alive() {                return;            }            if matches!(lock(&c.child).try_wait(), Ok(Some(_))) {                std::thread::sleep(Duration::from_millis(300));                finish(&c, &on_gone);                return;            }            let now = Instant::now();            let quiet = now.duration_since(*lock(&c.beat));            let stuck = lock(&c.stuck_since).is_some_and(|t| now.duration_since(t) > STUCK);            // Requests past their time: failed back to their pages while the host is alive (a plugin's dialog waiting            // for the user, say: killing the host would take the dialog and every instance with it); a hang otherwise.            let overdue: Vec<u32> = lock(&c.pending).iter().filter(|(_, w)| now > w.deadline).map(|(id, _)| *id).collect();            let mut hung_request = false;            if !overdue.is_empty() {                if quiet < FRESH {                    let mut pending = lock(&c.pending);                    for id in overdue {                        if let Some(w) = pending.remove(&id) {                            eprintln!("[plugins] request {id} ran out of time while the plugin host is alive (a plugin's own window may be waiting); failing just that request");                            lock(&c.expired).insert(id, w.opens);                            let _ = w.tx.send(Err("the plugin didn't answer in time (it may be showing a window of its own)".into()));                        }                    }                } else {                    hung_request = true;                }            }            // Silence with nothing asked: the main thread stopped (hung in a plugin's window, say). While a request runs            // its main thread may be busy in the plugin for a while (a big module loading): its time limit decides, up to            // SILENCE_EDITOR_BUSY while an editor (sharing the app's input) is open.            let waiting = !lock(&c.pending).is_empty();            let editors = c.editors.load(Ordering::Relaxed) > 0;            let limit = if editors { SILENCE_EDITOR } else { SILENCE };            let silent = quiet > limit && (!waiting || (editors && quiet > SILENCE_EDITOR_BUSY));            if hung_request || silent || stuck {                eprintln!(                    "[plugins] the plugin host stopped responding ({}); ending it",                    if stuck { "a plugin is stuck in its audio" } else if hung_request { "a request ran out of time with no heartbeat" } else { "no heartbeat" }                );                c.kill("hung");                return;            }        });        // Hello, before anything else.        conn.request(&Request::Hello { version: proto::VERSION, roots: roots.to_vec(), owner }, Vec::new(), Duration::from_secs(10))?;        *slot = Some(conn.clone());        Ok(conn)    }    /// Notes a death; false when hosts have died three times in a minute (don't restart on our own).    pub fn may_restart(&self) -> bool {        let mut d = lock(&self.deaths);        d.push(Instant::now());        d.retain(|t| t.elapsed() < Duration::from_secs(60));        d.len() < 3    }    /// Ends the host, if one runs.    pub fn stop(&self, reason: &str) {        if let Some(c) = lock(&self.conn).take() {            c.kill(reason);        }    }}/// The real host process with the test plugin (built by build.rs in debug builds), driven the way the app drives it.#[cfg(all(test, debug_assertions))]mod tests {    use super::*;    use serde_json::json;    const GAIN: &str = "4A57544741494E50524F433100000001";    const CRASH: &str = "4A574352415348310000000000000003";    /// juicewrld-plugins.exe beside the test binary's folder (cargo test builds it for the integration tests).    fn exe() -> PathBuf {        let p = std::env::current_exe().unwrap().parent().unwrap().parent().unwrap().join("juicewrld-plugins.exe");        assert!(p.is_file(), "no {} (cargo test builds it)", p.display());        p    }    /// A folder of the test's own (under JW_TEST_DIR when set), with the test plugin in it as a bundle.    fn folder_with_plugin(name: &str) -> (PathBuf, String) {        let base = std::env::var_os("JW_TEST_DIR").map(PathBuf::from).unwrap_or_else(std::env::temp_dir);        let d = base.join(format!("jw-app-{name}-{}", std::process::id()));        let _ = std::fs::remove_dir_all(&d);        let bin = d.join("JW Test.vst3").join("Contents").join("x86_64-win");        std::fs::create_dir_all(&bin).unwrap();        std::fs::copy(env!("JW_TEST_PLUGIN"), bin.join("JW Test.vst3")).unwrap();        let module = d.join("JW Test.vst3").to_string_lossy().to_string();        (d, module)    }    fn host(gone: Arc<Mutex<Vec<Gone>>>) -> Host {        Host::new(exe(), Arc::new(|_, _| {}), Arc::new(move |g| lock(&gone).push(g)))    }    fn open(c: &Conn, module: &str, cid: &str) -> Result<Value, String> {        let req = Request::Open { module: module.into(), cid: cid.into(), rate: 48000.0, block: 128, offline: true };        c.request(&req, Vec::new(), Duration::from_secs(20)).map(|(v, _)| v)    }    /// A folder added (or ticked) while the host runs: the running host is told, and opens its plugins; unticked    /// again, it refuses them again. The same host throughout.    #[test]    fn a_running_host_hears_of_folders_added_since_it_started() {        let (a, _) = folder_with_plugin("roots-a");        let (b, in_b) = folder_with_plugin("roots-b");        let h = host(Arc::new(Mutex::new(Vec::new())));        let only_a = vec![a.to_string_lossy().to_string()];        let both = vec![a.to_string_lossy().to_string(), b.to_string_lossy().to_string()];        let c1 = h.connect(&only_a, 0).unwrap();        assert!(open(&c1, &in_b, GAIN).unwrap_err().contains("plugin folders"));        let c2 = h.connect(&both, 0).unwrap();        assert_eq!(c2.generation, c1.generation, "the same host, told again");        open(&c2, &in_b, GAIN).unwrap();        let c3 = h.connect(&only_a, 0).unwrap();        assert!(open(&c3, &in_b, GAIN).unwrap_err().contains("plugin folders"));        h.stop("stopped");        let _ = std::fs::remove_dir_all(&a);        let _ = std::fs::remove_dir_all(&b);    }    /// A request that runs out of time while the host is alive fails on its own (the host isn't killed for it: a    /// plugin's dialog may be waiting for the user); a plugin stuck in its audio call still ends the host, named.    #[test]    fn a_request_past_its_time_fails_alone_while_a_stuck_plugin_still_ends_the_host() {        let (d, module) = folder_with_plugin("overdue");        let gone = Arc::new(Mutex::new(Vec::new()));        let h = host(gone.clone());        let c = h.connect(&[d.to_string_lossy().to_string()], 0).unwrap();        let inst = open(&c, &module, CRASH).unwrap()["inst"].as_u64().unwrap() as u32;        // Hang: the crash test plugin's next process call (a parameter flush here, no audio flowing) never returns.        c.request(&Request::SetParam { inst, id: 1, value: 1.0 }, Vec::new(), Duration::from_secs(10)).unwrap();        let t0 = Instant::now();        let e = c.request(&Request::Render { inst, frames: 128 }, vec![0u8; 1024], Duration::from_millis(500)).unwrap_err();        assert!(e.contains("in time"), "{e}");        assert!(t0.elapsed() < Duration::from_secs(2), "{:?}", t0.elapsed());        assert!(c.alive(), "only that request failed");        c.request(&Request::Ping {}, Vec::new(), Duration::from_secs(5)).unwrap();        // The stuck audio call is a hang all the same: 1.5 s to be reported, 3 s more, and the host is ended.        while lock(&gone).is_empty() && t0.elapsed() < Duration::from_secs(12) {            std::thread::sleep(Duration::from_millis(50));        }        let g = lock(&gone).first().cloned().expect("the host should have been ended");        assert_eq!(g.reason, "hung");        assert_eq!(g.crash.unwrap()["inst"], json!(inst), "the culprit named");        let _ = std::fs::remove_dir_all(&d);    }    /// The page closing an instance whose audio call is stuck in its plugin (a reload while it hangs, say) ends the host    /// at once: the instance can't be torn down and would stay stuck whatever the page did next, so every page hears    /// which of its plugins went, as for any hang.    #[test]    fn closing_a_stuck_instance_ends_the_host() {        let (d, module) = folder_with_plugin("close-stuck");        let gone = Arc::new(Mutex::new(Vec::new()));        let h = host(gone.clone());        let c = h.connect(&[d.to_string_lossy().to_string()], 0).unwrap();        let inst = open(&c, &module, CRASH).unwrap()["inst"].as_u64().unwrap() as u32;        // Hang: the parameter flush that follows (no audio flowing) never returns.        c.request(&Request::SetParam { inst, id: 1, value: 1.0 }, Vec::new(), Duration::from_secs(10)).unwrap();        std::thread::sleep(Duration::from_millis(300));        let t0 = Instant::now();        let e = crate::plugins::close_on_host(&c, inst).unwrap_err();        assert!(e.contains("stuck"), "{e}");        while lock(&gone).is_empty() && t0.elapsed() < Duration::from_secs(5) {            std::thread::sleep(Duration::from_millis(20));        }        let g = lock(&gone).first().cloned().expect("the host should have been ended");        eprintln!("[close-stuck] {e}; the host was ended {} ms after the close, as {}", t0.elapsed().as_millis(), g.reason);        assert_eq!(g.reason, "hung");        assert!(t0.elapsed() < Duration::from_secs(4), "{:?}", t0.elapsed());        let _ = std::fs::remove_dir_all(&d);    }    /// An editor that never finishes opening (its plugin hung in attached(), the host's main thread with it) ends the    /// host at EDITOR_LIMIT: the longest a plugin window that hangs as it opens can hold up the app's input, which an    /// editor owned by the app's window shares (tests/host.rs measures that part).    #[test]    fn an_editor_that_never_opens_ends_the_host_at_its_limit() {        let (d, module) = folder_with_plugin("editor-hang");        let gone = Arc::new(Mutex::new(Vec::new()));        let h = host(gone.clone());        let c = h.connect(&[d.to_string_lossy().to_string()], 0).unwrap();        let inst = open(&c, &module, CRASH).unwrap()["inst"].as_u64().unwrap() as u32;        // The crash test plugin's "Hang editor": its view's attached() never returns.        c.request(&Request::SetParam { inst, id: 2, value: 1.0 }, Vec::new(), Duration::from_secs(10)).unwrap();        let t0 = Instant::now();        let req = Request::Editor { inst, show: true, title: "JW Test Crash (Insert 1)".into(), x: None, y: None };        let e = c.request(&req, Vec::new(), EDITOR_LIMIT).unwrap_err();        while lock(&gone).is_empty() && t0.elapsed() < EDITOR_LIMIT + Duration::from_secs(5) {            std::thread::sleep(Duration::from_millis(20));        }        let took = t0.elapsed();        eprintln!("[editor-hang] {e}; the host was ended {} ms after the editor was asked for", took.as_millis());        let g = lock(&gone).first().cloned().expect("the host should have been ended");        assert_eq!(g.reason, "hung");        assert!(took >= EDITOR_LIMIT && took < EDITOR_LIMIT + Duration::from_secs(2), "{took:?}");        let _ = std::fs::remove_dir_all(&d);    }    /// While an editor is open, a main thread that stops inside a request with a long limit (an open may take a minute)    /// is ended after SILENCE_EDITOR_BUSY, not at that limit: the editor's window shares the app's input.    #[test]    fn with_an_editor_open_a_host_silent_inside_a_long_request_is_ended_sooner() {        // Its editor opens without focus, behind every other window (debug builds).        std::env::set_var("JW_NO_FOCUS", "1");        let (d, module) = folder_with_plugin("editor-busy");        let gone = Arc::new(Mutex::new(Vec::new()));        let h = host(gone.clone());        let c = h.connect(&[d.to_string_lossy().to_string()], 0).unwrap();        let gain = open(&c, &module, GAIN).unwrap()["inst"].as_u64().unwrap() as u32;        let show = Request::Editor { inst: gain, show: true, title: "JW Test Gain (Insert 1)".into(), x: None, y: None };        c.request(&show, Vec::new(), EDITOR_LIMIT).unwrap();        let t = Instant::now();        while c.editors.load(Ordering::Relaxed) == 0 && t.elapsed() < Duration::from_secs(3) {            std::thread::sleep(Duration::from_millis(50));        }        assert_eq!(c.editors.load(Ordering::Relaxed), 1, "the heartbeat says an editor is open");        // A second plugin's editor hangs as it opens, asked for with a minute's limit.        let crash = open(&c, &module, CRASH).unwrap()["inst"].as_u64().unwrap() as u32;        c.request(&Request::SetParam { inst: crash, id: 2, value: 1.0 }, Vec::new(), Duration::from_secs(10)).unwrap();        let t0 = Instant::now();        let hang = Request::Editor { inst: crash, show: true, title: "JW Test Crash (Insert 2)".into(), x: None, y: None };        assert!(c.request(&hang, Vec::new(), Duration::from_secs(60)).is_err());        while lock(&gone).is_empty() && t0.elapsed() < Duration::from_secs(30) {            std::thread::sleep(Duration::from_millis(20));        }        let took = t0.elapsed();        eprintln!("[editor-busy] the host was ended {} ms after its main thread went silent with an editor open", took.as_millis());        assert_eq!(lock(&gone).first().map(|g| g.reason.clone()).as_deref(), Some("hung"));        // Counted from the last heartbeat, which came up to a quarter of a second before the request.        let early = SILENCE_EDITOR_BUSY - Duration::from_millis(500);        assert!(took >= early && took < SILENCE_EDITOR_BUSY + Duration::from_secs(2), "{took:?}");        let _ = std::fs::remove_dir_all(&d);    }}