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