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