standard-plugin-sdk 0.1.7

Write Standard Code plugins in Rust: wasm components against standard:plugin@2.0.0
Documentation
//! A plugin's own panes on the in-process host: every pane it opens is
//! recorded in [`MockHost::pane_launches`] and is its own. It types into,
//! reads and closes them; their screen and history come from what the test
//! sets.

use alloc::string::ToString;
use alloc::vec::Vec;

use super::MockHost;
use crate::api::account::Pane;
use crate::daemon::PaneChangeKind;
use crate::daemon::panes::Screen;
use crate::error::{Error, Result};
use crate::ui_runtime::Event;

/// Live panes one plugin instance may hold.
pub(super) const OWNED_PANES_PER_PLUGIN: usize = 8;
const INPUT_MAX_BYTES: usize = 64 * 1024;

impl MockHost {
    /// Sets what `panes::screen` answers for one of the plugin's panes.
    pub fn set_pane_screen(&mut self, pane: &str, screen: Screen) {
        if let Some(launch) = self.owned_mut(pane) {
            launch.screen = screen;
        }
    }

    /// Sets the page `panes::history` answers for one of the plugin's panes.
    pub fn set_pane_history(&mut self, pane: &str, page: serde_json::Value) {
        if let Some(launch) = self.owned_mut(pane) {
            launch.history = Some(page);
        }
    }

    /// The title, directory or agent state of one of the plugin's panes
    /// changed: a subscribed plugin hears `Changed`, as it does when the
    /// agent in it goes idle.
    pub fn owned_pane_changed(&mut self, pane: &str) {
        self.owned_changed(PaneChangeKind::Changed, pane);
    }

    /// The program in one of the plugin's panes exits.
    pub fn owned_pane_exited(&mut self, pane: &str) {
        self.owned_changed(PaneChangeKind::Exited, pane);
    }

    fn owned_mut(&mut self, pane: &str) -> Option<&mut super::MockPaneLaunch> {
        self.machine
            .pane_launches
            .iter_mut()
            .find(|launch| launch.id == pane && !launch.closed)
    }

    pub(super) fn owned_changed(&mut self, kind: PaneChangeKind, pane: &str) {
        if !self.machine.panes_subscribed {
            return;
        }
        let pane = self
            .panes
            .iter()
            .find(|known| known.id == pane)
            .cloned()
            .unwrap_or_else(|| Pane {
                id: pane.to_string(),
                ..Pane::default()
            });
        self.machine
            .pending
            .push_back(Event::PaneChanged { kind, pane });
    }

    /// `panes.read`, or `panes.write` for the plugin's own panes alone.
    pub(super) fn check_pane_reads(&mut self) -> Result<()> {
        if self.grants.allows("panes.write") {
            return Ok(());
        }
        self.check("panes.read")
    }

    fn owned_checked(&mut self, pane: &str) -> Result<&mut super::MockPaneLaunch> {
        self.check("panes.write")?;
        self.owned_mut(pane)
            .ok_or_else(|| Error::Invalid(alloc::format!("{pane} is not a pane of this plugin")))
    }

    pub(super) fn owned_panes(&mut self) -> Result<Vec<Pane>> {
        self.check("panes.write")?;
        let live: Vec<_> = self
            .machine
            .pane_launches
            .iter()
            .filter(|launch| !launch.closed)
            .map(|launch| launch.id.clone())
            .collect();
        Ok(self
            .panes
            .iter()
            .filter(|pane| live.contains(&pane.id))
            .cloned()
            .collect())
    }

    /// Typing into one of its own panes is recorded; another pane takes the
    /// controller rules, which the test host does not model.
    pub(super) fn pane_input(&mut self, pane: &str, bytes: &[u8]) -> Result<()> {
        self.check("panes.write")?;
        if bytes.len() > INPUT_MAX_BYTES {
            return Err(Error::Invalid("input over 64 KiB".into()));
        }
        if let Some(launch) = self.owned_mut(pane) {
            launch.input.extend_from_slice(bytes);
        }
        Ok(())
    }

    pub(super) fn pane_close(&mut self, pane: &str) -> Result<()> {
        self.check("panes.write")?;
        if let Some(launch) = self.owned_mut(pane) {
            launch.closed = true;
            self.owned_changed(PaneChangeKind::Closed, pane);
            self.panes.retain(|known| known.id != pane);
        }
        Ok(())
    }

    pub(super) fn owned_screen(&mut self, pane: &str, lines: Option<u32>) -> Result<Screen> {
        let mut screen = self.owned_checked(pane)?.screen.clone();
        if let Some(keep) = lines.map(|keep| keep as usize)
            && screen.lines.len() > keep
        {
            let dropped = screen.lines.len() - keep;
            screen.lines.drain(..dropped);
            screen.scrollback = screen
                .scrollback
                .saturating_sub(u32::try_from(dropped).unwrap_or(u32::MAX));
            screen.truncated = true;
        }
        Ok(screen)
    }

    pub(super) fn owned_history(
        &mut self,
        pane: &str,
        query: &str,
    ) -> Result<alloc::string::String> {
        let mut query: serde_json::Value = serde_json::from_str(query)
            .map_err(|error| Error::Invalid(alloc::format!("a history query: {error}")))?;
        let Some(fields) = query.as_object_mut() else {
            return Err(Error::Invalid("a history query is an object".into()));
        };
        fields.insert(
            "target".into(),
            serde_json::json!({"type": "pane", "pane": pane}),
        );
        let launch = self.owned_checked(pane)?;
        launch.history_queries.push(query);
        let page = launch
            .history
            .clone()
            .unwrap_or_else(|| serde_json::json!({"entries": [], "next": null}));
        Ok(page.to_string())
    }
}