Skip to main content

byob_sheets/
lib.rs

1//! byob's spreadsheets: the bundled `sheets` plugin's backend, in-process, on the IronCalc
2//! engine: tools to create, describe, read, write, fill, restructure and format sheets, with
3//! lints, artifact versions, drafts and an editable grid view. The plugin's manifest
4//! (`crates/bundled/plugins/sheets`) names it with `"backend": {"native": "sheets"}`; the app
5//! registers [`factory`] under [`ID`].
6//!
7//! It implements [`byob_plugins::native::NativeBackend`], so the engine hosts it like a
8//! process backend (its own thread, restarted after a panic).
9#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable))]
10
11pub mod book;
12pub mod charts;
13pub mod refs;
14pub mod store;
15pub mod text;
16pub mod tools;
17pub mod view;
18
19use std::sync::Arc;
20
21use byob_plugins::native::{NativeBackend, NativeFactory, Outbox};
22use serde_json::{Value, json};
23
24use crate::store::Store;
25use crate::text::repr_str;
26use crate::tools::Ctx;
27use crate::view::Views;
28
29/// The id manifests name (`"backend": {"native": "sheets"}`).
30pub const ID: &str = "sheets";
31/// The artifact-site view it draws.
32const VIEW: &str = "sheet";
33/// Artifact views drawn again after changes (the newest ones).
34const MAX_ARTIFACT_KEYS: usize = 16;
35
36/// A problem the model can act on (its text is a plain sentence).
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub enum SheetError {
39    Msg(String),
40    /// The engine refused (an IronCalc error).
41    Engine(String),
42    /// A file couldn't be read or written.
43    Io(String),
44}
45
46impl SheetError {
47    pub fn text(&self) -> String {
48        match self {
49            Self::Msg(m) => m.clone(),
50            Self::Engine(e) => format!("The spreadsheet engine refused: {e}."),
51            Self::Io(e) => format!("A file couldn't be read or written: {e}."),
52        }
53    }
54}
55
56/// The tools it serves, in the manifest's order.
57pub const TOOLS: [&str; 8] = ["create_sheet", "describe_sheet", "read_cells", "write_cells", "fill", "edit_sheet", "format_cells", "chart_sheet"];
58
59/// The sheets backend's state: workbooks, views, and the artifacts its views show.
60#[derive(Default)]
61pub struct Sheets {
62    store: Store,
63    views: Views,
64    /// Keys of the drawn views with the artifact byob last said each shows (oldest first).
65    drawn: Vec<(String, Value)>,
66}
67
68/// Makes a fresh backend (registered as [`ID`]).
69pub fn factory() -> NativeFactory {
70    Arc::new(|| Box::new(Sheets::default()) as Box<dyn NativeBackend>)
71}
72
73impl Sheets {
74    /// A tool call: its result, or the error sentence.
75    pub fn tool(&mut self, name: &str, args: &Value, workspace: &str, chat: Option<&str>) -> Result<Value, String> {
76        let cx = Ctx { workspace, chat };
77        let empty = json!({});
78        let args = if args.is_object() { args } else { &empty };
79        let st = &mut self.store;
80        let r = match name {
81            "create_sheet" => tools::create_sheet(st, &cx, args),
82            "describe_sheet" => tools::describe_sheet(st, &cx, args),
83            "read_cells" => tools::read_cells(st, &cx, args),
84            "write_cells" => tools::write_cells(st, &cx, args),
85            "fill" => tools::fill(st, &cx, args),
86            "edit_sheet" => tools::edit_sheet(st, &cx, args),
87            "format_cells" => tools::format_cells(st, &cx, args),
88            "chart_sheet" => charts::chart_sheet(st, &cx, args),
89            other => return Err(format!("this backend has no tool {} (known: {})", repr_str(other), TOOLS.join(", "))),
90        };
91        r.map_err(|e| e.text())
92    }
93
94    /// Remember the artifact byob said view key `key` shows.
95    fn remember(&mut self, key: &str, params: &Value) {
96        let Some(a) = params.get("artifact").filter(|a| a.is_object()) else {
97            if !self.drawn.iter().any(|(k, _)| k == key) {
98                self.drawn.push((key.to_owned(), Value::Null));
99            }
100            return;
101        };
102        match self.drawn.iter_mut().find(|(k, _)| k == key) {
103            Some(slot) => slot.1 = a.clone(),
104            None => self.drawn.push((key.to_owned(), a.clone())),
105        }
106        while self.drawn.iter().filter(|(_, a)| a.is_object()).count() > MAX_ARTIFACT_KEYS {
107            if let Some(i) = self.drawn.iter().position(|(_, a)| a.is_object()) {
108                self.drawn.remove(i);
109            }
110        }
111    }
112
113    fn artifact_of(&self, key: &str) -> Option<Value> {
114        self.drawn.iter().find(|(k, _)| k == key).map(|(_, a)| a.clone()).filter(Value::is_object)
115    }
116
117    fn draw(&mut self, key: &str) -> Value {
118        let a = self.artifact_of(key);
119        self.views.draw(&mut self.store, a.as_ref())
120    }
121
122    /// Draw every view again and send it (after a tool call or a view event).
123    fn refresh(&mut self, out: &Outbox) {
124        let mut keys: Vec<String> = self.drawn.iter().map(|(k, _)| k.clone()).collect();
125        keys.sort();
126        for key in keys {
127            let tree = self.draw(&key);
128            out.view(VIEW, &key, tree);
129        }
130    }
131}
132
133impl NativeBackend for Sheets {
134    fn event(&mut self, ev: &Value, out: &Outbox) {
135        match ev.get("event").and_then(Value::as_str).unwrap_or_default() {
136            "view" => {
137                let view = ev.get("view").and_then(Value::as_str).unwrap_or_default();
138                let key = ev.get("key").and_then(Value::as_str).unwrap_or_default().to_owned();
139                if view != VIEW {
140                    out.fault(&format!("view {view}: nothing handles its events"));
141                    self.refresh(out);
142                    return;
143                }
144                self.remember(&key, ev);
145                let a = ev.get("artifact").filter(|a| a.is_object()).cloned().or_else(|| self.artifact_of(&key));
146                if let Some(a) = a
147                    && let Err(e) = self.views.event(&mut self.store, ev, &a, out)
148                {
149                    let action = ev.get("action").and_then(Value::as_str).unwrap_or_default();
150                    out.fault(&format!("view {view}: the event handler failed on {}:\n{}", repr_str(action), e.text()));
151                }
152                self.refresh(out);
153            }
154            "client" => self.refresh(out),
155            // byob undid versions of an artifact: its workbook in memory holds what was
156            // taken back, so the next use loads what is on disk now.
157            "artifact_updated" if ev.get("undone").and_then(Value::as_bool) == Some(true) => {
158                if let Some(aid) = ev.get("artifact").and_then(Value::as_str) {
159                    self.store.forget(aid);
160                }
161                self.refresh(out);
162            }
163            "web" => {
164                out.fault(&format!("web view {}: nothing handles its messages", ev.get("view").map(text::repr).unwrap_or_default()));
165                self.refresh(out);
166            }
167            _ => {}
168        }
169    }
170
171    fn request(&mut self, method: &str, params: &Value, _out: &Outbox) -> Result<Value, String> {
172        match method {
173            "tool" => {
174                let name = params.get("name").and_then(Value::as_str).unwrap_or_default();
175                let ws = params.get("workspace").and_then(Value::as_str).unwrap_or_default();
176                let chat = params.get("chat").and_then(Value::as_str);
177                self.tool(name, params.get("args").unwrap_or(&Value::Null), ws, chat)
178            }
179            "view" => {
180                let view = params.get("view").and_then(Value::as_str).unwrap_or_default();
181                if view != VIEW {
182                    return Err(format!("this backend draws no view {}", repr_str(view)));
183                }
184                let key = params.get("key").and_then(Value::as_str).unwrap_or_default().to_owned();
185                self.remember(&key, params);
186                Ok(self.draw(&key))
187            }
188            "hook" => Ok(json!({"action": "continue"})),
189            other => Err(format!("unknown request {}", repr_str(other))),
190        }
191    }
192
193    fn after_request(&mut self, method: &str, out: &Outbox) {
194        if method == "tool" {
195            self.refresh(out);
196        }
197    }
198
199    fn shutdown(&mut self) {
200        self.store.cleanup();
201    }
202}