1#![doc = include_str!("../tests/testing_harness.rs")]
12mod http;
15mod machine;
16
17pub(crate) use http::send as http_send;
18
19pub use machine::{MockPaneLaunch, MockProcess, MockWatch, MockWebSocket, ProcessScript};
20
21use alloc::collections::{BTreeMap, BTreeSet};
22use alloc::string::{String, ToString};
23use alloc::vec::Vec;
24use core::cell::RefCell;
25
26use standard_plugin_manifest::{GrantDenied, Grants};
27
28use crate::api::Target;
29use crate::api::account::{AccountState, Pane};
30use crate::api::capabilities::Capabilities;
31use crate::api::view::Theme;
32use crate::error::{Error, Result};
33use crate::geometry::{Geometry, Rect};
34use crate::surface::{HEADER_LEN, Model, RegionLayout};
35use crate::ui_runtime::{Event, Power, UiPlugin, UiRuntime};
36
37#[derive(Clone, Copy, Debug, PartialEq, Eq)]
39pub enum CallKind {
40 Wait,
42 Send,
44 Async(u64),
47}
48
49#[derive(Clone, Debug, PartialEq, Eq)]
51pub struct MockCall {
52 pub method: String,
53 pub payload: String,
54 pub target: Target,
55 pub kind: CallKind,
56 pub timeout_ms: Option<u32>,
57 pub answered: bool,
59}
60
61#[derive(Clone, Debug, PartialEq, Eq)]
63pub struct MockCommit {
64 pub seq: u32,
66 pub slot: u8,
67 pub dirty: Vec<Rect>,
69 pub full: bool,
71 pub geometry: Geometry,
72 pub model: Model,
73 pub region: Vec<u8>,
75}
76
77impl MockCommit {
78 pub fn slot_bytes(&self) -> &[u8] {
80 let layout = RegionLayout::new(self.model, self.geometry);
81 let start = (HEADER_LEN + u32::from(self.slot) * layout.slot_len) as usize;
82 &self.region[start..start + layout.slot_len as usize]
83 }
84}
85
86#[derive(Clone, Debug)]
87struct MockSurface {
88 model: Model,
89 geometry: Geometry,
90 region: Option<(usize, usize)>,
92 pending: Option<(usize, usize)>,
93 committed_once: bool,
94 commits: Vec<MockCommit>,
95}
96
97#[derive(Clone, Debug)]
100pub struct MockHost {
101 plugin_id: String,
102 granted: Vec<String>,
103 grants: Grants,
104 pub config: String,
105 pub values: BTreeMap<String, String>,
106 pub secrets: BTreeMap<String, String>,
107 pub account: AccountState,
108 pub driving: bool,
109 pub theme: Theme,
110 pub reduced_motion: bool,
112 pub capabilities: Capabilities,
113 pub focused_pane: Option<String>,
114 pub claimed_elsewhere: BTreeSet<String>,
116 pub claims: BTreeSet<String>,
118 pub emitted: Vec<(String, String, Target)>,
120 pub published: Vec<(String, String)>,
122 pub live_deleted: Vec<String>,
124 pub listening: BTreeSet<String>,
126 pub call_answers: BTreeMap<String, String>,
129 pub calls: Vec<MockCall>,
131 pub denials: Vec<String>,
133 pub panes: Vec<Pane>,
134 pub frame_request: Option<u64>,
138 pub opened: Vec<String>,
140 pub opened_urls: Vec<String>,
142 pub focused_panes: Vec<String>,
144 pub created_panes: Vec<(String, String, Vec<String>, String)>,
146 pub pane_create_error: Option<String>,
147 pub now_ms: u64,
150 pub url_gesture_ms: Option<u64>,
153 pub closed: Vec<String>,
155 pub gesture: bool,
158 pane_create_used: bool,
159 pub machine_id: Option<String>,
162 pub account_id: Option<String>,
164 pub lease_epoch: Option<u64>,
167 pub release: Option<crate::daemon::Release>,
169 pub instance_id: String,
171 pub environment: Vec<(String, String)>,
173 pub wall_ms: u64,
175 pub utc_offset_minutes: i32,
177 pub time_zone: Option<String>,
179 pub health: Option<(crate::health::Health, String)>,
181 pub tints: BTreeMap<String, u32>,
184 pub requested: BTreeMap<String, (u32, u32)>,
187 pub labels: BTreeMap<String, String>,
189 pub carets: BTreeMap<String, (u32, u32)>,
191 pub embed_bindings: BTreeSet<String>,
193 pub instances: BTreeMap<String, Option<String>>,
196 pub requested_px: BTreeMap<String, (u32, u32)>,
198 pub loopback_proxies: BTreeMap<String, u16>,
200 pub docked: BTreeSet<String>,
202 machine_surfaces: BTreeSet<String>,
204 project_surfaces: BTreeSet<String>,
206 surfaces: BTreeMap<String, MockSurface>,
207 machine: machine::Machine,
209 http: http::MockHttp,
211}
212
213impl MockHost {
214 pub fn new(plugin_id: &str) -> Self {
216 Self {
217 plugin_id: plugin_id.to_string(),
218 granted: Vec::new(),
219 grants: Grants::new(plugin_id, []),
220 config: String::new(),
221 values: BTreeMap::new(),
222 secrets: BTreeMap::new(),
223 account: AccountState::default(),
224 driving: false,
225 theme: Theme::default(),
226 reduced_motion: false,
227 capabilities: Capabilities {
228 graphics: false,
229 kitty: false,
230 frame_rate: 60,
231 cell_px: (0, 0),
232 pixel_scale: 1,
233 },
234 focused_pane: None,
235 claimed_elsewhere: BTreeSet::new(),
236 claims: BTreeSet::new(),
237 emitted: Vec::new(),
238 published: Vec::new(),
239 live_deleted: Vec::new(),
240 listening: BTreeSet::new(),
241 call_answers: BTreeMap::new(),
242 calls: Vec::new(),
243 denials: Vec::new(),
244 panes: Vec::new(),
245 frame_request: None,
246 opened: Vec::new(),
247 focused_panes: Vec::new(),
248 created_panes: Vec::new(),
249 pane_create_error: None,
250 opened_urls: Vec::new(),
251 now_ms: 0,
252 url_gesture_ms: None,
253 closed: Vec::new(),
254 gesture: false,
255 pane_create_used: false,
256 machine_id: None,
257 account_id: None,
258 lease_epoch: None,
259 release: None,
260 instance_id: "test-viewer".to_string(),
261 environment: Vec::new(),
262 wall_ms: 0,
263 utc_offset_minutes: 0,
264 time_zone: None,
265 health: None,
266 tints: BTreeMap::new(),
267 requested: BTreeMap::new(),
268 labels: BTreeMap::new(),
269 carets: BTreeMap::new(),
270 embed_bindings: BTreeSet::new(),
271 instances: BTreeMap::new(),
272 requested_px: BTreeMap::new(),
273 loopback_proxies: BTreeMap::new(),
274 docked: BTreeSet::new(),
275 machine_surfaces: BTreeSet::new(),
276 project_surfaces: BTreeSet::new(),
277 surfaces: BTreeMap::new(),
278 machine: machine::Machine::default(),
279 http: http::MockHttp::default(),
280 }
281 }
282
283 pub fn clock(mut self, wall_ms: u64, utc_offset_minutes: i32, time_zone: Option<&str>) -> Self {
285 self.wall_ms = wall_ms;
286 self.utc_offset_minutes = utc_offset_minutes;
287 self.time_zone = time_zone.map(str::to_string);
288 self
289 }
290
291 pub fn singleton(mut self, epoch: u64) -> Self {
293 self.lease_epoch = Some(epoch);
294 self
295 }
296
297 pub fn machine(mut self, machine_id: &str) -> Self {
299 self.machine_id = Some(machine_id.to_string());
300 self
301 }
302
303 pub fn env(mut self, name: &str, value: &str) -> Self {
305 self.environment.retain(|(key, _)| key != name);
306 self.environment.push((name.to_string(), value.to_string()));
307 self.environment.sort();
308 self
309 }
310
311 pub fn grant(mut self, grants: &[&str]) -> Self {
313 self.granted
314 .extend(grants.iter().map(|grant| grant.to_string()));
315 self.grants = Grants::new(&self.plugin_id, self.granted.iter().cloned());
316 self
317 }
318
319 pub fn surface(mut self, id: &str, model: Model) -> Self {
321 self.surfaces.insert(
322 id.to_string(),
323 MockSurface {
324 model,
325 geometry: Geometry::default(),
326 region: None,
327 pending: None,
328 committed_once: false,
329 commits: Vec::new(),
330 },
331 );
332 self
333 }
334
335 pub fn machine_surface(mut self, id: &str, model: Model) -> Self {
338 self.machine_surfaces.insert(id.to_string());
339 self.surface(id, model)
340 }
341
342 pub fn project_surface(mut self, id: &str, model: Model) -> Self {
345 self.project_surfaces.insert(id.to_string());
346 self.surface(id, model)
347 }
348
349 pub fn driving(mut self, driving: bool) -> Self {
350 self.driving = driving;
351 self
352 }
353
354 pub fn set_geometry(&mut self, id: &str, geometry: Geometry) -> Option<Event> {
357 if !self.surfaces.contains_key(id)
358 && let Some((base, _pane)) = id.split_once('@')
359 && let Some(template) = self.surfaces.get(base)
360 {
361 let mut instance = template.clone();
363 instance.geometry = Geometry::default();
364 instance.region = None;
365 instance.pending = None;
366 instance.committed_once = false;
367 instance.commits.clear();
368 self.surfaces.insert(id.to_string(), instance);
369 }
370 let surface = self.surfaces.get_mut(id)?;
371 if surface.geometry == geometry {
372 return None;
373 }
374 surface.geometry = geometry;
375 Some(Event::Resize {
376 surface: id.to_string(),
377 geometry,
378 })
379 }
380
381 pub fn attached(&self, id: &str) -> bool {
383 self.surfaces
384 .get(id)
385 .is_some_and(|surface| surface.region.is_some())
386 }
387
388 pub fn set_model(&mut self, id: &str, model: Model) -> Option<Event> {
391 let surface = self.surfaces.get_mut(id)?;
392 if surface.model == model {
393 return None;
394 }
395 surface.model = model;
396 surface.region = None;
397 surface.pending = None;
398 surface.committed_once = false;
399 Some(Event::Resize {
400 surface: id.to_string(),
401 geometry: surface.geometry,
402 })
403 }
404
405 pub fn commits(&self, id: &str) -> Vec<MockCommit> {
407 self.surfaces
408 .get(id)
409 .map(|surface| surface.commits.clone())
410 .unwrap_or_default()
411 }
412
413 fn answer(&self, method: &str) -> Result<String> {
415 self.call_answers
416 .get(method)
417 .cloned()
418 .ok_or_else(|| Error::Invalid(alloc::format!("unknown method {method:?}")))
419 }
420
421 fn take_async_answers(&mut self) -> Vec<Event> {
424 let mut events = Vec::new();
425 for index in 0..self.calls.len() {
426 let CallKind::Async(id) = self.calls[index].kind else {
427 continue;
428 };
429 if self.calls[index].answered {
430 continue;
431 }
432 self.calls[index].answered = true;
433 let result = self.answer(&self.calls[index].method).map(crate::Json);
434 events.push(Event::CallResult {
435 id: crate::api::calls::CallId(id),
436 result,
437 });
438 }
439 events
440 }
441
442 fn deny(&mut self, denial: GrantDenied) -> Error {
443 self.denials.push(denial.grant.clone());
444 Error::GrantDenied {
445 grant: denial.grant,
446 }
447 }
448
449 fn check(&mut self, grant: &str) -> Result<()> {
450 self.grants.check(grant).map_err(|denial| self.deny(denial))
451 }
452
453 fn check_namespaced(&mut self, kind: &str, subject: &str) -> Result<()> {
454 self.grants
455 .check_namespaced(kind, subject)
456 .map_err(|denial| self.deny(denial))
457 }
458}
459
460std::thread_local! {
461 static MOCK: RefCell<Option<MockHost>> = const { RefCell::new(None) };
462}
463
464pub fn install(host: MockHost) {
467 MOCK.with(|mock| *mock.borrow_mut() = Some(host));
468}
469
470pub fn with_host<R>(f: impl FnOnce(&mut MockHost) -> R) -> R {
472 MOCK.with(|mock| {
473 let mut mock = mock.borrow_mut();
474 f(mock.get_or_insert_with(|| MockHost::new("test-plugin")))
475 })
476}
477
478pub struct Harness<P: UiPlugin> {
480 runtime: UiRuntime<P>,
481}
482
483impl<P: UiPlugin> Harness<P> {
484 pub fn activate(host: MockHost, config: &str) -> Self {
486 let mut host = host;
487 host.config = config.to_string();
488 install(host);
489 let runtime = UiRuntime::new();
490 runtime.activate(config.to_string());
491 Self { runtime }
492 }
493
494 pub fn resize(&mut self, surface: &str, geometry: Geometry) {
496 if let Some(event) = with_host(|host| host.set_geometry(surface, geometry)) {
497 self.runtime.event(event);
498 }
499 }
500
501 pub fn frame(&mut self, now_ms: u64, interval_ms: u32, power: Power) -> Option<u64> {
504 with_host(|host| {
505 host.frame_request = None;
506 host.now_ms = now_ms;
507 });
508 self.runtime.frame(now_ms, interval_ms, power)
509 }
510
511 pub fn event(&mut self, event: Event) {
512 let gesture = matches!(
513 &event,
514 Event::Key(_)
515 | Event::Paste { .. }
516 | Event::Command(_)
517 | Event::Pointer(crate::Pointer {
518 kind: crate::PointerKind::Down,
519 ..
520 })
521 ) || crate::links::Link::from_event(&event).is_some();
522 with_host(|host| {
523 host.gesture = gesture;
524 host.pane_create_used = false;
525 if gesture {
526 host.url_gesture_ms = Some(host.now_ms);
527 }
528 });
529 self.runtime.event(event);
530 with_host(|host| host.gesture = false);
531 }
532
533 pub fn show(&mut self, surface: &str, visible: bool) {
535 self.event(Event::Visibility {
536 surface: surface.to_string(),
537 visible,
538 });
539 }
540
541 pub fn set_capabilities(&mut self, capabilities: Capabilities) {
543 with_host(|host| host.capabilities = capabilities);
544 self.event(Event::CapabilitiesChanged);
545 }
546
547 pub fn set_theme(&mut self, theme: Theme) {
549 with_host(|host| host.theme = theme);
550 self.event(Event::ThemeChanged);
551 }
552
553 pub fn set_reduced_motion(&mut self, reduced: bool) {
556 with_host(|host| host.reduced_motion = reduced);
557 self.event(Event::ThemeChanged);
558 }
559
560 pub fn set_model(&mut self, surface: &str, model: Model) {
563 if let Some(event) = with_host(|host| host.set_model(surface, model)) {
564 self.runtime.event(event);
565 }
566 }
567
568 pub fn key(&mut self, surface: &str, code: crate::KeyCode) {
570 self.event(Event::Key(crate::Key::press(surface, code)));
571 }
572
573 pub fn paste(&mut self, surface: &str, text: &str) {
575 self.event(Event::Paste {
576 surface: surface.to_string(),
577 text: text.to_string(),
578 });
579 }
580
581 pub fn pointer(&mut self, surface: &str, kind: crate::PointerKind, x: u32, y: u32) {
583 let cell = with_host(|host| {
584 host.surfaces
585 .get(surface)
586 .map_or((1, 1), |surface| match surface.model {
587 Model::Cells => (1, 1),
588 Model::Pixels => (
589 surface.geometry.cell_px_w.max(1),
590 surface.geometry.cell_px_h.max(1),
591 ),
592 })
593 });
594 self.event(Event::Pointer(crate::Pointer {
595 surface: surface.to_string(),
596 x,
597 y,
598 col: x / cell.0,
599 row: y / cell.1,
600 button: if matches!(kind, crate::PointerKind::Move) {
601 crate::Button::None
602 } else {
603 crate::Button::Left
604 },
605 kind,
606 modifiers: crate::Modifiers::NONE,
607 }));
608 }
609
610 pub fn link(&mut self, url: &str, pane: Option<&str>, machine: Option<&str>) {
612 let payload = serde_json::json!({ "url": url, "pane": pane, "machine": machine });
613 self.event(Event::Plugin {
614 name: crate::links::OPEN_EVENT.into(),
615 payload: crate::Json(payload.to_string()),
616 });
617 }
618
619 pub fn command(&mut self, id: &str) {
621 self.event(Event::Command(id.to_string()));
622 }
623
624 pub fn answer_calls(&mut self) -> usize {
628 let events = with_host(MockHost::take_async_answers);
629 let count = events.len();
630 for event in events {
631 self.event(event);
632 }
633 count
634 }
635
636 pub fn take_frame_request(&mut self) -> Option<u64> {
638 with_host(|host| host.frame_request.take())
639 }
640
641 pub fn plugin<R>(&self, f: impl FnOnce(&mut P) -> R) -> R {
643 self.runtime
644 .with_plugin(f)
645 .unwrap_or_else(|| panic!("the plugin is not active"))
646 }
647
648 pub fn commits(&self, surface: &str) -> Vec<MockCommit> {
649 with_host(|host| host.commits(surface))
650 }
651
652 pub fn host<R>(&self, f: impl FnOnce(&mut MockHost) -> R) -> R {
653 with_host(f)
654 }
655
656 pub fn deactivate(self) {
657 self.runtime.deactivate();
658 }
659}
660
661pub struct DaemonHarness<P: crate::daemon::DaemonPlugin> {
664 runtime: crate::daemon::runtime::DaemonRuntime<P>,
665}
666
667impl<P: crate::daemon::DaemonPlugin> DaemonHarness<P> {
668 pub fn activate(host: MockHost, config: &str) -> Self {
670 let mut host = host;
671 host.config = config.to_string();
672 install(host);
673 let runtime = crate::daemon::runtime::DaemonRuntime::new();
674 runtime.activate(config.to_string());
675 Self { runtime }
676 }
677
678 pub fn drive(&mut self, now_ms: u64) -> Option<u64> {
682 loop {
683 let pending = with_host(|host| host.machine.pending.pop_front());
684 let Some(event) = pending else {
685 break;
686 };
687 self.runtime.event(event);
688 }
689 self.runtime.drive(now_ms)
690 }
691
692 pub fn output(&mut self, pid: u32, stderr: bool, bytes: &[u8]) {
695 with_host(|host| host.output(pid, stderr, bytes));
696 }
697
698 pub fn exit(&mut self, pid: u32, status: i32) {
700 with_host(|host| host.exited(pid, status));
701 }
702
703 pub fn file_changed(&mut self, path: &str) -> usize {
707 with_host(|host| host.changed(path))
708 }
709
710 pub fn plugin<R>(&self, f: impl FnOnce(&P) -> R) -> R {
712 self.runtime
713 .with_plugin(f)
714 .unwrap_or_else(|| panic!("the plugin is not active"))
715 }
716
717 pub fn event(&mut self, event: Event) {
719 self.runtime.event(event);
720 }
721
722 pub fn interest(&mut self, surfaces: &[&str]) {
728 let payload = serde_json::json!({ "surfaces": surfaces }).to_string();
729 self.runtime.event(Event::Plugin {
730 name: crate::daemon::INTEREST_EVENT.to_string(),
731 payload: crate::Json(payload),
732 });
733 }
734
735 pub fn call(&mut self, method: &str, request: &str) -> Result<String> {
737 self.call_from(method, request, crate::daemon::Caller::default())
738 }
739
740 pub fn call_from(
742 &mut self,
743 method: &str,
744 request: &str,
745 caller: crate::daemon::Caller,
746 ) -> Result<String> {
747 self.runtime
748 .handle_call(method, request.to_string(), caller)
749 }
750
751 pub fn host<R>(&self, f: impl FnOnce(&mut MockHost) -> R) -> R {
752 with_host(f)
753 }
754
755 pub fn deactivate(self) {
756 self.runtime.deactivate();
757 }
758}
759
760pub(crate) mod host_calls {
762 use super::*;
763
764 fn check_key_name(key: &str) -> Result<()> {
769 let name = key.split_once('.').map_or("", |(_, name)| name);
770 let allowed =
771 |c: char| c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | ':' | '/' | '-');
772 let first = name.chars().next();
773 if first.is_some_and(|c| c.is_ascii_alphanumeric() || c == '_') && name.chars().all(allowed)
774 {
775 Ok(())
776 } else {
777 Err(Error::Invalid(alloc::format!(
778 "{key:?}: a key is <namespace>.<name>, the name of letters, digits and _ . : / -"
779 )))
780 }
781 }
782
783 pub(crate) fn values_get(key: &str) -> Result<Option<String>> {
784 with_host(|host| {
785 host.check_namespaced("values.read", key)?;
786 Ok(host.values.get(key).cloned())
787 })
788 }
789
790 pub(crate) fn values_set(key: &str, value: &str) -> Result<()> {
791 with_host(|host| {
792 host.check_namespaced("values.write", key)?;
793 check_key_name(key)?;
794 host.values.insert(key.to_string(), value.to_string());
795 Ok(())
796 })
797 }
798
799 pub(crate) fn values_delete(key: &str) -> Result<()> {
800 with_host(|host| {
801 host.check_namespaced("values.write", key)?;
802 host.values.remove(key);
803 Ok(())
804 })
805 }
806
807 pub(crate) fn values_keys(prefix: &str) -> Result<Vec<String>> {
808 with_host(|host| {
809 host.check_namespaced("values.read", prefix)?;
810 Ok(host
811 .values
812 .keys()
813 .filter(|key| key.starts_with(prefix))
814 .cloned()
815 .collect())
816 })
817 }
818
819 pub(crate) fn values_watch(prefix: &str) -> Result<()> {
820 with_host(|host| host.check_namespaced("values.read", prefix))
821 }
822
823 pub(crate) fn live_publish(key: &str, payload: &str) -> Result<()> {
824 with_host(|host| {
825 host.check_namespaced("live.publish", key)?;
826 check_key_name(key)?;
827 host.published.push((key.to_string(), payload.to_string()));
828 Ok(())
829 })
830 }
831
832 pub(crate) fn live_delete(key: &str) -> Result<()> {
833 with_host(|host| {
834 host.check_namespaced("live.publish", key)?;
835 host.live_deleted.push(key.to_string());
836 Ok(())
837 })
838 }
839
840 pub(crate) fn live_subscribe(prefix: &str) -> Result<()> {
841 with_host(|host| host.check_namespaced("live.subscribe", prefix))
842 }
843
844 pub(crate) fn live_unsubscribe(prefix: &str) -> Result<()> {
845 with_host(|host| host.check_namespaced("live.subscribe", prefix))
846 }
847
848 pub(crate) fn events_emit(name: &str, payload: &str, to: &Target) -> Result<()> {
849 with_host(|host| {
850 if name.starts_with("system.") {
851 return Err(host.deny(GrantDenied {
852 grant: alloc::format!("events.emit:{name}"),
853 }));
854 }
855 host.check_namespaced("events.emit", name)?;
856 host.emitted
857 .push((name.to_string(), payload.to_string(), to.clone()));
858 Ok(())
859 })
860 }
861
862 pub(crate) fn events_on(pattern: &str) -> Result<()> {
863 with_host(|host| {
864 host.check_namespaced("events.on", pattern)?;
865 host.listening.insert(pattern.to_string());
866 Ok(())
867 })
868 }
869
870 pub(crate) fn events_off(pattern: &str) -> Result<()> {
871 with_host(|host| {
872 host.check_namespaced("events.on", pattern)?;
873 host.listening.remove(pattern);
874 Ok(())
875 })
876 }
877
878 fn record_call(
879 host: &mut MockHost,
880 method: &str,
881 payload: &str,
882 to: &Target,
883 kind: CallKind,
884 timeout_ms: Option<u32>,
885 ) -> Result<()> {
886 let own = alloc::format!("call:{}", host.grants.plugin_id());
887 host.check(&own)?;
888 host.calls.push(MockCall {
889 method: method.to_string(),
890 payload: payload.to_string(),
891 target: to.clone(),
892 kind,
893 timeout_ms,
894 answered: false,
895 });
896 Ok(())
897 }
898
899 pub(crate) fn call(
900 method: &str,
901 payload: &str,
902 to: &Target,
903 timeout_ms: Option<u32>,
904 ) -> Result<String> {
905 with_host(|host| {
906 record_call(host, method, payload, to, CallKind::Wait, timeout_ms)?;
907 host.answer(method)
908 })
909 }
910
911 pub(crate) fn call_send(method: &str, payload: &str, to: &Target) -> Result<()> {
912 with_host(|host| record_call(host, method, payload, to, CallKind::Send, None))
913 }
914
915 pub(crate) fn call_async(
916 method: &str,
917 payload: &str,
918 to: &Target,
919 timeout_ms: Option<u32>,
920 ) -> Result<u64> {
921 with_host(|host| {
922 let id = host
923 .calls
924 .iter()
925 .filter(|call| matches!(call.kind, CallKind::Async(_)))
926 .count() as u64
927 + 1;
928 record_call(host, method, payload, to, CallKind::Async(id), timeout_ms)?;
929 Ok(id)
930 })
931 }
932
933 pub(crate) fn config() -> String {
934 with_host(|host| host.config.clone())
935 }
936
937 pub(crate) fn health_set(health: crate::health::Health, message: &str) {
938 with_host(|host| host.health = Some((health, message.to_string())));
939 }
940
941 pub(crate) fn secret(name: &str) -> Result<Option<String>> {
942 with_host(|host| {
943 host.check(&alloc::format!("secret:{name}"))?;
944 Ok(host.secrets.get(name).cloned())
945 })
946 }
947
948 pub(crate) fn account_state() -> Result<AccountState> {
949 with_host(|host| {
950 host.check("account.read")?;
951 Ok(host.account.clone())
952 })
953 }
954
955 pub(crate) fn account_watch() -> Result<()> {
956 with_host(|host| host.check("account.read"))
957 }
958
959 pub(crate) fn claim(key: &str, _ttl_ms: u32) -> Result<bool> {
960 with_host(|host| {
961 if host.claimed_elsewhere.contains(key) {
962 return Ok(false);
963 }
964 host.claims.insert(key.to_string());
965 Ok(true)
966 })
967 }
968
969 pub(crate) fn release(key: &str) -> Result<()> {
970 with_host(|host| {
971 host.claims.remove(key);
972 Ok(())
973 })
974 }
975
976 fn unknown(id: &str) -> Error {
977 Error::Invalid(alloc::format!("no surface {id:?} in the manifest"))
978 }
979
980 pub(crate) fn surface_layout(id: &str) -> Result<RegionLayout> {
981 with_host(|host| {
982 let surface = host.surfaces.get(id).ok_or_else(|| unknown(id))?;
983 Ok(RegionLayout::new(surface.model, surface.geometry))
984 })
985 }
986
987 pub(crate) fn surface_attach(id: &str, region: &[u8]) -> Result<()> {
988 with_host(|host| {
989 let surface = host.surfaces.get_mut(id).ok_or_else(|| unknown(id))?;
990 let layout = RegionLayout::new(surface.model, surface.geometry);
991 if surface.geometry.is_empty() {
992 return Err(Error::Invalid(alloc::format!(
993 "surface {id:?} has no size yet"
994 )));
995 }
996 if region.len() < layout.len as usize {
997 return Err(Error::Invalid("region too small".into()));
998 }
999 let word = |index: usize| {
1000 u32::from_le_bytes([
1001 region[index * 4],
1002 region[index * 4 + 1],
1003 region[index * 4 + 2],
1004 region[index * 4 + 3],
1005 ])
1006 };
1007 let g = surface.geometry;
1008 let expected = [
1009 match surface.model {
1010 Model::Cells => 0,
1011 Model::Pixels => 1,
1012 },
1013 g.cols,
1014 g.rows,
1015 g.px_w,
1016 g.px_h,
1017 g.cell_px_w,
1018 g.cell_px_h,
1019 ];
1020 if (1..8).any(|index| word(index) != expected[index - 1]) {
1021 return Err(Error::Invalid(
1022 "region header does not describe the current layout".into(),
1023 ));
1024 }
1025 let bound = (region.as_ptr() as usize, region.len());
1026 if surface.region.is_none() {
1027 surface.region = Some(bound);
1028 } else {
1029 surface.pending = Some(bound);
1030 }
1031 Ok(())
1032 })
1033 }
1034
1035 pub(crate) fn surface_commit(id: &str, slot: u8, dirty: &[Rect]) -> Result<()> {
1036 with_host(|host| {
1037 let surface = host.surfaces.get_mut(id).ok_or_else(|| unknown(id))?;
1038 if surface.region.is_none() && surface.pending.is_none() {
1039 return Err(Error::Invalid(alloc::format!(
1040 "surface {id:?} has no region attached"
1041 )));
1042 }
1043 if slot > 1 {
1044 return Err(Error::Invalid("slot must be 0 or 1".into()));
1045 }
1046 let full = surface.pending.is_some() || !surface.committed_once;
1047 if let Some(pending) = surface.pending.take() {
1048 surface.region = Some(pending);
1049 }
1050 let Some((address, len)) = surface.region else {
1051 return Err(Error::Invalid("no region".into()));
1052 };
1053 let bytes = unsafe { core::slice::from_raw_parts(address as *const u8, len) };
1058 let seq = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
1059 surface.committed_once = true;
1060 surface.commits.push(MockCommit {
1061 seq,
1062 slot,
1063 dirty: dirty.to_vec(),
1064 full,
1065 geometry: surface.geometry,
1066 model: surface.model,
1067 region: bytes.to_vec(),
1068 });
1069 Ok(())
1070 })
1071 }
1072
1073 pub(crate) fn surface_detach(id: &str) -> Result<()> {
1074 with_host(|host| {
1075 let surface = host.surfaces.get_mut(id).ok_or_else(|| unknown(id))?;
1076 surface.region = None;
1077 surface.pending = None;
1078 Ok(())
1079 })
1080 }
1081
1082 pub(crate) fn is_driving() -> bool {
1083 with_host(|host| host.driving)
1084 }
1085
1086 pub(crate) fn theme() -> Theme {
1087 with_host(|host| host.theme)
1088 }
1089
1090 pub(crate) fn reduced_motion() -> bool {
1091 with_host(|host| host.reduced_motion)
1092 }
1093
1094 pub(crate) fn capabilities() -> Capabilities {
1095 with_host(|host| host.capabilities)
1096 }
1097
1098 pub(crate) fn focused_pane() -> Option<String> {
1099 with_host(|host| host.focused_pane.clone())
1100 }
1101
1102 fn instance(surface: &str) -> Option<(&str, &str)> {
1104 surface
1105 .split_once('@')
1106 .filter(|(_, owner)| !owner.is_empty())
1107 }
1108
1109 pub(crate) fn surface_machine(surface: &str) -> Option<String> {
1110 let (template, machine) = instance(surface)?;
1111 with_host(|host| host.machine_surfaces.contains(template)).then(|| machine.to_string())
1112 }
1113
1114 pub(crate) fn surface_project(surface: &str) -> Option<String> {
1115 let (template, project) = instance(surface)?;
1116 with_host(|host| host.project_surfaces.contains(template)).then(|| project.to_string())
1117 }
1118
1119 pub(crate) fn surface_docked(surface: &str) -> bool {
1120 with_host(|host| host.docked.contains(surface))
1121 }
1122
1123 pub(crate) fn surface_tint(surface: &str) -> Option<u32> {
1124 if let Some(owner) = surface_machine(surface).or_else(|| surface_project(surface)) {
1125 return with_host(|host| host.tints.get(&owner).copied());
1126 }
1127 let pane = surface_pane(surface)?;
1128 with_host(|host| {
1129 let pane = host
1130 .account
1131 .panes
1132 .iter()
1133 .find(|known| known.id == pane.id)?;
1134 pane.project
1135 .as_ref()
1136 .and_then(|project| host.tints.get(project))
1137 .or_else(|| host.tints.get(&pane.machine))
1138 .copied()
1139 })
1140 }
1141
1142 pub(crate) fn identity_tint(id: &str) -> Option<u32> {
1143 with_host(|host| host.tints.get(id).copied())
1144 }
1145
1146 pub(crate) fn surface_request_size(id: &str, cols: u32, rows: u32) -> Result<()> {
1147 with_host(|host| {
1148 let known = host.surfaces.contains_key(id)
1149 || instance(id).is_some_and(|(template, _)| host.surfaces.contains_key(template));
1150 if !known {
1151 return Err(unknown(id));
1152 }
1153 host.requested
1154 .insert(id.to_string(), (cols.min(1024), rows.min(512)));
1155 Ok(())
1156 })
1157 }
1158
1159 pub(crate) fn surface_set_label(id: &str, label: Option<&str>) -> Result<()> {
1160 with_host(|host| {
1161 let known = host.surfaces.contains_key(id)
1162 || instance(id).is_some_and(|(template, _)| host.surfaces.contains_key(template));
1163 if !known {
1164 return Err(unknown(id));
1165 }
1166 match label {
1167 Some(label)
1168 if label.chars().count() > 48 || label.chars().any(char::is_control) =>
1169 {
1170 return Err(crate::Error::Invalid(
1171 "a label is at most 48 characters with no control characters".into(),
1172 ));
1173 }
1174 Some(label) => {
1175 host.labels.insert(id.to_string(), label.to_string());
1176 }
1177 None => {
1178 host.labels.remove(id);
1179 }
1180 }
1181 Ok(())
1182 })
1183 }
1184
1185 pub(crate) fn surface_set_caret(id: &str, caret: Option<(u32, u32)>) -> Result<()> {
1186 with_host(|host| {
1187 let known = host.surfaces.contains_key(id)
1188 || instance(id).is_some_and(|(template, _)| host.surfaces.contains_key(template));
1189 if !known {
1190 return Err(unknown(id));
1191 }
1192 match caret {
1193 Some(caret) => {
1194 host.carets.insert(id.to_string(), caret);
1195 }
1196 None => {
1197 host.carets.remove(id);
1198 }
1199 }
1200 Ok(())
1201 })
1202 }
1203
1204 pub(crate) fn surface_pane(surface: &str) -> Option<crate::api::view::PaneRef> {
1205 let (template, pane) = instance(surface)?;
1206 if with_host(|host| {
1207 host.machine_surfaces.contains(template) || host.project_surfaces.contains(template)
1208 }) {
1209 return None;
1210 }
1211 let id = pane.to_string();
1212 let generation = with_host(|host| {
1213 host.account
1214 .panes
1215 .iter()
1216 .find(|pane| pane.id == id)
1217 .map_or(0, |pane| pane.generation)
1218 });
1219 Some(crate::api::view::PaneRef { id, generation })
1220 }
1221
1222 pub(crate) fn machine_id() -> Option<String> {
1223 with_host(|host| host.machine_id.clone())
1224 }
1225
1226 pub(crate) fn loopback_proxy(machine: &str) -> Result<u16> {
1227 with_host(|host| {
1228 host.check("link.loopback")?;
1229 host.loopback_proxies
1230 .get(machine)
1231 .copied()
1232 .ok_or_else(|| Error::Unavailable(alloc::format!("no proxy to {machine}")))
1233 })
1234 }
1235
1236 pub(crate) fn instance_id() -> String {
1237 with_host(|host| host.instance_id.clone())
1238 }
1239
1240 pub(crate) fn wall_ms() -> u64 {
1241 with_host(|host| host.wall_ms)
1242 }
1243
1244 pub(crate) fn utc_offset_minutes() -> i32 {
1245 with_host(|host| host.utc_offset_minutes)
1246 }
1247
1248 pub(crate) fn time_zone() -> Option<String> {
1249 with_host(|host| host.time_zone.clone())
1250 }
1251
1252 pub(crate) fn daemon_machine_id() -> String {
1253 with_host(|host| host.machine_id.clone().unwrap_or_default())
1254 }
1255
1256 pub(crate) fn daemon_account_id() -> Option<String> {
1257 with_host(|host| host.account_id.clone())
1258 }
1259
1260 pub(crate) fn daemon_lease_epoch() -> Option<u64> {
1261 with_host(|host| host.lease_epoch)
1262 }
1263
1264 pub(crate) fn daemon_release() -> Option<crate::daemon::Release> {
1265 with_host(|host| host.release.clone())
1266 }
1267
1268 pub(crate) fn daemon_environment() -> Vec<(String, String)> {
1269 with_host(|host| host.environment.clone())
1270 }
1271
1272 pub(crate) fn request_frame() {
1273 wake_at(0);
1274 }
1275
1276 pub(crate) fn wake_at(at_ms: u64) {
1277 with_host(|host| {
1278 host.frame_request = Some(host.frame_request.map_or(at_ms, |at| at.min(at_ms)));
1279 });
1280 }
1281
1282 pub(crate) fn url_open(url: &str) -> Result<()> {
1283 use standard_plugin_manifest::url::{URL_OPEN_WINDOW_MS, https_host};
1284 with_host(|host| {
1285 let domain = https_host(url).map_err(Error::Invalid)?;
1286 if !host.grants.allows_url_open(&domain) {
1287 return Err(host.deny(GrantDenied {
1288 grant: alloc::format!("url.open:{domain}"),
1289 }));
1290 }
1291 let now = host.now_ms;
1292 if !host
1293 .url_gesture_ms
1294 .is_some_and(|at| host.gesture || now.saturating_sub(at) <= URL_OPEN_WINDOW_MS)
1295 {
1296 return Err(Error::Invalid(
1297 "url.open needs user input within the last second".into(),
1298 ));
1299 }
1300 host.url_gesture_ms = None;
1301 host.opened_urls.push(url.to_string());
1302 Ok(())
1303 })
1304 }
1305
1306 pub(crate) fn surface_open(id: &str) -> Result<()> {
1307 with_host(|host| {
1308 if !host.surfaces.contains_key(id) {
1309 return Err(unknown(id));
1310 }
1311 if !host.gesture {
1312 return Err(Error::Invalid(
1313 "surface.open needs a user gesture or a command".into(),
1314 ));
1315 }
1316 host.opened.push(id.to_string());
1317 Ok(())
1318 })
1319 }
1320
1321 pub(crate) fn create_pane(project: &str, argv: &[String], title: &str) -> Result<String> {
1322 with_host(|host| {
1323 host.check("view.pane-create")?;
1324 if !host.gesture {
1325 return Err(Error::Invalid("Pane creation needs a user gesture".into()));
1326 }
1327 if !host.driving {
1328 return Err(Error::Unavailable(
1329 "Take control in this viewer to open a pane".into(),
1330 ));
1331 }
1332 if let Some(error) = &host.pane_create_error {
1333 return Err(Error::Unavailable(error.clone()));
1334 }
1335 if host.pane_create_used {
1336 return Err(Error::RateLimited);
1337 }
1338 let pane = alloc::format!("viewer-pane-{}", host.created_panes.len() + 1);
1339 standard_plugin_manifest::pane_create::PaneCreate {
1340 pane: pane.clone(),
1341 project: project.into(),
1342 argv: argv.to_vec(),
1343 title: title.into(),
1344 }
1345 .validate()
1346 .map_err(Error::Invalid)?;
1347 host.pane_create_used = true;
1348 host.created_panes
1349 .push((pane.clone(), project.into(), argv.to_vec(), title.into()));
1350 Ok(pane)
1351 })
1352 }
1353
1354 pub(crate) fn focus_pane(pane: &str) -> Result<()> {
1355 with_host(|host| {
1356 if !host.gesture {
1357 return Err(Error::Invalid(
1358 "view.focus-pane needs a user gesture or a command".into(),
1359 ));
1360 }
1361 host.focused_panes.push(pane.to_string());
1362 Ok(())
1363 })
1364 }
1365
1366 pub(crate) fn surface_close(id: &str) -> Result<()> {
1367 with_host(|host| {
1368 host.closed.push(id.to_string());
1369 Ok(())
1370 })
1371 }
1372
1373 pub(crate) fn process_spawn(program: &str, args: &[String], cwd: Option<&str>) -> Result<u32> {
1374 let mut command = crate::daemon::process::Command::new(program);
1375 command.args = args.to_vec();
1376 command.cwd = cwd.map(ToString::to_string);
1377 with_host(|host| host.spawn(&command))
1378 }
1379
1380 pub(crate) fn process_run(command: &crate::daemon::process::Command) -> Result<u32> {
1381 with_host(|host| host.spawn(command))
1382 }
1383
1384 pub(crate) fn process_write(pid: u32, bytes: &[u8]) -> Result<()> {
1385 with_host(|host| host.write(pid, bytes))
1386 }
1387
1388 pub(crate) fn process_run_with_channel(
1389 command: &crate::daemon::process::Command,
1390 ) -> Result<u32> {
1391 with_host(|host| host.spawn_with_channel(command))
1392 }
1393
1394 pub(crate) fn process_send(pid: u32, message: &str) -> Result<()> {
1395 with_host(|host| host.send(pid, message))
1396 }
1397
1398 pub(crate) fn surface_open_instance(
1399 id: &str,
1400 key: &str,
1401 after: Option<&str>,
1402 ) -> Result<String> {
1403 with_host(|host| {
1404 if !host.surfaces.contains_key(id) {
1405 return Err(unknown(id));
1406 }
1407 let unprompted = after.is_some() && host.grants.allows("surface.open-unprompted");
1408 if !host.gesture && !unprompted {
1409 return Err(Error::Invalid(
1410 "surface.open-instance needs a user gesture, or surface.open-unprompted and a pane".into(),
1411 ));
1412 }
1413 let instance = alloc::format!("{id}@{key}");
1414 host.instances
1415 .insert(instance.clone(), after.map(ToString::to_string));
1416 host.opened.push(instance.clone());
1417 Ok(instance)
1418 })
1419 }
1420
1421 pub(crate) fn surface_request_size_px(id: &str, width: u32, height: u32) -> Result<()> {
1422 with_host(|host| {
1423 host.requested_px.insert(id.to_string(), (width, height));
1424 Ok(())
1425 })
1426 }
1427
1428 pub(crate) fn surface_bind_embed(id: &str, bind: bool) -> Result<()> {
1429 with_host(|host| {
1430 let known = host.surfaces.contains_key(id) || host.instances.contains_key(id);
1431 if !known {
1432 return Err(unknown(id));
1433 }
1434 if bind {
1435 host.embed_bindings.insert(id.to_string());
1436 } else {
1437 host.embed_bindings.remove(id);
1438 }
1439 Ok(())
1440 })
1441 }
1442
1443 pub(crate) fn process_close_stdin(pid: u32) -> Result<()> {
1444 with_host(|host| host.close_stdin(pid))
1445 }
1446
1447 pub(crate) fn process_try_wait(pid: u32) -> Result<Option<i32>> {
1448 with_host(|host| host.try_wait(pid))
1449 }
1450
1451 pub(crate) fn process_wait(pid: u32) -> Result<i32> {
1452 with_host(|host| host.wait(pid))
1453 }
1454
1455 pub(crate) fn process_wait_timeout(pid: u32, _timeout_ms: u32) -> Result<Option<i32>> {
1456 with_host(|host| host.wait_timeout(pid))
1457 }
1458
1459 pub(crate) fn process_kill(pid: u32) -> Result<()> {
1460 with_host(|host| host.kill(pid))
1461 }
1462
1463 pub(crate) fn watch(path: &str, options: &crate::daemon::watch::Options) -> Result<u32> {
1464 with_host(|host| host.watch(path, options.recursive, &options.exclude))
1465 }
1466
1467 pub(crate) fn unwatch(handle: u32) -> Result<()> {
1468 with_host(|host| host.unwatch(handle))
1469 }
1470
1471 pub(crate) fn websocket_open(url: &str, headers: &[(String, String)]) -> Result<u32> {
1472 with_host(|host| host.websocket_open(url, headers))
1473 }
1474
1475 pub(crate) fn websocket_send(socket: u32, text: &str) -> Result<()> {
1476 with_host(|host| host.websocket_send(socket, text))
1477 }
1478
1479 pub(crate) fn websocket_close(socket: u32) {
1480 with_host(|host| host.websocket_close(socket));
1481 }
1482
1483 pub(crate) fn panes() -> Result<Vec<Pane>> {
1484 with_host(|host| {
1485 host.check("panes.read")?;
1486 Ok(host.panes.clone())
1487 })
1488 }
1489
1490 pub(crate) fn pane_create(
1491 cwd: &str,
1492 command: Option<&str>,
1493 env: &[(String, String)],
1494 ) -> Result<(String, u64)> {
1495 with_host(|host| {
1496 host.check("panes.write")?;
1497 host.create_pane(cwd, command, env, None)
1498 })
1499 }
1500
1501 pub(crate) fn pane_create_with(
1502 cwd: &str,
1503 command: Option<&str>,
1504 env: &[(String, String)],
1505 title: Option<&str>,
1506 ) -> Result<(String, u64)> {
1507 with_host(|host| {
1508 host.check("panes.write")?;
1509 host.create_pane(cwd, command, env, title)
1510 })
1511 }
1512
1513 pub(crate) fn pane_input(_pane: &str, _bytes: &[u8]) -> Result<()> {
1514 with_host(|host| host.check("panes.write"))
1515 }
1516
1517 pub(crate) fn pane_close(_pane: &str) -> Result<()> {
1518 with_host(|host| host.check("panes.write"))
1519 }
1520
1521 pub(crate) fn panes_subscribe(_on: bool) -> Result<()> {
1522 with_host(|host| host.check("panes.read"))
1523 }
1524
1525 pub(crate) fn pane_wait(_pane: &str, _timeout_ms: u32) -> Result<bool> {
1526 with_host(|host| {
1527 host.check("panes.read")?;
1528 Ok(true)
1529 })
1530 }
1531}