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