Skip to main content

byob_protocol/
artifact.rs

1//! Artifacts: files the model makes that live beside the conversation — a markdown report,
2//! a single-file HTML app, a chart, an image, any other text file — and that are versioned
3//! and exportable.
4//!
5//! What an artifact is, is an open **content type** ([`Artifact::content_type`], e.g.
6//! `text/markdown`, `text/html`, [`TYPE_CHART`], `image/png`, `text/plain`), which the
7//! engine resolves from the file name through its registry of artifact types (built-ins and,
8//! later, plugins' registrations). Clients pick a renderer by it and fall back to showing the
9//! text source for types they don't know. [`ArtifactKind`] is the closed set older clients
10//! understand; the engine still sends it (unknown types as [`ArtifactKind::Text`]) and a
11//! client of an older engine derives the type from it.
12//!
13//! Every version is a separate file in the chat's workspace (normally
14//! `.byob/artifacts/<id>/v<n>.<ext>`; charts and images that tools made elsewhere are
15//! adopted where they are). Steps that made or changed one carry an [`ArtifactRef`]; clients
16//! get the chat's artifacts in [`crate::ServerMsg::Artifacts`] and fetch a version's bytes
17//! with [`crate::ClientMsg::GetArtifact`] (for display and export).
18
19use serde::{Deserialize, Serialize};
20
21/// Largest artifact version sent to a client in one [`crate::ServerMsg::ArtifactFile`]
22/// (base64 makes it 4/3 bigger, still well inside a frame).
23pub const MAX_ARTIFACT_SEND_BYTES: usize = 2 * 1024 * 1024;
24
25/// Content types of byob's built-in artifact types.
26pub const TYPE_MARKDOWN: &str = "text/markdown";
27pub const TYPE_HTML: &str = "text/html";
28pub const TYPE_CHART: &str = "application/vnd.byob.chart+json";
29pub const TYPE_PNG: &str = "image/png";
30pub const TYPE_JPEG: &str = "image/jpeg";
31/// Any other text file, and the fallback for types nobody registered.
32pub const TYPE_TEXT: &str = "text/plain";
33
34/// Longest content type.
35pub const MAX_CONTENT_TYPE_CHARS: usize = 100;
36
37/// A content type is `type/subtype`, lowercase ASCII letters, digits and `.+-_` (no
38/// parameters): a lookup key, safe in a header.
39pub fn valid_content_type(t: &str) -> bool {
40    let ok = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'.' | b'+' | b'-' | b'_'));
41    t.len() <= MAX_CONTENT_TYPE_CHARS && t.split_once('/').is_some_and(|(a, b)| ok(a) && ok(b))
42}
43
44/// The `Content-Type` to serve or save a version of `content_type` with: text gets a
45/// charset, structured JSON (`…+json`) is plain `application/json`.
46pub fn mime(content_type: &str) -> String {
47    if !valid_content_type(content_type) {
48        "application/octet-stream".to_owned()
49    } else if content_type.starts_with("text/") {
50        format!("{content_type}; charset=utf-8")
51    } else if content_type.ends_with("+json") {
52        "application/json".to_owned()
53    } else {
54        content_type.to_owned()
55    }
56}
57
58/// What an artifact is, as clients of protocol 13.0 knew it (see the module docs).
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
60#[serde(rename_all = "snake_case")]
61pub enum ArtifactKind {
62    /// `.md`: rendered, with a source view.
63    Markdown,
64    /// `.html`: a single-file app (HTML + CSS + JS), run sandboxed.
65    Html,
66    /// `.chart.json`: drawn natively.
67    Chart,
68    /// PNG or JPEG.
69    Image,
70    /// Any other text file (csv, json, py, svg source…), shown as source. Also any kind a
71    /// newer engine sends that this client doesn't know.
72    #[serde(other)]
73    Text,
74}
75
76impl ArtifactKind {
77    /// The content type this kind stands for (`filename` tells PNG from JPEG).
78    pub fn content_type(self, filename: &str) -> &'static str {
79        match self {
80            Self::Markdown => TYPE_MARKDOWN,
81            Self::Html => TYPE_HTML,
82            Self::Chart => TYPE_CHART,
83            Self::Image if filename.to_ascii_lowercase().ends_with(".png") => TYPE_PNG,
84            Self::Image => TYPE_JPEG,
85            Self::Text => TYPE_TEXT,
86        }
87    }
88}
89
90/// One saved version of an artifact.
91#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
92pub struct ArtifactVersion {
93    /// 1, 2, 3… (never reused).
94    pub n: u32,
95    /// Workspace-relative path of this version's file.
96    pub path: String,
97    /// Milliseconds since the Unix epoch.
98    pub created_at: i64,
99    /// What changed, in the model's words ("button is blue now").
100    #[serde(default)]
101    pub note: String,
102    #[serde(default)]
103    pub size: u64,
104}
105
106#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
107pub struct Artifact {
108    /// `[a-z0-9-]`, unique in the workspace.
109    pub id: String,
110    /// For clients of protocol 13.0; [`Artifact::content_type`] is what it is.
111    pub kind: ArtifactKind,
112    /// What it is (13.1+; empty from older engines and in older index files: then
113    /// [`Artifact::content_type`] derives it from `kind`).
114    #[serde(default, skip_serializing_if = "String::is_empty")]
115    pub content_type: String,
116    pub title: String,
117    /// Name to export it as, e.g. `loan-calculator.html`.
118    pub filename: String,
119    /// Oldest first; never empty.
120    pub versions: Vec<ArtifactVersion>,
121}
122
123impl Artifact {
124    /// Its content type: the one the engine sent if it is well-formed, else the one its
125    /// [`ArtifactKind`] stands for.
126    pub fn content_type(&self) -> &str {
127        if valid_content_type(&self.content_type) { &self.content_type } else { self.kind.content_type(&self.filename) }
128    }
129
130    pub fn latest(&self) -> Option<&ArtifactVersion> {
131        self.versions.iter().max_by_key(|v| v.n)
132    }
133
134    pub fn version(&self, n: u32) -> Option<&ArtifactVersion> {
135        self.versions.iter().find(|v| v.n == n)
136    }
137}
138
139/// "This step made version `version` of artifact `id`."
140#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
141pub struct ArtifactRef {
142    pub id: String,
143    pub version: u32,
144}
145
146/// An artifact id is safe to use as a folder name and a URL segment.
147pub fn valid_id(id: &str) -> bool {
148    (1..=64).contains(&id.len()) && id.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') && !id.starts_with('-')
149}
150
151/// The theme an HTML app is given, as CSS custom properties (`--byob-bg`, …). Apps are told
152/// to style themselves with these so they match the window. Additive: names are only ever
153/// appended (the artifact helper accepts lowercase letters and dashes only, so no digits).
154pub const THEME_VARS: [&str; 26] = [
155    "--byob-bg",
156    "--byob-surface",
157    "--byob-fg",
158    "--byob-muted",
159    "--byob-accent",
160    "--byob-on-accent",
161    "--byob-border",
162    "--byob-danger",
163    "--byob-success",
164    "--byob-warning",
165    "--byob-link",
166    "--byob-strong",
167    "--byob-faint",
168    "--byob-panel",
169    "--byob-field",
170    "--byob-code-bg",
171    "--byob-code-fg",
172    "--byob-radius",
173    "--byob-chart-a",
174    "--byob-chart-b",
175    "--byob-chart-c",
176    "--byob-chart-d",
177    "--byob-chart-e",
178    "--byob-chart-f",
179    "--byob-chart-g",
180    "--byob-chart-h",
181];
182
183#[cfg(test)]
184mod tests {
185    use super::*;
186
187    #[test]
188    fn content_types_and_their_fallbacks() {
189        let a = |kind, content_type: &str, filename: &str| Artifact {
190            id: "a".into(),
191            kind,
192            content_type: content_type.into(),
193            title: "A".into(),
194            filename: filename.into(),
195            versions: vec![],
196        };
197        // From a 13.1 engine: the type it sent, whatever the kind says.
198        assert_eq!(a(ArtifactKind::Text, "application/vnd.acme.sheet+json", "x.sheet").content_type(), "application/vnd.acme.sheet+json");
199        // From an older engine (or index file): derived from the kind.
200        assert_eq!(a(ArtifactKind::Image, "", "p.PNG").content_type(), TYPE_PNG);
201        assert_eq!(a(ArtifactKind::Image, "", "p.jpg").content_type(), TYPE_JPEG);
202        assert_eq!(a(ArtifactKind::Chart, "", "s.chart.json").content_type(), TYPE_CHART);
203        // Garbage is ignored.
204        assert_eq!(a(ArtifactKind::Html, "Text/HTML; x=<y>", "a.html").content_type(), TYPE_HTML);
205        assert!(valid_content_type("text/x-python") && !valid_content_type("text") && !valid_content_type("/x"));
206        assert!(!valid_content_type(&format!("a/{}", "b".repeat(100))));
207        assert_eq!(mime(TYPE_MARKDOWN), "text/markdown; charset=utf-8");
208        assert_eq!(mime(TYPE_CHART), "application/json");
209        assert_eq!(mime(TYPE_PNG), "image/png");
210        assert_eq!(mime("bad"), "application/octet-stream");
211        // Not sent when empty; old JSON without it parses.
212        let json = serde_json::to_string(&a(ArtifactKind::Text, "", "n")).unwrap();
213        assert!(!json.contains("content_type"));
214        let back: Artifact = serde_json::from_str(&json).unwrap();
215        assert_eq!(back.content_type(), TYPE_TEXT);
216    }
217
218    #[test]
219    fn ids() {
220        assert!(valid_id("loan-calculator-3f2a"));
221        for bad in ["", "-x", "A", "a/b", "..", "a b", &"x".repeat(65)] {
222            assert!(!valid_id(bad), "{bad}");
223        }
224    }
225
226    #[test]
227    fn latest_and_lookup() {
228        let v = |n| ArtifactVersion { n, path: format!("v{n}"), created_at: 0, note: String::new(), size: 1 };
229        let a = Artifact {
230            id: "a".into(),
231            kind: ArtifactKind::Html,
232            content_type: TYPE_HTML.into(),
233            title: "A".into(),
234            filename: "a.html".into(),
235            versions: vec![v(1), v(3), v(2)],
236        };
237        assert_eq!(a.latest().map(|v| v.n), Some(3));
238        assert_eq!(a.version(2).map(|v| v.path.as_str()), Some("v2"));
239        assert!(a.version(9).is_none());
240    }
241}