Skip to main content

standard_plugin/
testing.rs

1//! Run a plugin under `cargo test`, against an in-process host.
2//!
3//! On targets other than wasm, every SDK call goes to the thread's
4//! [`MockHost`] instead of the WIT imports. The mock checks grants exactly
5//! as the viewer's host does (both use `standard-plugin-manifest`), keeps
6//! values, records what the plugin emitted and committed, and lays out
7//! surfaces. [`Harness`] drives a [`UiPlugin`] the way a viewer does:
8//! activate, resize, frames, events.
9//!
10//! ```rust,ignore
11#![doc = include_str!("../tests/testing_harness.rs")]
12//! ```
13
14mod http;
15mod machine;
16mod owned;
17
18pub(crate) use http::send as http_send;
19
20pub use machine::{MockPaneLaunch, MockProcess, MockWatch, MockWebSocket, ProcessScript};
21
22use alloc::collections::{BTreeMap, BTreeSet};
23use alloc::string::{String, ToString};
24use alloc::vec::Vec;
25use core::cell::RefCell;
26
27use standard_plugin_manifest::{GrantDenied, Grants};
28
29use crate::api::Target;
30use crate::api::account::{AccountState, Pane};
31use crate::api::capabilities::Capabilities;
32use crate::api::view::Theme;
33use crate::error::{Error, Result};
34use crate::geometry::{Geometry, Rect};
35use crate::surface::{HEADER_LEN, Model, RegionLayout};
36use crate::ui_runtime::{Event, Power, UiPlugin, UiRuntime};
37
38/// How a plugin made a call.
39#[derive(Clone, Copy, Debug, PartialEq, Eq)]
40pub enum CallKind {
41    /// `calls.call`: it waited for the answer.
42    Wait,
43    /// `calls.send`: nothing answers.
44    Send,
45    /// `calls.call-async` with this id; the answer is delivered by
46    /// [`Harness::answer_calls`].
47    Async(u64),
48}
49
50/// One call as the host saw it.
51#[derive(Clone, Debug, PartialEq, Eq)]
52pub struct MockCall {
53    pub method: String,
54    pub payload: String,
55    pub target: Target,
56    pub kind: CallKind,
57    pub timeout_ms: Option<u32>,
58    /// A `call-async` whose answer was delivered.
59    pub answered: bool,
60}
61
62/// One commit as the host saw it.
63#[derive(Clone, Debug, PartialEq, Eq)]
64pub struct MockCommit {
65    /// The header sequence number the region carried.
66    pub seq: u32,
67    pub slot: u8,
68    /// The rectangles the plugin sent.
69    pub dirty: Vec<Rect>,
70    /// The host treats it as fully dirty (the first after an attach).
71    pub full: bool,
72    pub geometry: Geometry,
73    pub model: Model,
74    /// The whole region (header and both slots) at commit time.
75    pub region: Vec<u8>,
76}
77
78impl MockCommit {
79    /// The committed slot's bytes.
80    pub fn slot_bytes(&self) -> &[u8] {
81        let layout = RegionLayout::new(self.model, self.geometry);
82        let start = (HEADER_LEN + u32::from(self.slot) * layout.slot_len) as usize;
83        &self.region[start..start + layout.slot_len as usize]
84    }
85}
86
87#[derive(Clone, Debug)]
88struct MockSurface {
89    model: Model,
90    geometry: Geometry,
91    /// Address and length of the attached region in this process.
92    region: Option<(usize, usize)>,
93    pending: Option<(usize, usize)>,
94    committed_once: bool,
95    commits: Vec<MockCommit>,
96}
97
98/// The in-process host. Build one, [`install`] it (or hand it to a
99/// [`Harness`]), and inspect it after the plugin ran.
100#[derive(Clone, Debug)]
101pub struct MockHost {
102    plugin_id: String,
103    granted: Vec<String>,
104    grants: Grants,
105    pub config: String,
106    pub values: BTreeMap<String, String>,
107    pub secrets: BTreeMap<String, String>,
108    pub account: AccountState,
109    pub driving: bool,
110    pub theme: Theme,
111    /// The viewer's reduce-motion setting (`view::reduced_motion`).
112    pub reduced_motion: bool,
113    pub capabilities: Capabilities,
114    pub focused_pane: Option<String>,
115    /// Claims another viewer holds: claiming these fails.
116    pub claimed_elsewhere: BTreeSet<String>,
117    /// Claims this instance holds.
118    pub claims: BTreeSet<String>,
119    /// `events.emit` calls: name, payload, target.
120    pub emitted: Vec<(String, String, Target)>,
121    /// `live.publish` calls: key, payload.
122    pub published: Vec<(String, String)>,
123    /// `live.delete` calls: the keys withdrawn, in order.
124    pub live_deleted: Vec<String>,
125    /// Patterns `events.on` registered.
126    pub listening: BTreeSet<String>,
127    /// `calls.call` and `call-async` answers by method (the companion's
128    /// side); a method without one answers `invalid`.
129    pub call_answers: BTreeMap<String, String>,
130    /// Every `calls.call`, `send` and `call-async`, in order.
131    pub calls: Vec<MockCall>,
132    /// Grants the plugin was denied, in order.
133    pub denials: Vec<String>,
134    pub panes: Vec<Pane>,
135    /// A frame the plugin asked for outside `frame()`
136    /// ([`crate::Context::request_frame`] or `wake_at`): the earliest
137    /// viewer instant, `0` for "the next frame".
138    pub frame_request: Option<u64>,
139    /// Surfaces `open` opened, in order.
140    pub opened: Vec<String>,
141    /// URLs `url::open` opened, in order.
142    pub opened_urls: Vec<String>,
143    /// Panes `focus_pane` asked the viewer to focus, in order.
144    pub focused_panes: Vec<String>,
145    /// Viewer creates: permanent id, project id, argv, title.
146    pub created_panes: Vec<(String, String, Vec<String>, String)>,
147    pub pane_create_error: Option<String>,
148    /// The viewer clock of the last `Harness::frame`, for the `url.open`
149    /// input window.
150    pub now_ms: u64,
151    /// When the last user input was delivered (`now_ms` then), until a URL
152    /// opened for it.
153    pub url_gesture_ms: Option<u64>,
154    /// Surfaces `close` closed, in order.
155    pub closed: Vec<String>,
156    /// Whether the plugin is handling a user gesture now (the harness sets
157    /// it around key, paste, pointer-press and command events).
158    pub gesture: bool,
159    pane_create_used: bool,
160    /// The machine the plugin runs on: a daemon's `Context::machine_id`, a
161    /// viewer's `view::machine_id`.
162    pub machine_id: Option<String>,
163    /// A daemon's `Context::account_id`.
164    pub account_id: Option<String>,
165    /// `daemon-context.lease-epoch`: a singleton's epoch, `None` for fleet
166    /// (`MockHost::singleton`).
167    pub lease_epoch: Option<u64>,
168    /// The build `daemon::Context::release` reports.
169    pub release: Option<crate::daemon::Release>,
170    /// A viewer's `view::instance_id`.
171    pub instance_id: String,
172    /// A daemon plugin's environment (`daemon::env`).
173    pub environment: Vec<(String, String)>,
174    /// `view::wall_ms`: milliseconds since the Unix epoch.
175    pub wall_ms: u64,
176    /// `view::utc_offset_minutes`.
177    pub utc_offset_minutes: i32,
178    /// `view::time_zone`.
179    pub time_zone: Option<String>,
180    /// The plugin's last `health::set`: its state and message.
181    pub health: Option<(crate::health::Health, String)>,
182    /// Identity tints by machine or project id (`view::surface_tint`,
183    /// `view::identity_tint`).
184    pub tints: BTreeMap<String, u32>,
185    /// Sizes the plugin asked for, by surface (`request_size`), bounded as
186    /// the host bounds them.
187    pub requested: BTreeMap<String, (u32, u32)>,
188    /// Labels the plugin set, by surface (`set_label`).
189    pub labels: BTreeMap<String, String>,
190    /// Carets the plugin set, by surface (`set_caret`): column and row.
191    pub carets: BTreeMap<String, (u32, u32)>,
192    /// Scrolling the plugin set, by surface (`set_scroll`).
193    pub scrolls: BTreeMap<String, crate::surface::Scroll>,
194    /// Rows the plugin asked to bring into view (`reveal`), in order:
195    /// surface, first row, last row.
196    pub reveals: Vec<(String, u32, u32)>,
197    /// What each scrolling surface shows (`viewport`), as a test sets it.
198    pub viewports: BTreeMap<String, crate::surface::Viewport>,
199    pub copied_text: Vec<String>,
200    /// Agent pointers the plugin set, by surface (`set_agent_pointer`),
201    /// with the presses each played.
202    pub agent_pointers: BTreeMap<String, (crate::surface::AgentPointer, u32)>,
203    /// Surfaces hosting an embedded program (`bind_embed`).
204    pub embed_bindings: BTreeSet<String>,
205    /// Instances the plugin opened (`open_instance`), with the pane each
206    /// opens after.
207    pub instances: BTreeMap<String, Option<String>>,
208    /// Pixel sizes the plugin asked for (`request_size_px`).
209    pub requested_px: BTreeMap<String, (u32, u32)>,
210    /// The loopback proxy port `view::loopback_proxy` answers, by machine.
211    pub loopback_proxies: BTreeMap<String, u16>,
212    /// The `window` surfaces shown docked (`view::surface_docked`).
213    pub docked: BTreeSet<String>,
214    /// Declared surfaces instanced per machine (`machine.after`).
215    machine_surfaces: BTreeSet<String>,
216    /// Declared surfaces instanced per project (`project.after`).
217    project_surfaces: BTreeSet<String>,
218    surfaces: BTreeMap<String, MockSurface>,
219    /// Children and watches (the daemon world).
220    machine: machine::Machine,
221    /// Scripted `daemon::http` (`MockHost::http`).
222    http: http::MockHttp,
223}
224
225impl MockHost {
226    /// A host for plugin `plugin_id` with no grants, not driving.
227    pub fn new(plugin_id: &str) -> Self {
228        Self {
229            plugin_id: plugin_id.to_string(),
230            granted: Vec::new(),
231            grants: Grants::new(plugin_id, []),
232            config: String::new(),
233            values: BTreeMap::new(),
234            secrets: BTreeMap::new(),
235            account: AccountState::default(),
236            driving: false,
237            theme: Theme::default(),
238            reduced_motion: false,
239            capabilities: Capabilities {
240                graphics: false,
241                kitty: false,
242                frame_rate: 60,
243                cell_px: (0, 0),
244                pixel_scale: 1,
245            },
246            focused_pane: None,
247            claimed_elsewhere: BTreeSet::new(),
248            claims: BTreeSet::new(),
249            emitted: Vec::new(),
250            published: Vec::new(),
251            live_deleted: Vec::new(),
252            listening: BTreeSet::new(),
253            call_answers: BTreeMap::new(),
254            calls: Vec::new(),
255            denials: Vec::new(),
256            panes: Vec::new(),
257            frame_request: None,
258            opened: Vec::new(),
259            focused_panes: Vec::new(),
260            created_panes: Vec::new(),
261            pane_create_error: None,
262            opened_urls: Vec::new(),
263            now_ms: 0,
264            url_gesture_ms: None,
265            closed: Vec::new(),
266            gesture: false,
267            pane_create_used: false,
268            machine_id: None,
269            account_id: None,
270            lease_epoch: None,
271            release: None,
272            instance_id: "test-viewer".to_string(),
273            environment: Vec::new(),
274            wall_ms: 0,
275            utc_offset_minutes: 0,
276            time_zone: None,
277            health: None,
278            tints: BTreeMap::new(),
279            requested: BTreeMap::new(),
280            labels: BTreeMap::new(),
281            carets: BTreeMap::new(),
282            scrolls: BTreeMap::new(),
283            reveals: Vec::new(),
284            viewports: BTreeMap::new(),
285            copied_text: Vec::new(),
286            agent_pointers: BTreeMap::new(),
287            embed_bindings: BTreeSet::new(),
288            instances: BTreeMap::new(),
289            requested_px: BTreeMap::new(),
290            loopback_proxies: BTreeMap::new(),
291            docked: BTreeSet::new(),
292            machine_surfaces: BTreeSet::new(),
293            project_surfaces: BTreeSet::new(),
294            surfaces: BTreeMap::new(),
295            machine: machine::Machine::default(),
296            http: http::MockHttp::default(),
297        }
298    }
299
300    /// The viewer's wall clock and time zone.
301    pub fn clock(mut self, wall_ms: u64, utc_offset_minutes: i32, time_zone: Option<&str>) -> Self {
302        self.wall_ms = wall_ms;
303        self.utc_offset_minutes = utc_offset_minutes;
304        self.time_zone = time_zone.map(str::to_string);
305        self
306    }
307
308    /// Runs a daemon plugin as a singleton under lease `epoch`.
309    pub fn singleton(mut self, epoch: u64) -> Self {
310        self.lease_epoch = Some(epoch);
311        self
312    }
313
314    /// The machine the plugin runs on.
315    pub fn machine(mut self, machine_id: &str) -> Self {
316        self.machine_id = Some(machine_id.to_string());
317        self
318    }
319
320    /// Sets one variable of a daemon plugin's environment.
321    pub fn env(mut self, name: &str, value: &str) -> Self {
322        self.environment.retain(|(key, _)| key != name);
323        self.environment.push((name.to_string(), value.to_string()));
324        self.environment.sort();
325        self
326    }
327
328    /// Adds grants (the manifest's grant keys).
329    pub fn grant(mut self, grants: &[&str]) -> Self {
330        self.granted
331            .extend(grants.iter().map(|grant| grant.to_string()));
332        self.grants = Grants::new(&self.plugin_id, self.granted.iter().cloned());
333        self
334    }
335
336    /// Declares a surface the way a manifest does, with no size yet.
337    pub fn surface(mut self, id: &str, model: Model) -> Self {
338        self.surfaces.insert(
339            id.to_string(),
340            MockSurface {
341                model,
342                geometry: Geometry::default(),
343                region: None,
344                pending: None,
345                committed_once: false,
346                commits: Vec::new(),
347            },
348        );
349        self
350    }
351
352    /// Declares a `machine.after` surface: its instances are
353    /// `<surface>@<machine>`.
354    pub fn machine_surface(mut self, id: &str, model: Model) -> Self {
355        self.machine_surfaces.insert(id.to_string());
356        self.surface(id, model)
357    }
358
359    /// Declares a `project.after` surface: its instances are
360    /// `<surface>@<project>`.
361    pub fn project_surface(mut self, id: &str, model: Model) -> Self {
362        self.project_surfaces.insert(id.to_string());
363        self.surface(id, model)
364    }
365
366    pub fn driving(mut self, driving: bool) -> Self {
367        self.driving = driving;
368        self
369    }
370
371    /// Sets a surface's size, as the viewer's layout does. Returns the
372    /// resize event to deliver (the [`Harness`] delivers it).
373    pub fn set_geometry(&mut self, id: &str, geometry: Geometry) -> Option<Event> {
374        if !self.surfaces.contains_key(id)
375            && let Some((base, _pane)) = id.split_once('@')
376            && let Some(template) = self.surfaces.get(base)
377        {
378            // A pane instance of a declared footer or header surface.
379            let mut instance = template.clone();
380            instance.geometry = Geometry::default();
381            instance.region = None;
382            instance.pending = None;
383            instance.committed_once = false;
384            instance.commits.clear();
385            self.surfaces.insert(id.to_string(), instance);
386        }
387        let surface = self.surfaces.get_mut(id)?;
388        if surface.geometry == geometry {
389            return None;
390        }
391        surface.geometry = geometry;
392        Some(Event::Resize {
393            surface: id.to_string(),
394            geometry,
395        })
396    }
397
398    /// Whether the plugin has a region attached to surface `id`.
399    pub fn attached(&self, id: &str) -> bool {
400        self.surfaces
401            .get(id)
402            .is_some_and(|surface| surface.region.is_some())
403    }
404
405    /// Switches the model the viewer uses for a surface that lists
406    /// several: the plugin sees it as a resize.
407    pub fn set_model(&mut self, id: &str, model: Model) -> Option<Event> {
408        let surface = self.surfaces.get_mut(id)?;
409        if surface.model == model {
410            return None;
411        }
412        surface.model = model;
413        surface.region = None;
414        surface.pending = None;
415        surface.committed_once = false;
416        Some(Event::Resize {
417            surface: id.to_string(),
418            geometry: surface.geometry,
419        })
420    }
421
422    /// Every commit of a surface, oldest first.
423    pub fn commits(&self, id: &str) -> Vec<MockCommit> {
424        self.surfaces
425            .get(id)
426            .map(|surface| surface.commits.clone())
427            .unwrap_or_default()
428    }
429
430    /// The companion's answer to `method`, as a call gets it.
431    fn answer(&self, method: &str) -> Result<String> {
432        self.call_answers
433            .get(method)
434            .cloned()
435            .ok_or_else(|| Error::Invalid(alloc::format!("unknown method {method:?}")))
436    }
437
438    /// The `call-async`s not answered yet, marked answered, each with the
439    /// event that answers it.
440    fn take_async_answers(&mut self) -> Vec<Event> {
441        let mut events = Vec::new();
442        for index in 0..self.calls.len() {
443            let CallKind::Async(id) = self.calls[index].kind else {
444                continue;
445            };
446            if self.calls[index].answered {
447                continue;
448            }
449            self.calls[index].answered = true;
450            let result = self.answer(&self.calls[index].method).map(crate::Json);
451            events.push(Event::CallResult {
452                id: crate::api::calls::CallId(id),
453                result,
454            });
455        }
456        events
457    }
458
459    fn deny(&mut self, denial: GrantDenied) -> Error {
460        self.denials.push(denial.grant.clone());
461        Error::GrantDenied {
462            grant: denial.grant,
463        }
464    }
465
466    fn check(&mut self, grant: &str) -> Result<()> {
467        self.grants.check(grant).map_err(|denial| self.deny(denial))
468    }
469
470    fn check_namespaced(&mut self, kind: &str, subject: &str) -> Result<()> {
471        self.grants
472            .check_namespaced(kind, subject)
473            .map_err(|denial| self.deny(denial))
474    }
475}
476
477std::thread_local! {
478    static MOCK: RefCell<Option<MockHost>> = const { RefCell::new(None) };
479}
480
481/// Makes `host` this thread's host. A thread without one gets
482/// `MockHost::new("test-plugin")` on its first call.
483pub fn install(host: MockHost) {
484    MOCK.with(|mock| *mock.borrow_mut() = Some(host));
485}
486
487/// Runs `f` on this thread's host.
488pub fn with_host<R>(f: impl FnOnce(&mut MockHost) -> R) -> R {
489    MOCK.with(|mock| {
490        let mut mock = mock.borrow_mut();
491        f(mock.get_or_insert_with(|| MockHost::new("test-plugin")))
492    })
493}
494
495/// Drives a [`UiPlugin`] as a viewer does, on this thread's [`MockHost`].
496pub struct Harness<P: UiPlugin> {
497    runtime: UiRuntime<P>,
498}
499
500impl<P: UiPlugin> Harness<P> {
501    /// Installs `host` and activates the plugin with `config`.
502    pub fn activate(host: MockHost, config: &str) -> Self {
503        let mut host = host;
504        host.config = config.to_string();
505        install(host);
506        let runtime = UiRuntime::new();
507        runtime.activate(config.to_string());
508        Self { runtime }
509    }
510
511    /// Lays a surface out at `geometry` and delivers the resize event.
512    pub fn resize(&mut self, surface: &str, geometry: Geometry) {
513        if let Some(event) = with_host(|host| host.set_geometry(surface, geometry)) {
514            self.runtime.event(event);
515        }
516    }
517
518    /// Calls `frame` with the paced interval and power state a viewer
519    /// passes; returns when the plugin wants the next one.
520    pub fn frame(&mut self, now_ms: u64, interval_ms: u32, power: Power) -> Option<u64> {
521        with_host(|host| {
522            host.frame_request = None;
523            host.now_ms = now_ms;
524        });
525        self.runtime.frame(now_ms, interval_ms, power)
526    }
527
528    pub fn event(&mut self, event: Event) {
529        let gesture = matches!(
530            &event,
531            Event::Key(_)
532                | Event::Paste { .. }
533                | Event::Command(_)
534                | Event::Pointer(crate::Pointer {
535                    kind: crate::PointerKind::Down,
536                    ..
537                })
538        ) || crate::links::Link::from_event(&event).is_some();
539        with_host(|host| {
540            host.gesture = gesture;
541            host.pane_create_used = false;
542            if gesture {
543                host.url_gesture_ms = Some(host.now_ms);
544            }
545        });
546        self.runtime.event(event);
547        with_host(|host| host.gesture = false);
548    }
549
550    /// Shows or hides a surface, as the viewer does when it places it.
551    pub fn show(&mut self, surface: &str, visible: bool) {
552        self.event(Event::Visibility {
553            surface: surface.to_string(),
554            visible,
555        });
556    }
557
558    /// Changes what the viewer can show and tells the plugin.
559    pub fn set_capabilities(&mut self, capabilities: Capabilities) {
560        with_host(|host| host.capabilities = capabilities);
561        self.event(Event::CapabilitiesChanged);
562    }
563
564    /// Changes the theme and tells the plugin.
565    pub fn set_theme(&mut self, theme: Theme) {
566        with_host(|host| host.theme = theme);
567        self.event(Event::ThemeChanged);
568    }
569
570    /// Turns the viewer's reduce-motion setting on or off and tells the
571    /// plugin, as the viewer does (`Event::ThemeChanged`).
572    pub fn set_reduced_motion(&mut self, reduced: bool) {
573        with_host(|host| host.reduced_motion = reduced);
574        self.event(Event::ThemeChanged);
575    }
576
577    /// Switches a multi-model surface to `model`, as the viewer does when
578    /// its graphics support changes.
579    pub fn set_model(&mut self, surface: &str, model: Model) {
580        if let Some(event) = with_host(|host| host.set_model(surface, model)) {
581            self.runtime.event(event);
582        }
583    }
584
585    /// A key press on `surface`.
586    pub fn key(&mut self, surface: &str, code: crate::KeyCode) {
587        self.event(Event::Key(crate::Key::press(surface, code)));
588    }
589
590    /// Text pasted into `surface`.
591    pub fn paste(&mut self, surface: &str, text: &str) {
592        self.event(Event::Paste {
593            surface: surface.to_string(),
594            text: text.to_string(),
595        });
596    }
597
598    /// A pointer event at `(x, y)` in the surface's units.
599    pub fn pointer(&mut self, surface: &str, kind: crate::PointerKind, x: u32, y: u32) {
600        let cell = with_host(|host| {
601            host.surfaces
602                .get(surface)
603                .map_or((1, 1), |surface| match surface.model {
604                    Model::Cells => (1, 1),
605                    Model::Pixels => (
606                        surface.geometry.cell_px_w.max(1),
607                        surface.geometry.cell_px_h.max(1),
608                    ),
609                })
610        });
611        self.event(Event::Pointer(crate::Pointer {
612            surface: surface.to_string(),
613            x,
614            y,
615            col: x / cell.0,
616            row: y / cell.1,
617            button: if matches!(kind, crate::PointerKind::Move) {
618                crate::Button::None
619            } else {
620                crate::Button::Left
621            },
622            kind,
623            modifiers: crate::Modifiers::NONE,
624        }));
625    }
626
627    /// A link clicked in a pane, as a plugin with `links.handle` hears it.
628    pub fn link(&mut self, url: &str, pane: Option<&str>, machine: Option<&str>) {
629        let payload = serde_json::json!({ "url": url, "pane": pane, "machine": machine });
630        self.event(Event::Plugin {
631            name: crate::links::OPEN_EVENT.into(),
632            payload: crate::Json(payload.to_string()),
633        });
634    }
635
636    /// Runs one of the manifest's commands.
637    pub fn command(&mut self, id: &str) {
638        self.event(Event::Command(id.to_string()));
639    }
640
641    /// Answers every `call-async` the plugin made so far from
642    /// [`MockHost::call_answers`], delivering one
643    /// [`Event::CallResult`] each, in order. Returns how many.
644    pub fn answer_calls(&mut self) -> usize {
645        let events = with_host(MockHost::take_async_answers);
646        let count = events.len();
647        for event in events {
648            self.event(event);
649        }
650        count
651    }
652
653    /// The frame the plugin asked for from an event, and clears it.
654    pub fn take_frame_request(&mut self) -> Option<u64> {
655        with_host(|host| host.frame_request.take())
656    }
657
658    /// The plugin, to assert on its state.
659    pub fn plugin<R>(&self, f: impl FnOnce(&mut P) -> R) -> R {
660        self.runtime
661            .with_plugin(f)
662            .unwrap_or_else(|| panic!("the plugin is not active"))
663    }
664
665    pub fn commits(&self, surface: &str) -> Vec<MockCommit> {
666        with_host(|host| host.commits(surface))
667    }
668
669    pub fn host<R>(&self, f: impl FnOnce(&mut MockHost) -> R) -> R {
670        with_host(f)
671    }
672
673    pub fn deactivate(self) {
674        self.runtime.deactivate();
675    }
676}
677
678/// Drives a [`DaemonPlugin`](crate::daemon::DaemonPlugin) as `standardd`
679/// would: activate, `drive` at the instants it asks for, events and calls.
680pub struct DaemonHarness<P: crate::daemon::DaemonPlugin> {
681    runtime: crate::daemon::runtime::DaemonRuntime<P>,
682}
683
684impl<P: crate::daemon::DaemonPlugin> DaemonHarness<P> {
685    /// Installs `host` and activates the plugin with `config`.
686    pub fn activate(host: MockHost, config: &str) -> Self {
687        let mut host = host;
688        host.config = config.to_string();
689        install(host);
690        let runtime = crate::daemon::runtime::DaemonRuntime::new();
691        runtime.activate(config.to_string());
692        Self { runtime }
693    }
694
695    /// Delivers what happened on the machine since the last drive (a
696    /// scripted child's output and exit, file changes), then runs the
697    /// plugin's tasks at `now_ms`; when it next wants to run.
698    pub fn drive(&mut self, now_ms: u64) -> Option<u64> {
699        loop {
700            let pending = with_host(|host| host.machine.pending.pop_front());
701            let Some(event) = pending else {
702                break;
703            };
704            self.runtime.event(event);
705        }
706        self.runtime.drive(now_ms)
707    }
708
709    /// Output of a running child, as its piped stream carries it; delivered
710    /// on the next [`DaemonHarness::drive`].
711    pub fn output(&mut self, pid: u32, stderr: bool, bytes: &[u8]) {
712        with_host(|host| host.output(pid, stderr, bytes));
713    }
714
715    /// A running child exits with `status`; delivered on the next drive.
716    pub fn exit(&mut self, pid: u32, status: i32) {
717        with_host(|host| host.exited(pid, status));
718    }
719
720    /// Something changed at `path`: every watch that covers it, at its
721    /// depth and outside its exclude globs, hears it on the next drive.
722    /// How many watches hear it.
723    pub fn file_changed(&mut self, path: &str) -> usize {
724        with_host(|host| host.changed(path))
725    }
726
727    /// The plugin, to assert on its state.
728    pub fn plugin<R>(&self, f: impl FnOnce(&P) -> R) -> R {
729        self.runtime
730            .with_plugin(f)
731            .unwrap_or_else(|| panic!("the plugin is not active"))
732    }
733
734    /// Delivers an event (drive afterwards to let the plugin see it).
735    pub fn event(&mut self, event: Event) {
736        self.runtime.event(event);
737    }
738
739    /// The account's viewers now show exactly `surfaces` of the plugin, as
740    /// the host reports it (the [`INTEREST_EVENT`](crate::daemon::INTEREST_EVENT)
741    /// plugin event); the plugin hears
742    /// [`Event::Interest`](crate::Event::Interest) on the next drive when it
743    /// changed. `&[]`: nobody looks.
744    pub fn interest(&mut self, surfaces: &[&str]) {
745        let payload = serde_json::json!({ "surfaces": surfaces }).to_string();
746        self.runtime.event(Event::Plugin {
747            name: crate::daemon::INTEREST_EVENT.to_string(),
748            payload: crate::Json(payload),
749        });
750    }
751
752    /// Calls the plugin's `call` handler as its UI half would.
753    pub fn call(&mut self, method: &str, request: &str) -> Result<String> {
754        self.call_from(method, request, crate::daemon::Caller::default())
755    }
756
757    /// Calls the plugin's `call` handler as `caller`.
758    pub fn call_from(
759        &mut self,
760        method: &str,
761        request: &str,
762        caller: crate::daemon::Caller,
763    ) -> Result<String> {
764        self.runtime
765            .handle_call(method, request.to_string(), caller)
766    }
767
768    pub fn host<R>(&self, f: impl FnOnce(&mut MockHost) -> R) -> R {
769        with_host(f)
770    }
771
772    pub fn deactivate(self) {
773        self.runtime.deactivate();
774    }
775}
776
777/// The host calls, as `crate::host` names them.
778pub(crate) mod host_calls {
779    use super::*;
780
781    /// The account service's rule for a value or live key's name (after
782    /// `<namespace>.`): it starts with a letter, digit or `_`, then only
783    /// those, `.`, `:`, `/` and `-`. The mock refuses what the account
784    /// would, so a plugin's tests catch a key it could never write.
785    fn check_key_name(key: &str) -> Result<()> {
786        let name = key.split_once('.').map_or("", |(_, name)| name);
787        let allowed =
788            |c: char| c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | ':' | '/' | '-');
789        let first = name.chars().next();
790        if first.is_some_and(|c| c.is_ascii_alphanumeric() || c == '_') && name.chars().all(allowed)
791        {
792            Ok(())
793        } else {
794            Err(Error::Invalid(alloc::format!(
795                "{key:?}: a key is <namespace>.<name>, the name of letters, digits and _ . : / -"
796            )))
797        }
798    }
799
800    pub(crate) fn values_get(key: &str) -> Result<Option<String>> {
801        with_host(|host| {
802            host.check_namespaced("values.read", key)?;
803            Ok(host.values.get(key).cloned())
804        })
805    }
806
807    pub(crate) fn values_set(key: &str, value: &str) -> Result<()> {
808        with_host(|host| {
809            host.check_namespaced("values.write", key)?;
810            check_key_name(key)?;
811            host.values.insert(key.to_string(), value.to_string());
812            Ok(())
813        })
814    }
815
816    pub(crate) fn values_delete(key: &str) -> Result<()> {
817        with_host(|host| {
818            host.check_namespaced("values.write", key)?;
819            host.values.remove(key);
820            Ok(())
821        })
822    }
823
824    pub(crate) fn values_keys(prefix: &str) -> Result<Vec<String>> {
825        with_host(|host| {
826            host.check_namespaced("values.read", prefix)?;
827            Ok(host
828                .values
829                .keys()
830                .filter(|key| key.starts_with(prefix))
831                .cloned()
832                .collect())
833        })
834    }
835
836    pub(crate) fn values_watch(prefix: &str) -> Result<()> {
837        with_host(|host| host.check_namespaced("values.read", prefix))
838    }
839
840    pub(crate) fn live_publish(key: &str, payload: &str) -> Result<()> {
841        with_host(|host| {
842            host.check_namespaced("live.publish", key)?;
843            check_key_name(key)?;
844            host.published.push((key.to_string(), payload.to_string()));
845            Ok(())
846        })
847    }
848
849    pub(crate) fn live_delete(key: &str) -> Result<()> {
850        with_host(|host| {
851            host.check_namespaced("live.publish", key)?;
852            host.live_deleted.push(key.to_string());
853            Ok(())
854        })
855    }
856
857    pub(crate) fn live_subscribe(prefix: &str) -> Result<()> {
858        with_host(|host| host.check_namespaced("live.subscribe", prefix))
859    }
860
861    pub(crate) fn live_unsubscribe(prefix: &str) -> Result<()> {
862        with_host(|host| host.check_namespaced("live.subscribe", prefix))
863    }
864
865    pub(crate) fn events_emit(name: &str, payload: &str, to: &Target) -> Result<()> {
866        with_host(|host| {
867            if name.starts_with("system.") {
868                return Err(host.deny(GrantDenied {
869                    grant: alloc::format!("events.emit:{name}"),
870                }));
871            }
872            host.check_namespaced("events.emit", name)?;
873            host.emitted
874                .push((name.to_string(), payload.to_string(), to.clone()));
875            Ok(())
876        })
877    }
878
879    pub(crate) fn events_on(pattern: &str) -> Result<()> {
880        with_host(|host| {
881            host.check_namespaced("events.on", pattern)?;
882            host.listening.insert(pattern.to_string());
883            Ok(())
884        })
885    }
886
887    pub(crate) fn events_off(pattern: &str) -> Result<()> {
888        with_host(|host| {
889            host.check_namespaced("events.on", pattern)?;
890            host.listening.remove(pattern);
891            Ok(())
892        })
893    }
894
895    fn record_call(
896        host: &mut MockHost,
897        method: &str,
898        payload: &str,
899        to: &Target,
900        kind: CallKind,
901        timeout_ms: Option<u32>,
902    ) -> Result<()> {
903        let own = alloc::format!("call:{}", host.grants.plugin_id());
904        host.check(&own)?;
905        host.calls.push(MockCall {
906            method: method.to_string(),
907            payload: payload.to_string(),
908            target: to.clone(),
909            kind,
910            timeout_ms,
911            answered: false,
912        });
913        Ok(())
914    }
915
916    pub(crate) fn call(
917        method: &str,
918        payload: &str,
919        to: &Target,
920        timeout_ms: Option<u32>,
921    ) -> Result<String> {
922        with_host(|host| {
923            record_call(host, method, payload, to, CallKind::Wait, timeout_ms)?;
924            host.answer(method)
925        })
926    }
927
928    pub(crate) fn call_send(method: &str, payload: &str, to: &Target) -> Result<()> {
929        with_host(|host| record_call(host, method, payload, to, CallKind::Send, None))
930    }
931
932    pub(crate) fn call_async(
933        method: &str,
934        payload: &str,
935        to: &Target,
936        timeout_ms: Option<u32>,
937    ) -> Result<u64> {
938        with_host(|host| {
939            let id = host
940                .calls
941                .iter()
942                .filter(|call| matches!(call.kind, CallKind::Async(_)))
943                .count() as u64
944                + 1;
945            record_call(host, method, payload, to, CallKind::Async(id), timeout_ms)?;
946            Ok(id)
947        })
948    }
949
950    pub(crate) fn config() -> String {
951        with_host(|host| host.config.clone())
952    }
953
954    pub(crate) fn health_set(health: crate::health::Health, message: &str) {
955        with_host(|host| host.health = Some((health, message.to_string())));
956    }
957
958    pub(crate) fn secret(name: &str) -> Result<Option<String>> {
959        with_host(|host| {
960            host.check(&alloc::format!("secret:{name}"))?;
961            Ok(host.secrets.get(name).cloned())
962        })
963    }
964
965    pub(crate) fn account_state() -> Result<AccountState> {
966        with_host(|host| {
967            host.check("account.read")?;
968            Ok(host.account.clone())
969        })
970    }
971
972    pub(crate) fn account_watch() -> Result<()> {
973        with_host(|host| host.check("account.read"))
974    }
975
976    pub(crate) fn claim(key: &str, _ttl_ms: u32) -> Result<bool> {
977        with_host(|host| {
978            if host.claimed_elsewhere.contains(key) {
979                return Ok(false);
980            }
981            host.claims.insert(key.to_string());
982            Ok(true)
983        })
984    }
985
986    pub(crate) fn release(key: &str) -> Result<()> {
987        with_host(|host| {
988            host.claims.remove(key);
989            Ok(())
990        })
991    }
992
993    fn unknown(id: &str) -> Error {
994        Error::Invalid(alloc::format!("no surface {id:?} in the manifest"))
995    }
996
997    pub(crate) fn surface_layout(id: &str) -> Result<RegionLayout> {
998        with_host(|host| {
999            let surface = host.surfaces.get(id).ok_or_else(|| unknown(id))?;
1000            Ok(RegionLayout::new(surface.model, surface.geometry))
1001        })
1002    }
1003
1004    pub(crate) fn surface_attach(id: &str, region: &[u8]) -> Result<()> {
1005        with_host(|host| {
1006            let surface = host.surfaces.get_mut(id).ok_or_else(|| unknown(id))?;
1007            let layout = RegionLayout::new(surface.model, surface.geometry);
1008            if surface.geometry.is_empty() {
1009                return Err(Error::Invalid(alloc::format!(
1010                    "surface {id:?} has no size yet"
1011                )));
1012            }
1013            if region.len() < layout.len as usize {
1014                return Err(Error::Invalid("region too small".into()));
1015            }
1016            let word = |index: usize| {
1017                u32::from_le_bytes([
1018                    region[index * 4],
1019                    region[index * 4 + 1],
1020                    region[index * 4 + 2],
1021                    region[index * 4 + 3],
1022                ])
1023            };
1024            let g = surface.geometry;
1025            let expected = [
1026                match surface.model {
1027                    Model::Cells => 0,
1028                    Model::Pixels => 1,
1029                },
1030                g.cols,
1031                g.rows,
1032                g.px_w,
1033                g.px_h,
1034                g.cell_px_w,
1035                g.cell_px_h,
1036            ];
1037            if (1..8).any(|index| word(index) != expected[index - 1]) {
1038                return Err(Error::Invalid(
1039                    "region header does not describe the current layout".into(),
1040                ));
1041            }
1042            let bound = (region.as_ptr() as usize, region.len());
1043            if surface.region.is_none() {
1044                surface.region = Some(bound);
1045            } else {
1046                surface.pending = Some(bound);
1047            }
1048            Ok(())
1049        })
1050    }
1051
1052    pub(crate) fn surface_commit(id: &str, slot: u8, dirty: &[Rect]) -> Result<()> {
1053        with_host(|host| {
1054            let surface = host.surfaces.get_mut(id).ok_or_else(|| unknown(id))?;
1055            if surface.region.is_none() && surface.pending.is_none() {
1056                return Err(Error::Invalid(alloc::format!(
1057                    "surface {id:?} has no region attached"
1058                )));
1059            }
1060            if slot > 1 {
1061                return Err(Error::Invalid("slot must be 0 or 1".into()));
1062            }
1063            let full = surface.pending.is_some() || !surface.committed_once;
1064            if let Some(pending) = surface.pending.take() {
1065                surface.region = Some(pending);
1066            }
1067            let Some((address, len)) = surface.region else {
1068                return Err(Error::Invalid("no region".into()));
1069            };
1070            // SAFETY: the SDK keeps an attached region alive until the
1071            // first commit after its replacement, the same guarantee the
1072            // viewer's host relies on to read guest memory; this is that
1073            // commit's region, read while the plugin is inside the call.
1074            let bytes = unsafe { core::slice::from_raw_parts(address as *const u8, len) };
1075            let seq = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
1076            surface.committed_once = true;
1077            surface.commits.push(MockCommit {
1078                seq,
1079                slot,
1080                dirty: dirty.to_vec(),
1081                full,
1082                geometry: surface.geometry,
1083                model: surface.model,
1084                region: bytes.to_vec(),
1085            });
1086            Ok(())
1087        })
1088    }
1089
1090    pub(crate) fn surface_detach(id: &str) -> Result<()> {
1091        with_host(|host| {
1092            let surface = host.surfaces.get_mut(id).ok_or_else(|| unknown(id))?;
1093            surface.region = None;
1094            surface.pending = None;
1095            Ok(())
1096        })
1097    }
1098
1099    pub(crate) fn is_driving() -> bool {
1100        with_host(|host| host.driving)
1101    }
1102
1103    pub(crate) fn theme() -> Theme {
1104        with_host(|host| host.theme)
1105    }
1106
1107    pub(crate) fn reduced_motion() -> bool {
1108        with_host(|host| host.reduced_motion)
1109    }
1110
1111    pub(crate) fn capabilities() -> Capabilities {
1112        with_host(|host| host.capabilities)
1113    }
1114
1115    pub(crate) fn focused_pane() -> Option<String> {
1116        with_host(|host| host.focused_pane.clone())
1117    }
1118
1119    /// The template and owner of an instance id (`<surface>@<owner>`).
1120    fn instance(surface: &str) -> Option<(&str, &str)> {
1121        surface
1122            .split_once('@')
1123            .filter(|(_, owner)| !owner.is_empty())
1124    }
1125
1126    pub(crate) fn surface_machine(surface: &str) -> Option<String> {
1127        let (template, machine) = instance(surface)?;
1128        with_host(|host| host.machine_surfaces.contains(template)).then(|| machine.to_string())
1129    }
1130
1131    pub(crate) fn surface_project(surface: &str) -> Option<String> {
1132        let (template, project) = instance(surface)?;
1133        with_host(|host| host.project_surfaces.contains(template)).then(|| project.to_string())
1134    }
1135
1136    pub(crate) fn surface_docked(surface: &str) -> bool {
1137        with_host(|host| host.docked.contains(surface))
1138    }
1139
1140    pub(crate) fn surface_tint(surface: &str) -> Option<u32> {
1141        if let Some(owner) = surface_machine(surface).or_else(|| surface_project(surface)) {
1142            return with_host(|host| host.tints.get(&owner).copied());
1143        }
1144        let pane = surface_pane(surface)?;
1145        with_host(|host| {
1146            let pane = host
1147                .account
1148                .panes
1149                .iter()
1150                .find(|known| known.id == pane.id)?;
1151            pane.project
1152                .as_ref()
1153                .and_then(|project| host.tints.get(project))
1154                .or_else(|| host.tints.get(&pane.machine))
1155                .copied()
1156        })
1157    }
1158
1159    pub(crate) fn identity_tint(id: &str) -> Option<u32> {
1160        with_host(|host| host.tints.get(id).copied())
1161    }
1162
1163    pub(crate) fn surface_request_size(id: &str, cols: u32, rows: u32) -> Result<()> {
1164        with_host(|host| {
1165            let known = host.surfaces.contains_key(id)
1166                || instance(id).is_some_and(|(template, _)| host.surfaces.contains_key(template));
1167            if !known {
1168                return Err(unknown(id));
1169            }
1170            host.requested
1171                .insert(id.to_string(), (cols.min(1024), rows.min(512)));
1172            Ok(())
1173        })
1174    }
1175
1176    pub(crate) fn surface_set_label(id: &str, label: Option<&str>) -> Result<()> {
1177        with_host(|host| {
1178            let known = host.surfaces.contains_key(id)
1179                || instance(id).is_some_and(|(template, _)| host.surfaces.contains_key(template));
1180            if !known {
1181                return Err(unknown(id));
1182            }
1183            match label {
1184                Some(label)
1185                    if label.chars().count() > 48 || label.chars().any(char::is_control) =>
1186                {
1187                    return Err(crate::Error::Invalid(
1188                        "a label is at most 48 characters with no control characters".into(),
1189                    ));
1190                }
1191                Some(label) => {
1192                    host.labels.insert(id.to_string(), label.to_string());
1193                }
1194                None => {
1195                    host.labels.remove(id);
1196                }
1197            }
1198            Ok(())
1199        })
1200    }
1201
1202    pub(crate) fn surface_copy_text(id: &str, text: &str) -> Result<()> {
1203        with_host(|host| {
1204            let known = host.surfaces.contains_key(id)
1205                || instance(id).is_some_and(|(template, _)| host.surfaces.contains_key(template));
1206            if !known {
1207                return Err(unknown(id));
1208            }
1209            if !host.gesture {
1210                return Err(crate::Error::Invalid(
1211                    "Copying text needs a user gesture".into(),
1212                ));
1213            }
1214            standard_plugin_manifest::copy_text::validate(text).map_err(crate::Error::Invalid)?;
1215            if host.copied_text.len() >= standard_plugin_manifest::copy_text::MAX_PENDING {
1216                return Err(crate::Error::Unavailable(
1217                    "Too many copies are pending".into(),
1218                ));
1219            }
1220            host.copied_text.push(text.into());
1221            Ok(())
1222        })
1223    }
1224
1225    pub(crate) fn surface_set_caret(id: &str, caret: Option<(u32, u32)>) -> Result<()> {
1226        with_host(|host| {
1227            let known = host.surfaces.contains_key(id)
1228                || instance(id).is_some_and(|(template, _)| host.surfaces.contains_key(template));
1229            if !known {
1230                return Err(unknown(id));
1231            }
1232            match caret {
1233                Some(caret) => {
1234                    host.carets.insert(id.to_string(), caret);
1235                }
1236                None => {
1237                    host.carets.remove(id);
1238                }
1239            }
1240            Ok(())
1241        })
1242    }
1243
1244    pub(crate) fn surface_set_scroll(
1245        id: &str,
1246        scroll: Option<crate::surface::Scroll>,
1247    ) -> Result<()> {
1248        with_host(|host| {
1249            let known = host.surfaces.contains_key(id)
1250                || instance(id).is_some_and(|(template, _)| host.surfaces.contains_key(template));
1251            if !known {
1252                return Err(unknown(id));
1253            }
1254            match scroll {
1255                Some(scroll) => {
1256                    if scroll.rows > crate::surface::Scroll::MAX_ROWS {
1257                        return Err(crate::Error::Invalid(alloc::format!(
1258                            "a scrolling surface is at most {} rows",
1259                            crate::surface::Scroll::MAX_ROWS
1260                        )));
1261                    }
1262                    if scroll.fixed_top.saturating_add(scroll.fixed_bottom) >= scroll.rows {
1263                        return Err(crate::Error::Invalid(
1264                            "the fixed rows leave no rows to scroll".into(),
1265                        ));
1266                    }
1267                    host.scrolls.insert(id.to_string(), scroll);
1268                }
1269                None => {
1270                    host.scrolls.remove(id);
1271                    host.viewports.remove(id);
1272                }
1273            }
1274            Ok(())
1275        })
1276    }
1277
1278    pub(crate) fn surface_reveal(id: &str, first: u32, last: u32) -> Result<()> {
1279        with_host(|host| {
1280            if !host.scrolls.contains_key(id) {
1281                return Err(crate::Error::Invalid(alloc::format!(
1282                    "{id} does not scroll; call set_scroll first"
1283                )));
1284            }
1285            host.reveals.push((id.to_string(), first, last.max(first)));
1286            Ok(())
1287        })
1288    }
1289
1290    pub(crate) fn surface_viewport(id: &str) -> Result<Option<crate::surface::Viewport>> {
1291        with_host(|host| {
1292            let known = host.surfaces.contains_key(id)
1293                || instance(id).is_some_and(|(template, _)| host.surfaces.contains_key(template));
1294            if !known {
1295                return Err(unknown(id));
1296            }
1297            Ok(host
1298                .scrolls
1299                .contains_key(id)
1300                .then(|| host.viewports.get(id).copied())
1301                .flatten())
1302        })
1303    }
1304
1305    pub(crate) fn surface_set_agent_pointer(
1306        id: &str,
1307        pointer: Option<crate::surface::AgentPointer>,
1308    ) -> Result<()> {
1309        with_host(|host| {
1310            let known = host.surfaces.contains_key(id)
1311                || instance(id).is_some_and(|(template, _)| host.surfaces.contains_key(template));
1312            if !known {
1313                return Err(unknown(id));
1314            }
1315            match pointer {
1316                Some(pointer) => {
1317                    let presses = host
1318                        .agent_pointers
1319                        .get(id)
1320                        .map_or(0, |(_, presses)| *presses)
1321                        + u32::from(pointer.press);
1322                    host.agent_pointers
1323                        .insert(id.to_string(), (pointer, presses));
1324                }
1325                None => {
1326                    host.agent_pointers.remove(id);
1327                }
1328            }
1329            Ok(())
1330        })
1331    }
1332
1333    pub(crate) fn surface_pane(surface: &str) -> Option<crate::api::view::PaneRef> {
1334        let (template, pane) = instance(surface)?;
1335        if with_host(|host| {
1336            host.machine_surfaces.contains(template) || host.project_surfaces.contains(template)
1337        }) {
1338            return None;
1339        }
1340        let id = pane.to_string();
1341        let generation = with_host(|host| {
1342            host.account
1343                .panes
1344                .iter()
1345                .find(|pane| pane.id == id)
1346                .map_or(0, |pane| pane.generation)
1347        });
1348        Some(crate::api::view::PaneRef { id, generation })
1349    }
1350
1351    pub(crate) fn machine_id() -> Option<String> {
1352        with_host(|host| host.machine_id.clone())
1353    }
1354
1355    pub(crate) fn loopback_proxy(machine: &str) -> Result<u16> {
1356        with_host(|host| {
1357            host.check("link.loopback")?;
1358            host.loopback_proxies
1359                .get(machine)
1360                .copied()
1361                .ok_or_else(|| Error::Unavailable(alloc::format!("no proxy to {machine}")))
1362        })
1363    }
1364
1365    pub(crate) fn instance_id() -> String {
1366        with_host(|host| host.instance_id.clone())
1367    }
1368
1369    pub(crate) fn wall_ms() -> u64 {
1370        with_host(|host| host.wall_ms)
1371    }
1372
1373    pub(crate) fn utc_offset_minutes() -> i32 {
1374        with_host(|host| host.utc_offset_minutes)
1375    }
1376
1377    pub(crate) fn time_zone() -> Option<String> {
1378        with_host(|host| host.time_zone.clone())
1379    }
1380
1381    pub(crate) fn daemon_machine_id() -> String {
1382        with_host(|host| host.machine_id.clone().unwrap_or_default())
1383    }
1384
1385    pub(crate) fn daemon_account_id() -> Option<String> {
1386        with_host(|host| host.account_id.clone())
1387    }
1388
1389    pub(crate) fn daemon_lease_epoch() -> Option<u64> {
1390        with_host(|host| host.lease_epoch)
1391    }
1392
1393    pub(crate) fn daemon_release() -> Option<crate::daemon::Release> {
1394        with_host(|host| host.release.clone())
1395    }
1396
1397    pub(crate) fn daemon_environment() -> Vec<(String, String)> {
1398        with_host(|host| host.environment.clone())
1399    }
1400
1401    pub(crate) fn request_frame() {
1402        wake_at(0);
1403    }
1404
1405    pub(crate) fn wake_at(at_ms: u64) {
1406        with_host(|host| {
1407            host.frame_request = Some(host.frame_request.map_or(at_ms, |at| at.min(at_ms)));
1408        });
1409    }
1410
1411    pub(crate) fn url_open(url: &str) -> Result<()> {
1412        use standard_plugin_manifest::url::{URL_OPEN_WINDOW_MS, https_host};
1413        with_host(|host| {
1414            let domain = https_host(url).map_err(Error::Invalid)?;
1415            if !host.grants.allows_url_open(&domain) {
1416                return Err(host.deny(GrantDenied {
1417                    grant: alloc::format!("url.open:{domain}"),
1418                }));
1419            }
1420            let now = host.now_ms;
1421            if !host
1422                .url_gesture_ms
1423                .is_some_and(|at| host.gesture || now.saturating_sub(at) <= URL_OPEN_WINDOW_MS)
1424            {
1425                return Err(Error::Invalid(
1426                    "url.open needs user input within the last second".into(),
1427                ));
1428            }
1429            host.url_gesture_ms = None;
1430            host.opened_urls.push(url.to_string());
1431            Ok(())
1432        })
1433    }
1434
1435    pub(crate) fn surface_open(id: &str) -> Result<()> {
1436        with_host(|host| {
1437            if !host.surfaces.contains_key(id) {
1438                return Err(unknown(id));
1439            }
1440            if !host.gesture {
1441                return Err(Error::Invalid(
1442                    "surface.open needs a user gesture or a command".into(),
1443                ));
1444            }
1445            host.opened.push(id.to_string());
1446            Ok(())
1447        })
1448    }
1449
1450    pub(crate) fn create_pane(project: &str, argv: &[String], title: &str) -> Result<String> {
1451        with_host(|host| {
1452            host.check("view.pane-create")?;
1453            if !host.gesture {
1454                return Err(Error::Invalid("Pane creation needs a user gesture".into()));
1455            }
1456            if !host.driving {
1457                return Err(Error::Unavailable(
1458                    "Take control in this viewer to open a pane".into(),
1459                ));
1460            }
1461            if let Some(error) = &host.pane_create_error {
1462                return Err(Error::Unavailable(error.clone()));
1463            }
1464            if host.pane_create_used {
1465                return Err(Error::RateLimited);
1466            }
1467            let pane = alloc::format!("viewer-pane-{}", host.created_panes.len() + 1);
1468            standard_plugin_manifest::pane_create::PaneCreate {
1469                pane: pane.clone(),
1470                project: project.into(),
1471                argv: argv.to_vec(),
1472                title: title.into(),
1473            }
1474            .validate()
1475            .map_err(Error::Invalid)?;
1476            host.pane_create_used = true;
1477            host.created_panes
1478                .push((pane.clone(), project.into(), argv.to_vec(), title.into()));
1479            Ok(pane)
1480        })
1481    }
1482
1483    pub(crate) fn focus_pane(pane: &str) -> Result<()> {
1484        with_host(|host| {
1485            if !host.gesture {
1486                return Err(Error::Invalid(
1487                    "view.focus-pane needs a user gesture or a command".into(),
1488                ));
1489            }
1490            host.focused_panes.push(pane.to_string());
1491            Ok(())
1492        })
1493    }
1494
1495    pub(crate) fn surface_close(id: &str) -> Result<()> {
1496        with_host(|host| {
1497            host.closed.push(id.to_string());
1498            Ok(())
1499        })
1500    }
1501
1502    pub(crate) fn process_spawn(program: &str, args: &[String], cwd: Option<&str>) -> Result<u32> {
1503        let mut command = crate::daemon::process::Command::new(program);
1504        command.args = args.to_vec();
1505        command.cwd = cwd.map(ToString::to_string);
1506        with_host(|host| host.spawn(&command))
1507    }
1508
1509    pub(crate) fn process_run(command: &crate::daemon::process::Command) -> Result<u32> {
1510        with_host(|host| host.spawn(command))
1511    }
1512
1513    pub(crate) fn process_write(pid: u32, bytes: &[u8]) -> Result<()> {
1514        with_host(|host| host.write(pid, bytes))
1515    }
1516
1517    pub(crate) fn process_run_with_channel(
1518        command: &crate::daemon::process::Command,
1519    ) -> Result<u32> {
1520        with_host(|host| host.spawn_with_channel(command))
1521    }
1522
1523    pub(crate) fn process_send(pid: u32, message: &str) -> Result<()> {
1524        with_host(|host| host.send(pid, message))
1525    }
1526
1527    pub(crate) fn surface_open_instance(
1528        id: &str,
1529        key: &str,
1530        after: Option<&str>,
1531    ) -> Result<String> {
1532        with_host(|host| {
1533            if !host.surfaces.contains_key(id) {
1534                return Err(unknown(id));
1535            }
1536            let unprompted = after.is_some() && host.grants.allows("surface.open-unprompted");
1537            if !host.gesture && !unprompted {
1538                return Err(Error::Invalid(
1539                    "surface.open-instance needs a user gesture, or surface.open-unprompted and a pane".into(),
1540                ));
1541            }
1542            let instance = alloc::format!("{id}@{key}");
1543            host.instances
1544                .insert(instance.clone(), after.map(ToString::to_string));
1545            host.opened.push(instance.clone());
1546            Ok(instance)
1547        })
1548    }
1549
1550    pub(crate) fn surface_request_size_px(id: &str, width: u32, height: u32) -> Result<()> {
1551        with_host(|host| {
1552            host.requested_px.insert(id.to_string(), (width, height));
1553            Ok(())
1554        })
1555    }
1556
1557    pub(crate) fn surface_bind_embed(id: &str, bind: bool) -> Result<()> {
1558        with_host(|host| {
1559            let known = host.surfaces.contains_key(id) || host.instances.contains_key(id);
1560            if !known {
1561                return Err(unknown(id));
1562            }
1563            if bind {
1564                host.embed_bindings.insert(id.to_string());
1565            } else {
1566                host.embed_bindings.remove(id);
1567            }
1568            Ok(())
1569        })
1570    }
1571
1572    pub(crate) fn process_close_stdin(pid: u32) -> Result<()> {
1573        with_host(|host| host.close_stdin(pid))
1574    }
1575
1576    pub(crate) fn process_try_wait(pid: u32) -> Result<Option<i32>> {
1577        with_host(|host| host.try_wait(pid))
1578    }
1579
1580    pub(crate) fn process_wait(pid: u32) -> Result<i32> {
1581        with_host(|host| host.wait(pid))
1582    }
1583
1584    pub(crate) fn process_wait_timeout(pid: u32, _timeout_ms: u32) -> Result<Option<i32>> {
1585        with_host(|host| host.wait_timeout(pid))
1586    }
1587
1588    pub(crate) fn process_kill(pid: u32) -> Result<()> {
1589        with_host(|host| host.kill(pid))
1590    }
1591
1592    pub(crate) fn watch(path: &str, options: &crate::daemon::watch::Options) -> Result<u32> {
1593        with_host(|host| host.watch(path, options.recursive, &options.exclude))
1594    }
1595
1596    pub(crate) fn unwatch(handle: u32) -> Result<()> {
1597        with_host(|host| host.unwatch(handle))
1598    }
1599
1600    pub(crate) fn websocket_open(url: &str, headers: &[(String, String)]) -> Result<u32> {
1601        with_host(|host| host.websocket_open(url, headers))
1602    }
1603
1604    pub(crate) fn websocket_send(socket: u32, text: &str) -> Result<()> {
1605        with_host(|host| host.websocket_send(socket, text))
1606    }
1607
1608    pub(crate) fn websocket_close(socket: u32) {
1609        with_host(|host| host.websocket_close(socket));
1610    }
1611
1612    pub(crate) fn panes() -> Result<Vec<Pane>> {
1613        with_host(|host| {
1614            host.check("panes.read")?;
1615            Ok(host.panes.clone())
1616        })
1617    }
1618
1619    pub(crate) fn pane_create(
1620        cwd: &str,
1621        command: Option<&str>,
1622        env: &[(String, String)],
1623    ) -> Result<(String, u64)> {
1624        with_host(|host| {
1625            host.check("panes.write")?;
1626            host.create_pane(cwd, command, env, None, false)
1627        })
1628    }
1629
1630    pub(crate) fn pane_create_with(
1631        cwd: &str,
1632        command: Option<&str>,
1633        env: &[(String, String)],
1634        title: Option<&str>,
1635    ) -> Result<(String, u64)> {
1636        with_host(|host| {
1637            host.check("panes.write")?;
1638            host.create_pane(cwd, command, env, title, false)
1639        })
1640    }
1641
1642    pub(crate) fn pane_input(pane: &str, bytes: &[u8]) -> Result<()> {
1643        with_host(|host| host.pane_input(pane, bytes))
1644    }
1645
1646    pub(crate) fn pane_close(pane: &str) -> Result<()> {
1647        with_host(|host| host.pane_close(pane))
1648    }
1649
1650    pub(crate) fn panes_subscribe(on: bool) -> Result<()> {
1651        with_host(|host| {
1652            host.check_pane_reads()?;
1653            host.machine.panes_subscribed = on;
1654            Ok(())
1655        })
1656    }
1657
1658    pub(crate) fn pane_wait(_pane: &str, _timeout_ms: u32) -> Result<bool> {
1659        with_host(|host| {
1660            host.check_pane_reads()?;
1661            Ok(true)
1662        })
1663    }
1664
1665    pub(crate) fn pane_create_options(
1666        pane: &crate::daemon::panes::NewPane,
1667    ) -> Result<(String, u64)> {
1668        with_host(|host| {
1669            host.check("panes.write")?;
1670            host.create_pane(
1671                &pane.cwd,
1672                pane.command.as_deref(),
1673                &pane.env,
1674                pane.title.as_deref(),
1675                pane.hidden,
1676            )
1677        })
1678    }
1679
1680    pub(crate) fn panes_owned() -> Result<Vec<Pane>> {
1681        with_host(MockHost::owned_panes)
1682    }
1683
1684    pub(crate) fn pane_screen(
1685        pane: &str,
1686        lines: Option<u32>,
1687    ) -> Result<crate::daemon::panes::Screen> {
1688        with_host(|host| host.owned_screen(pane, lines))
1689    }
1690
1691    pub(crate) fn pane_history(pane: &str, query: &str) -> Result<String> {
1692        with_host(|host| host.owned_history(pane, query))
1693    }
1694}