Skip to main content

standard_plugin/testing/
owned.rs

1//! A plugin's own panes on the in-process host: every pane it opens is
2//! recorded in [`MockHost::pane_launches`] and is its own. It types into,
3//! reads and closes them; their screen and history come from what the test
4//! sets.
5
6use alloc::string::ToString;
7use alloc::vec::Vec;
8
9use super::MockHost;
10use crate::api::account::Pane;
11use crate::daemon::PaneChangeKind;
12use crate::daemon::panes::Screen;
13use crate::error::{Error, Result};
14use crate::ui_runtime::Event;
15
16/// Live panes one plugin instance may hold.
17pub(super) const OWNED_PANES_PER_PLUGIN: usize = 8;
18const INPUT_MAX_BYTES: usize = 64 * 1024;
19
20impl MockHost {
21    /// Sets what `panes::screen` answers for one of the plugin's panes.
22    pub fn set_pane_screen(&mut self, pane: &str, screen: Screen) {
23        if let Some(launch) = self.owned_mut(pane) {
24            launch.screen = screen;
25        }
26    }
27
28    /// Sets the page `panes::history` answers for one of the plugin's panes.
29    pub fn set_pane_history(&mut self, pane: &str, page: serde_json::Value) {
30        if let Some(launch) = self.owned_mut(pane) {
31            launch.history = Some(page);
32        }
33    }
34
35    /// The title, directory or agent state of one of the plugin's panes
36    /// changed: a subscribed plugin hears `Changed`, as it does when the
37    /// agent in it goes idle.
38    pub fn owned_pane_changed(&mut self, pane: &str) {
39        self.owned_changed(PaneChangeKind::Changed, pane);
40    }
41
42    /// The program in one of the plugin's panes exits.
43    pub fn owned_pane_exited(&mut self, pane: &str) {
44        self.owned_changed(PaneChangeKind::Exited, pane);
45    }
46
47    fn owned_mut(&mut self, pane: &str) -> Option<&mut super::MockPaneLaunch> {
48        self.machine
49            .pane_launches
50            .iter_mut()
51            .find(|launch| launch.id == pane && !launch.closed)
52    }
53
54    pub(super) fn owned_changed(&mut self, kind: PaneChangeKind, pane: &str) {
55        if !self.machine.panes_subscribed {
56            return;
57        }
58        let pane = self
59            .panes
60            .iter()
61            .find(|known| known.id == pane)
62            .cloned()
63            .unwrap_or_else(|| Pane {
64                id: pane.to_string(),
65                ..Pane::default()
66            });
67        self.machine
68            .pending
69            .push_back(Event::PaneChanged { kind, pane });
70    }
71
72    /// `panes.read`, or `panes.write` for the plugin's own panes alone.
73    pub(super) fn check_pane_reads(&mut self) -> Result<()> {
74        if self.grants.allows("panes.write") {
75            return Ok(());
76        }
77        self.check("panes.read")
78    }
79
80    fn owned_checked(&mut self, pane: &str) -> Result<&mut super::MockPaneLaunch> {
81        self.check("panes.write")?;
82        self.owned_mut(pane)
83            .ok_or_else(|| Error::Invalid(alloc::format!("{pane} is not a pane of this plugin")))
84    }
85
86    pub(super) fn owned_panes(&mut self) -> Result<Vec<Pane>> {
87        self.check("panes.write")?;
88        let live: Vec<_> = self
89            .machine
90            .pane_launches
91            .iter()
92            .filter(|launch| !launch.closed)
93            .map(|launch| launch.id.clone())
94            .collect();
95        Ok(self
96            .panes
97            .iter()
98            .filter(|pane| live.contains(&pane.id))
99            .cloned()
100            .collect())
101    }
102
103    /// Typing into one of its own panes is recorded; another pane takes the
104    /// controller rules, which the test host does not model.
105    pub(super) fn pane_input(&mut self, pane: &str, bytes: &[u8]) -> Result<()> {
106        self.check("panes.write")?;
107        if bytes.len() > INPUT_MAX_BYTES {
108            return Err(Error::Invalid("input over 64 KiB".into()));
109        }
110        if let Some(launch) = self.owned_mut(pane) {
111            launch.input.extend_from_slice(bytes);
112        }
113        Ok(())
114    }
115
116    pub(super) fn pane_close(&mut self, pane: &str) -> Result<()> {
117        self.check("panes.write")?;
118        if let Some(launch) = self.owned_mut(pane) {
119            launch.closed = true;
120            self.owned_changed(PaneChangeKind::Closed, pane);
121            self.panes.retain(|known| known.id != pane);
122        }
123        Ok(())
124    }
125
126    pub(super) fn owned_screen(&mut self, pane: &str, lines: Option<u32>) -> Result<Screen> {
127        let mut screen = self.owned_checked(pane)?.screen.clone();
128        if let Some(keep) = lines.map(|keep| keep as usize)
129            && screen.lines.len() > keep
130        {
131            let dropped = screen.lines.len() - keep;
132            screen.lines.drain(..dropped);
133            screen.scrollback = screen
134                .scrollback
135                .saturating_sub(u32::try_from(dropped).unwrap_or(u32::MAX));
136            screen.truncated = true;
137        }
138        Ok(screen)
139    }
140
141    pub(super) fn owned_history(
142        &mut self,
143        pane: &str,
144        query: &str,
145    ) -> Result<alloc::string::String> {
146        let mut query: serde_json::Value = serde_json::from_str(query)
147            .map_err(|error| Error::Invalid(alloc::format!("a history query: {error}")))?;
148        let Some(fields) = query.as_object_mut() else {
149            return Err(Error::Invalid("a history query is an object".into()));
150        };
151        fields.insert(
152            "target".into(),
153            serde_json::json!({"type": "pane", "pane": pane}),
154        );
155        let launch = self.owned_checked(pane)?;
156        launch.history_queries.push(query);
157        let page = launch
158            .history
159            .clone()
160            .unwrap_or_else(|| serde_json::json!({"entries": [], "next": null}));
161        Ok(page.to_string())
162    }
163}