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